您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python子进程超时?

Python子进程超时?

我会建议采取看看Timerthreading的模块。我用它来实现超时Popen

首先,创建一个回调:

def timeout( p ):
    if p.poll() is None:
        print 'Error: process taking too long to complete--terminating'
        p.kill()

然后打开过程:

proc = Popen( ... )

然后创建一个计时器,该计时器将调用回调,并将过程传递给它。

t = threading.Timer( 10.0, timeout, [proc] )
t.start()
t.join()

在程序后面的某个位置,您可能需要添加以下行:

t.cancel()

否则,python程序将继续运行,直到计时器运行完毕。

编辑:我被告知,subprocesspp.poll()和条件之间可能存在可能终止的竞争条件p.kill()。我相信以下代码可以解决此问题:

import errno

def timeout( p ):
    if p.poll() is None:
        try:
            p.kill()
            print 'Error: process taking too long to complete--terminating'
        except OSError as e:
            if e.errno != errno.ESRCH:
                raise

尽管您可能希望清除异常处理以专门处理子过程已经正常终止时发生的特定异常。

python 2022/1/1 18:43:57 有291人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶