Seb*_*erk 7 python linux subprocess os.system
我想用一个程序启动几个子进程,即一个模块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))
Run Code Online (Sandbox Code Playgroud)
bar.py:
import time
print("bla")
time.sleep(10) % within this time, the process should be killed
print("blubb")
Run Code Online (Sandbox Code Playgroud)
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.
Run Code Online (Sandbox Code Playgroud)
要终止该过程,您可以使用terminate方法或kill.(无需使用外部kill程序)
proc.terminate()
Run Code Online (Sandbox Code Playgroud)