您可以使用terminate(优雅)和Popen对象的terminate方法终止创建的进程。像firefox这样的程序往往会立即返回,所以这并不总是有效的。但总的想法是:import subprocess
import threading
def kill_this(procs, hard=False):
"""kill the Popen processes in the list"""
for proc in procs:
if hard:
proc.kill()
else:
proc.terminate()
class A(threading.Thread):
"""Runs tor and firefox, with graceful termination in 10 seconds and
a hard kill in 20 seconds as needed"""
def __init__(self):
Thread.__init__(self)
def run(self):
# create processes
tor = subprocess.Popen(['tor'])
firefox = subprocess.Popen(['firefox'])
# setup timers to kill 'em
soft = threading.Timer(10, kill_this, ((tor, firefox), False))
hard = threading.Timer(20, kill_this, ((tor, firefox), True))
# wait for process exit
tor.wait()
firefox.wait()
soft.cancel()
hard.cancel()
或者,您可以使用系统调用来获取要终止的进程的pid,然后将kill_this转换为使用不同的API:
^{pr2}$