我正在尝试创建一个执行此操作的程序:
我已经尝试了很长时间,这些是我目前的问题:
我已经知道如何使用subprocess.Popen调用进程以及如何使用命令行函数来终止它们。我也知道如何获得PID。
这是我的实际代码:
import threading, subprocess, shlex
class Prog1(threading.Thread):
def __init__(self, arg=''):
self.arg = arg
threading.Thread.__init__(self)
def run(self):
p = subprocess.Popen(shelx.split(self.arg))
global p.pid
subprocess.Popen(shelx.split("kill -9 " + q.pid))
class Prog2(threading.Thread):
def __init__(self, arg=''):
self.arg = arg
threading.Thread.__init__(self)
def run(self):
q = subprocess.Popen(shelx.split(self.arg))
global q.pid
subprocess.Popen(shelx.split("kill -9 " + p.pid))
答案 0 :(得分:2)
on python 2.7
import thread
然后
thread.start_new_thread(funct,(param1, param2...))
对我有用,不知道杀了他们,但是从你的问题来看,这就是你被困在哪里?
在@ J.F.Sebastian的反馈之后,我开始研究新的(旧的)线程模块并修复我之前的代码,以及我目前正在处理的代码。
import threading
t=threading.Thread(target=fuct, args=(param1, param2...)).start()
不知道这是否是最强大的使用方法,但我只知道它存在了25分钟:)
答案 1 :(得分:1)
要杀死所有进程,如果其中任何进程已退出,则可以在单独的线程中为每个进程调用process.wait()
,并使用threading.Event
表示是否有任何进程结束:
#!/usr/bin/env python
import shlex
import subprocess
import threading
def kill_all(processes):
for p in processes:
try:
if p.poll() is None:
p.kill() # note: it may leave orphans
p.wait()
except: # pylint: disable=W0702
pass # ignore whatever it is (including SIGINT)
def wait(process, exit_event):
try:
process.wait()
finally:
exit_event.set() # signal the process has exited
def main():
# start processes
cmd = "/bin/bash -c 'echo start {0}; sleep {0}; echo done {0}'".format
processes = []
for i in range(1, 3):
try:
processes.append(subprocess.Popen(shlex.split(cmd(i))))
except EnvironmentError:
kill_all(processes) # failed to start some process; kill'em all
return 1 # error
# wait until at least one process finishes
exit_event = threading.Event()
for p in processes:
threading.Thread(target=wait, args=(p, exit_event)).start()
exit_event.wait()
kill_all(processes)
if __name__ == "__main__":
import sys
sys.exit(main())
start 1
start 2
done 1