我有一个线程调用 Popen
从命令行实用程序中获取字符串。直到一些非常非常滞后的网络数据到达时,这个命令行函数才会返回。有时可能需要几分钟,有时不到一秒钟。
如果用户愿意,他们可以取消等待这个数据。在这种情况下,停止线程的正确方法是什么?
class CommThread( threading.Thread ):
def __init__(self):
self.stdout = None
self.stderr = None
self.command = None
threading.Thread.__init__(self)
def run(self):
if self.command is not None:
p = Popen( self.command.split(), shell=False, stdout=PIPE, stderr=PIPE)
self.stdout, self.stderr = p.communicate()
最佳答案
您可以通过调用p.terminate()
来终止子进程。这可以从另一个线程完成。
关于python - 停止等待 popen 的 python 线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8440565/