Nap*_*ead 5 python subprocess timeout stdout python-3.x
需要:
Python 3子进程模块内置了超时,我也尝试使用计时器和使用线程实现超时,但它不能与输出一起使用.readline()阻止与否?readlines()肯定会在吐出所有输出之前等待进程结束,这不是我需要的(我需要继续).
我接近切换到node.js :-(
我会使用 asyncio 来完成此类任务。
从进程中读取 IO,就像这个接受的 anwser 中那样: How to Stream stdout/stderr from a child process using asyncio, and acquire its exit code after?
(我不想在这里完全复制)
将其包装在超时中:
async def killer(trans, timeout):
await asyncio.sleep(timeout)
trans.kill()
print ('killed!!')
trans, *other_stuff = loop.run_until_complete(
loop.subprocess_exec(
SubprocessProtocol, 'py', '-3', '-c', 'import time; time.sleep(6); print("Yay!")' ,
)
)
asyncio.ensure_future(killer(trans, 5)) # 5 seconds timeout for the kill
loop.run_forever()
Run Code Online (Sandbox Code Playgroud)
玩得开心 ...
| 归档时间: |
|
| 查看次数: |
712 次 |
| 最近记录: |