2024-06-23 18:44:30 发布
网友
需要:
python3subprocess模块内置了timeout,我自己也尝试过使用计时器和线程实现timeout,但它不能处理输出。readline()是否阻塞?readlines()在输出所有输出之前,肯定在等待进程结束,这不是我需要的(我需要继续)。在
readline()
readlines()
我马上就要转到节点.js:-(
使用下面的2python脚本。在
硕士.py将使用Popen启动一个新进程,并将启动一个观察线程,该线程将在3.0秒后终止该进程。
Popen
3.0
如果写入stdout的数据中没有新行,则从属服务器必须调用flush方法(在windows上,'\n'也会导致刷新)。
stdout
'\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)
Be careful the time module is not a high precision timer.
time
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
对于这种任务,我会使用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()
玩得开心。。。在
使用下面的2python脚本。在
硕士.py将使用
Popen
启动一个新进程,并将启动一个观察线程,该线程将在3.0
秒后终止该进程。如果写入
stdout
的数据中没有新行,则从属服务器必须调用flush方法(在windows上,'\n'
也会导致刷新)。硕士.py
从属.py
^{pr2}$对于这种任务,我会使用asyncio。在
从进程中读取IO,如下所示: How to stream stdout/stderr from a child process using asyncio, and obtain its exit code after?
(我不想完全复制到这里)
超时结束:
玩得开心。。。在
相关问题 更多 >
编程相关推荐