如何使用 asyncio 优雅地超时

How to gracefully timeout with asyncio

所以在添加 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>

loop.run_until_complete 接受等待的东西:协程或未来。您传递的函数结果 return 什么都没有。

您应该将 get_coros() 更改为实际的 return 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()

更新:

我现在无法验证我的猜测,但就是这样:虽然 asyncio.wait_for(fut, timeout=5) 会在 5 秒后取消任务,但不会 terminate 该过程。您可以手动执行此操作:

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