【问题标题】:stopping a python thread waiting for popen?停止等待popen的python线程?
【发布时间】:2011-12-09 03:08:19
【问题描述】:

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

【问题讨论】:

    标签: python multithreading popen


    【解决方案1】:

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

    【讨论】:

      【解决方案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()

      【讨论】:

        猜你喜欢
        • 2014-08-22
        • 1970-01-01
        • 1970-01-01
        • 2010-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-11
        • 2020-12-17
        相关资源
        最近更新 更多