停止python线程等待popen?

时间:2011-12-09 03:08:19

标签: python multithreading popen

我有一个调用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()

2 个答案:

答案 0 :(得分:3)

您可以通过调用p.terminate()来终止子进程。这可以从另一个线程完成。

答案 1 :(得分:2)

使用Popen.terminate()这里是文档http://docs.python.org/library/subprocess.html

你的代码应该是这样的:

def run(self):
    if self.command is not None:
        self.process = Popen( self.command.split(), shell=False, stdout=PIPE, stderr=PIPE)

def stop(self):
    if self.process is not None:
        self.process.terminate()

你可以在其他代码块中调用CommThread.stop()

相关问题