如何使用超时运行进程并在运行时仍然获得stdout

Nap*_*ead 5 python subprocess timeout stdout python-3.x

需要:

  1. X秒后超时,如果在进程正常结束之前达到超时,则终止进程(以及它打开的所有进程).
  2. 在运行时读取正在进行的输
  3. 使用产生输出的过程,不产生输出的过程,以及产生输出的过程,然后停止产生输出(例如卡住).
  4. 在Windows上运行.
  5. 在Python 3.5.2上运行.

Python 3子进程模块内置了超时,我也尝试使用计时器和使用线程实现超时,但它不能与输出一起使用.readline()阻止与否?readlines()肯定会在吐出所有输出之前等待进程结束,这不是我需要的(我需要继续).

我接近切换到node.js :-(

Yoa*_*ner 3

我会使用 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)

玩得开心 ...