[英]python Popen: How do I stop(kill) the subprocess that created using Popen?
I need to stop the service(runs at the background in another thread) that I issued through Popen in python after I got the result, but the following approach failed(just use ping
for the sake of explanation):得到结果后,我需要停止我在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()
After running above program, when I pgrep for ping
, it's still there.运行上面的程序后,当我 pgrep for
ping
时,它仍然存在。 How can I kill the subprocess opened by Popen?如何杀死Popen打开的子进程? Thanks.
谢谢。
PS: I also tried result.terminate(), but doesn't really solve the problem either. PS:我也试过result.terminate(),也没有真正解决问题。
You don't really need to run a subprocess from a thread.您实际上不需要从线程运行子进程。 Try running the subprocess without a thread.
尝试在没有线程的情况下运行子进程。 Also, you specified shell=True, so it's running the command in a shell. So there are two new processes, the shell and the command.
此外,您指定了 shell=True,因此它在 shell 中运行命令。因此有两个新进程,即 shell 和命令。 You can also remove the shell by making shell=False.
您还可以通过设置 shell=False 来删除 shell。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.