The communicate() and wait() methods don’t take a timeout parameter: use the wait_for() function
使用wait_for()对communicate()施加超时很容易,但是我找不到从中断的communicate()调用中检索部分结果的方法,communicate()的后续调用也不会返回丢失的部分。在
示例脚本:#! /usr/bin/env python3
import asyncio
async def communicate_short(loop):
p = await asyncio.create_subprocess_exec('ping', '127.0.0.1', '-n', '4', stdout=asyncio.subprocess.PIPE)
# For Linux: use '-c' instead of '-n'
try:
# 2 seconds timeout
res = await asyncio.wait_for(p.communicate(), 2)
except asyncio.TimeoutError as e:
# After timeout happens:
# How do I get the subprocess's STDOUT up to this point?
try:
print(res[0].decode('utf-8'))
# Will raise NameError since the communicate() call did not complete
except NameError as e:
print('NameError: %s' % e)
res = await p.communicate()
print(res[0].decode('utf-8'))
# Only prints the later half of ping's STDOUT
if __name__ == '__main__':
loop = asyncio.ProactorEventLoop()
asyncio.set_event_loop(loop)
# For Linux: just do loop = asyncio.get_event_loop()
loop.run_until_complete(communicate_short(loop))
示例脚本的输出:
^{pr2}$
请注意,只打印最后2个数据包。前2个包的输出丢失。在
那么,如何在超时发生之前从子进程获取输出呢?在
编辑:更准确地说,理想情况下,我要找的东西:做communicate()所做的事情,即异步地写入子进程的STDIN并读取其STDOUT和STDERR,而不会出现死锁(that the docs ominously warn about);
具有可配置的总超时,因此当子进程终止或达到超时时,将返回到目前为止接收到的STDOUT和STDERR。
看起来这样的东西还不存在,人们必须实现它。在