【问题标题】:How to timeout when I use subprocess [duplicate]使用子进程时如何超时[重复]
【发布时间】:2015-06-01 17:03:00
【问题描述】:

我在 Python2.7 中使用 sub.Popen

但是,Python3有超时,Python2.7不行。

这是我的sn-p。

proc = sub.Popen(['some command', 'some params'], stdout=sub.PIPE)    

try:
    for row in proc.stdout:
        print row.rstrip()   # process here
        result = str(row.rstrip())
        count += 1
        if count > 10:
            break
except:
    print 'tcpdump error'
    proc.terminate()

如何设置超时。

【问题讨论】:

    标签: python process


    【解决方案1】:

    基于 this blog post 代码,您可以使用 threading.Thread 进行一些更改:

    from threading import Thread
    from subprocess import PIPE, Popen
    
    
    def proc_timeout(secs, *args):
        proc = Popen(args, stderr=PIPE, stdout=PIPE)
        proc_thread = Thread(target=proc.wait)
        proc_thread.start()
        proc_thread.join(secs)
        if proc_thread.is_alive():
            try:
                proc.kill()
            except OSError:
                return proc.returncode
            print('Process #{} killed after {} seconds'.format(proc.pid, secs))
        return proc
    

    你应该只在你的 try/except 中捕获特定的异常,不要试图全部捕获它们。

    【讨论】:

    • @shinriyo,不用担心,没有过度测试代码,但应该做你想做的。如果命令在秒内没有返回,它将引发 SubprocessTimeoutError
    • 嘿,设法使用这个,但我找不到用这个记录 STDOUT 的方法。 proc = Popen(args, stderr=PIPE, stdout=PIPE) 不会让你从标准输出读取。它让我得到:从关闭的文件中读取错误。有什么办法吗?
    • 你运行得如何,我编辑了答案,删除了 raise,因为你可能总是希望在超时之前输出
    • 我实际上是在使用加注。看起来它有效。太好了!
    【解决方案2】:

    如果您使用的是 linux(或可能是其他 unix 衍生产品),您可以使用timeout 命令。例如:

    subprocess.Popen(['timeout', '5', 'sleep', '20']).wait()
    

    将在 5 秒后超时。 proc.communicate() 也应该使用这种方法。

    可以在此相关问题中找到其他替代方法:Using module 'subprocess' with timeout

    【讨论】:

    • 感谢您的回复。我不知道 linux 命令“超时”。
    猜你喜欢
    • 1970-01-01
    • 2011-04-22
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    • 2012-06-09
    • 2011-04-13
    • 1970-01-01
    相关资源
    最近更新 更多