python - 停止等待 popen 的 python 线程?

标签 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()

最佳答案

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

关于python - 停止等待 popen 的 python 线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8440565/

相关文章:

python - 在 message.content.find 上 Disord.py 双输出

python - 如何使用 uwsgi web.py 运行后台功能?

python - subprocess.Popen execve() arg 3 包含一个非字符串值

Python3 FileNotFoundError 任何文件,使用 subprocess.popen()

python - python中的SQL双连接

python - matplotlib 中的偏移辅助轴

Python,如何在函数之外使用函数的一部分

c# - 实现多线程后与数据库的连接丢失

c# - 在 Parallel.Invoke 中处理大型记录集时出现错误 “A task was canceled.”

Python Popen shell 脚本但失败