如何在超时的情况下运行进程,但仍在runtim获取stdout

2024-06-23 18:44:30 发布

您现在位置:Python中文网/ 问答频道 /正文

需要:

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

python3subprocess模块内置了timeout,我自己也尝试过使用计时器和线程实现timeout,但它不能处理输出。readline()是否阻塞?readlines()在输出所有输出之前,肯定在等待进程结束,这不是我需要的(我需要继续)。在

我马上就要转到节点.js:-(


Tags: 模块readlineget节点进程过程windowsjs
2条回答

使用下面的2python脚本。在

  • 硕士.py将使用Popen启动一个新进程,并将启动一个观察线程,该线程将在3.0秒后终止该进程。

  • 如果写入stdout的数据中没有新行,则从属服务器必须调用flush方法(在windows上,'\n'也会导致刷新)。

Be careful the time module is not a high precision timer.

The load time of the process can be longer than 3.0 seconds in extreme cases (reading an executable from a flash drive having USB 1.0)

硕士.py

import subprocess, threading, time

def watcher(proc, delay):
    time.sleep(delay)
    proc.kill()

proc = subprocess.Popen('python Slave.py', stdout = subprocess.PIPE)
threading.Thread(target = watcher, args = (proc, 3.0)).start()

data = bytearray()

while proc:
    chunk = proc.stdout.read(1)
    if not chunk:
        break
    data.extend(chunk)
    print(data)

从属.py

^{pr2}$

对于这种任务,我会使用asyncio。在

从进程中读取IO,如下所示: How to stream stdout/stderr from a child process using asyncio, and obtain 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()

玩得开心。。。在

相关问题 更多 >

    热门问题