python await 超时_python3asyncio:wait帴for()communicate()超时,如何获得部分结果?...

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。

看起来这样的东西还不存在,人们必须实现它。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值