![](/img/trans.png)
[英]Gently kill a process created with Python's subprocess.Popen() in Windows
[英]python Popen: How do I stop(kill) the subprocess that created using Popen?
得到结果后,我需要停止我在python通过Popen发出的服务(在另一个线程的后台运行),但是下面的方法失败了(只是为了解释而使用ping
):
class sample(threading.Thread):
def __init__(self, command, queue):
threading.Thread.__init__(self)
self.command = command;
self.queue = queue
def run(self):
result = Popen(self.command, shell=True, stdout=PIPE, stderr=STDOUT)
while True:
output = result.stdout.readline()
if not self.queue.empty():
result.kill()
break
if output != "":
print output
else:
break
def main():
q = Queue()
command = sample("ping 127.0.0.1", q)
command.start()
time.sleep(10)
q.put("stop!")
command.join()
if __name__ == "__main__":
main()
运行上面的程序后,当我 pgrep for ping
时,它仍然存在。 如何杀死Popen打开的子进程? 谢谢。
PS:我也试过result.terminate(),也没有真正解决问题。
您实际上不需要从线程运行子进程。 尝试在没有线程的情况下运行子进程。 此外,您指定了 shell=True,因此它在 shell 中运行命令。因此有两个新进程,即 shell 和命令。 您还可以通过设置 shell=False 来删除 shell。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.