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


问题内容

我想用一个程序启动几个子流程,即一个模块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")

问题答案:

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()