[英]How to terminate a thread subprocess call and thread exit in Python?
我正在嘗試在 Python 的線程中運行子進程 Popen。 Popen 中的命令預計會連續運行以收集日志。 但是當線程外滿足條件時,我想停止 Popen 子進程,並且相應的線程也完成。 下面是一個示例代表代碼:
import threading
import subprocess
class MyClass(threading.Thread):
def __init__(self):
super(MyClass, self).__init__()
def run(self):
self.proc = subprocess.Popen("while true; do foo; sleep 2; done", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = self.proc.communicate()
myclass = MyClass()
myclass.start()
myclass.proc.kill()
print("Done")
但是在上面的代碼中,它永遠卡住了。 停止正在運行的 Popen 子進程並完成線程的正確方法是什么?
將參數preexec_fn=os.setsid
添加到您的Popen
函數中。
使用os.killpg(proc.pid, signal.SIGKILL)
通過 pid 殺死子進程。
您真正需要做的就是讓線程(即MyClass
實例)執行“終止”並使用它將等待的事件實例化MyClass
,然后在設置時終止進程。 因為我不知道foo
中有什么,所以我用一個簡單的echo hello
代替了它,並在Popen
調用上設置了text=True ,這樣 output 是 Unicode 而不是字節:
import threading
import subprocess
import time
class MyClass(threading.Thread):
def __init__(self, evt):
super(MyClass, self).__init__()
self.evt = evt
def run(self):
proc = subprocess.Popen("while true; do echo hello; sleep 2; done", shell=True, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# wait for the "kill" order:
self.evt.wait()
proc.kill()
stdout, stderr = proc.communicate()
# for demo purposes let's see what has been output:
print(stdout, end='')
evt = threading.Event()
myclass = MyClass(evt)
myclass.start()
# let the process run for 5 seconds and then give the kill order:
time.sleep(5)
print("Killing process:")
evt.set()
myclass.join()
print("Done")
印刷:
Killing process:
hello
hello
hello
Done
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.