我想用一个程序启动几个子进程,即模块 foo.py
启动多个 bar.py
实例。
因为有时我必须手动终止进程,所以我需要进程 ID 来执行 kill 命令。
即使整个设置非常“脏”,如果进程是通过 os.system
启动的,是否有一个好的 pythonic 方法来获取进程的 pid
?
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()
关于python - 如何确定通过 os.system 启动的进程的 pid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20218570/