【问题标题】:Python - kill hung process started using subprocess.PopenPython - 使用 subprocess.Popen 杀死挂起的进程
【发布时间】:2016-08-18 18:58:19
【问题描述】:

我已经使用以下方法启动了一个子进程:

proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
output = proc.communicate()[0]

有时cmd 命令会挂起,所以我的 Python 脚本此时也会挂起。

我想让它运行一段时间(10 秒?),如果我没有得到响应,那么只需终止进程并继续执行我的脚本。

我该怎么做?

【问题讨论】:

    标签: python subprocess popen kill freeze


    【解决方案1】:

    如果您使用的是 python 3,Popen.communicate 有一个超时 kwarg:

    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
    output = proc.communicate(timeout=10)[0]
    

    【讨论】:

    • 多么方便。我应该更仔细地阅读文档。
    【解决方案2】:

    来自subprocess documentation proc.terminate() 就是你要找的东西

    【讨论】:

    • 是的,我可以这样做,但不能做的是等待10秒然后选择放弃。我该怎么做?
    猜你喜欢
    • 2017-07-27
    • 1970-01-01
    • 2011-05-04
    • 2012-03-12
    • 1970-01-01
    • 2014-05-18
    • 1970-01-01
    • 2019-11-13
    • 1970-01-01
    相关资源
    最近更新 更多