python - 使用子进程时如何超时

标签 python process

我在Python2.7中使用sub.Popen

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

这是我的片段。

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

如何设置超时。

最佳答案

基于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 中捕获特定的异常,而不是 try catch 所有异常。

关于python - 使用子进程时如何超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29316426/

相关文章:

python - 将搜索结果链接到其自己的详细信息页面

jquery - 直接 LXML 或 PyQuery

linux - Linux 中的线程与进程

linux - 进程如何在 Linux 中找到动态共享库?

linux - 什么是池线程

javascript - 有什么方法可以从 HTML 文档中删除 javascript 代码吗?

python - 无法导入jupyter笔记本中已安装的包

python - 模仿方法重载是 Pythonic 吗?

linux - 如何显示自系统上次在 linux 中重新启动以来运行次数最多的程序

java - 使用InputStream读取Java进程状态,然后使用OutputStream发送命令提示符