擅长:python、mysql、java
<p>对于这种任务,我会使用asyncio。在</p>
<p>从进程中读取IO,如下所示:
<a href="https://stackoverflow.com/questions/24435987/how-to-stream-stdout-stderr-from-a-child-process-using-asyncio-and-obtain-its-e">How to stream stdout/stderr from a child process using asyncio, and obtain its exit code after?</a></p>
<p>(我不想完全复制到这里)</p>
<p>超时结束:</p>
<pre><code>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()
</code></pre>
<p>玩得开心。。。在</p>