如何确定通过os.system启动的进程的pid

发布于 2021-01-29 16:48:14

我想用一个程序启动几个子流程,即一个模块foo.py启动的多个实例bar.py

由于有时需要手动终止进程,因此我需要进程ID来执行kill命令。

即使整个安装过程很“肮脏”,但是pid如果通过进程启动,是否有一种很好的pythonic方式来获取进程os.system

foo.py:

import os
import time
os.system("python bar.py \"{0}\ &".format(str(argument)))
time.sleep(3)
pid = ???
os.system("kill -9 {0}".format(pid))

bar.py:

import time
print("bla")
time.sleep(10) % within this time, the process should be killed
print("blubb")
关注者
0
被浏览
47
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    os.system返回退出代码。它不提供子进程的pid。

    使用subprocess模块。

    import subprocess
    import time
    argument = '...'
    proc = subprocess.Popen(['python', 'bar.py', argument], shell=True)
    time.sleep(3) # <-- There's no time.wait, but time.sleep.
    pid = proc.pid # <--- access `pid` attribute to get the pid of the child process.
    

    要终止该过程,可以使用terminate方法或kill。(无需使用外部kill程序)

    proc.terminate()
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看