如何使用asyncio优雅地超时

时间:2017-07-31 23:22:14

标签: python-3.x async-await runtime-error python-asyncio timeoutexception

所以在添加try / catch块之前,当进程运行不到5分钟时,我的事件循环正常关闭,但是在添加try / catch块之后,当进程超过5分钟时我开始收到此错误

async def run_check(shell_command):
    p = await asyncio.create_subprocess_shell(shell_command,
                    stdin=PIPE, stdout=PIPE, stderr=STDOUT)
    fut = p.communicate()
    try:
        pcap_run = await asyncio.wait_for(fut, timeout=5)
    except asyncio.TimeoutError:
        pass

def get_coros():
    for pcap_loc in print_dir_cointent():
        for pcap_check in get_pcap_executables():
            tmp_coro = (run_check('{args}'
            .format(e=sys.executable, args=args)))
            if tmp_coro != False:
                coros.append(tmp_coro)
     return coros

async def main(self):
    p_coros = get_coros()
    for f in asyncio.as_completed(p_coros):
        res = await f




loop = asyncio.get_event_loop()
loop.run_until_complete(get_coros())
loop.close()

追溯:

Exception ignored in: <bound method BaseSubprocessTransport.__del__ of 
    <_UnixSubprocessTransport closed pid=171106 running stdin=
    <_UnixWritePipeTransport closing fd=8 open> stdout=<_UnixReadPipeTransport fd=9 open>>>
    Traceback (most recent call last):
      File "/usr/lib/python3.5/asyncio/base_subprocess.py", line 126, in __del__
      File "/usr/lib/python3.5/asyncio/base_subprocess.py", line 101, in close
      File "/usr/lib/python3.5/asyncio/unix_events.py", line 568, in close
      File "/usr/lib/python3.5/asyncio/unix_events.py", line 560, in write_eof
      File "/usr/lib/python3.5/asyncio/base_events.py", line 497, in call_soon
      File "/usr/lib/python3.5/asyncio/base_events.py", line 506, in _call_soon
      File "/usr/lib/python3.5/asyncio/base_events.py", line 334, in _check_closed
    RuntimeError: Event loop is closed

在执行代码的最后一行之后发生回溯。

调试日志:

DEBUG:asyncio:Using selector: EpollSelector
DEBUG:asyncio:run shell command '/local/p_check w_1.pcap --json' stdin=<pipe> stdout=stderr=<pipe>
DEBUG:asyncio:process '/local/p_check w_1.pcap --json' created: pid 171289DEBUG:asyncio:Write pipe 8 connected: (<_UnixWritePipeTransport fd=8 idle bufsize=0>, <WriteSubprocessPipeProto fd=0 pipe=<_UnixWritePipeTransport fd=8 idle bufsize=0>>)
DEBUG:asyncio:Read pipe 9 connected: (<_UnixReadPipeTransport fd=9 polling>, <ReadSubprocessPipeProto fd=1 pipe=<_UnixReadPipeTransport fd=9 polling>>) INFO:asyncio:run shell command '/local/p_check w_1.pcap --json': <_UnixSubprocessTransport pid=171289 running stdin=<_UnixWritePipeTransport fd=8 idle bufsize=0> stdout=<_UnixReadPipeTransport fd=9 polling>>
DEBUG:asyncio:<Process 171289> communicate: read stdout
INFO:asyncio:poll 4997.268 ms took 5003.093 ms: timeout
DEBUG:asyncio:Close <_UnixSelectorEventLoop running=False closed=False debug=True>

1 个答案:

答案 0 :(得分:5)

loop.run_until_complete接受一些可以接受的东西:协程或未来。你传递的函数没有返回任何结果。

您应该将get_coros()更改为实际返回coros列表:

def get_coros():
    ...
    return coros

并将该列表转换为等待逐个执行作业的列表(如果需要,可以并行执行)。例如:

async def main():
    for coro in get_coros():
        await coro

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()

<强> UPD:

很抱歉,我现在无法测试我的猜测,但现在是:asyncio.wait_for(fut, timeout=5)在5秒后取消任务,但它不会terminate处理。也许我们应该手动完成:

try:
    await asyncio.wait_for(fut, timeout=5)
except asyncio.TimeoutError:
    p.kill()
    await p.communicate()