I want to start several subprocesses with a programm, i.e. a module foo.py
starts several instances of bar.py
.
Since I sometimes have to terminate the process manually, I need the process id to perform a kill command.
Even though the whole setup is pretty “dirty”, is there a good pythonic way to obtain a process’ pid
, if the process is started via 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")
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…