[英]Start child process with subprocess.Popen and read its output while it is running
[英]Constantly print Subprocess output while process is running
要从我的 Python 脚本启动程序,我使用以下方法:
def execute(command):
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = process.communicate()[0]
exitCode = process.returncode
if (exitCode == 0):
return output
else:
raise ProcessException(command, exitCode, output)
因此,当我启动像Process.execute("mvn clean install")
这样的进程时,我的程序会一直等到进程完成,然后我才能获得程序的完整 output。 如果我正在运行一个需要一段时间才能完成的进程,这很烦人。
我可以让我的程序逐行写入进程 output 吗?
我找到了这篇可能相关的文章。
您可以在命令输出后立即使用iter处理行: lines = iter(fd.readline, "")
。 这是一个显示典型用例的完整示例(感谢@jfs 的帮助):
from __future__ import print_function # Only Python 2.x
import subprocess
def execute(cmd):
popen = subprocess.Popen(cmd, stdout=subprocess.PIPE, universal_newlines=True)
for stdout_line in iter(popen.stdout.readline, ""):
yield stdout_line
popen.stdout.close()
return_code = popen.wait()
if return_code:
raise subprocess.CalledProcessError(return_code, cmd)
# Example
for path in execute(["locate", "a"]):
print(path, end="")
在 Python 3 中刷新其标准输出缓冲区后,要逐行打印子进程的输出:
from subprocess import Popen, PIPE, CalledProcessError
with Popen(cmd, stdout=PIPE, bufsize=1, universal_newlines=True) as p:
for line in p.stdout:
print(line, end='') # process line here
if p.returncode != 0:
raise CalledProcessError(p.returncode, p.args)
注意:您不需要p.poll()
- 到达 eof 时循环结束。 而且您不需要iter(p.stdout.readline, '')
- 预读错误已在 Python 3 中修复。
好的,我设法在没有线程的情况下解决了它(任何建议为什么使用线程会更好),方法是使用这个问题中的一个片段Intercepting stdout of a subprocess while it is running
def execute(command):
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
# Poll process for new output until finished
while True:
nextline = process.stdout.readline()
if nextline == '' and process.poll() is not None:
break
sys.stdout.write(nextline)
sys.stdout.flush()
output = process.communicate()[0]
exitCode = process.returncode
if (exitCode == 0):
return output
else:
raise ProcessException(command, exitCode, output)
当您只想print
输出时,实际上有一种非常简单的方法:
import subprocess
import sys
def execute(command):
subprocess.check_call(command, shell=True, stdout=sys.stdout, stderr=subprocess.STDOUT)
在这里,我们只是将子进程指向我们自己的stdout
,并使用现有的成功或异常 api。
@tokland
尝试了您的代码并将其更正为 3.4 和 windows dir.cmd 是一个简单的 dir 命令,保存为 cmd 文件
import subprocess
c = "dir.cmd"
def execute(command):
popen = subprocess.Popen(command, stdout=subprocess.PIPE,bufsize=1)
lines_iterator = iter(popen.stdout.readline, b"")
while popen.poll() is None:
for line in lines_iterator:
nline = line.rstrip()
print(nline.decode("latin"), end = "\r\n",flush =True) # yield line
execute(c)
在 Python >= 3.5 中使用subprocess.run
对我有用:
import subprocess
cmd = 'echo foo; sleep 1; echo foo; sleep 2; echo foo'
subprocess.run(cmd, shell=True)
(在执行期间获取输出也可以在没有shell=True
的情况下工作) https://docs.python.org/3/library/subprocess.html#subprocess.run
对于尝试回答此问题以从 Python 脚本获取标准输出的任何人,请注意 Python 会缓冲其标准输出,因此可能需要一段时间才能看到标准输出。
这可以通过在目标脚本中的每个 stdout 写入后添加以下内容来纠正:
sys.stdout.flush()
要回答原始问题,IMO 的最佳方法是将子进程stdout
直接重定向到程序的stdout
(可选地,可以对stderr
执行相同操作,如下例所示)
p = Popen(cmd, stdout=sys.stdout, stderr=sys.stderr)
p.communicate()
如果有人想使用线程同时从stdout
和stderr
读取,这就是我想出的:
import threading
import subprocess
import Queue
class AsyncLineReader(threading.Thread):
def __init__(self, fd, outputQueue):
threading.Thread.__init__(self)
assert isinstance(outputQueue, Queue.Queue)
assert callable(fd.readline)
self.fd = fd
self.outputQueue = outputQueue
def run(self):
map(self.outputQueue.put, iter(self.fd.readline, ''))
def eof(self):
return not self.is_alive() and self.outputQueue.empty()
@classmethod
def getForFd(cls, fd, start=True):
queue = Queue.Queue()
reader = cls(fd, queue)
if start:
reader.start()
return reader, queue
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdoutReader, stdoutQueue) = AsyncLineReader.getForFd(process.stdout)
(stderrReader, stderrQueue) = AsyncLineReader.getForFd(process.stderr)
# Keep checking queues until there is no more output.
while not stdoutReader.eof() or not stderrReader.eof():
# Process all available lines from the stdout Queue.
while not stdoutQueue.empty():
line = stdoutQueue.get()
print 'Received stdout: ' + repr(line)
# Do stuff with stdout line.
# Process all available lines from the stderr Queue.
while not stderrQueue.empty():
line = stderrQueue.get()
print 'Received stderr: ' + repr(line)
# Do stuff with stderr line.
# Sleep for a short time to avoid excessive CPU use while waiting for data.
sleep(0.05)
print "Waiting for async readers to finish..."
stdoutReader.join()
stderrReader.join()
# Close subprocess' file descriptors.
process.stdout.close()
process.stderr.close()
print "Waiting for process to exit..."
returnCode = process.wait()
if returnCode != 0:
raise subprocess.CalledProcessError(returnCode, command)
我只是想分享这个,因为我最终在这个问题上试图做类似的事情,但没有一个答案能解决我的问题。 希望它可以帮助某人!
请注意,在我的用例中,外部进程会杀死我们Popen()
的进程。
这个 PoC 不断地读取进程的输出,并且可以在需要时访问。 只保留最后一个结果,所有其他输出都被丢弃,因此可以防止 PIPE 内存不足:
import subprocess
import time
import threading
import Queue
class FlushPipe(object):
def __init__(self):
self.command = ['python', './print_date.py']
self.process = None
self.process_output = Queue.LifoQueue(0)
self.capture_output = threading.Thread(target=self.output_reader)
def output_reader(self):
for line in iter(self.process.stdout.readline, b''):
self.process_output.put_nowait(line)
def start_process(self):
self.process = subprocess.Popen(self.command,
stdout=subprocess.PIPE)
self.capture_output.start()
def get_output_for_processing(self):
line = self.process_output.get()
print ">>>" + line
if __name__ == "__main__":
flush_pipe = FlushPipe()
flush_pipe.start_process()
now = time.time()
while time.time() - now < 10:
flush_pipe.get_output_for_processing()
time.sleep(2.5)
flush_pipe.capture_output.join(timeout=0.001)
flush_pipe.process.kill()
打印日期.py
#!/usr/bin/env python
import time
if __name__ == "__main__":
while True:
print str(time.time())
time.sleep(0.01)
输出:您可以清楚地看到只有 ~2.5s 间隔的输出,中间没有任何输出。
>>>1520535158.51
>>>1520535161.01
>>>1520535163.51
>>>1520535166.01
这至少在 Python3.4 中有效
import subprocess
process = subprocess.Popen(cmd_list, stdout=subprocess.PIPE)
for line in process.stdout:
print(line.decode().strip())
这里的答案都没有满足我的所有需求。
一点背景知识:我正在使用 ThreadPoolExecutor 来管理一个线程池,每个线程启动一个子进程并并发运行它们。 (在 Python2.7 中,但这也应该适用于较新的 3.x)。 我不想仅将线程用于输出收集,因为我希望尽可能多地用于其他事情(20 个进程的池将使用 40 个线程来运行;1 个用于进程线程,1 个用于 stdout...如果你想要 stderr 我猜还有更多)
我在这里剥离了很多异常等,所以这是基于在生产中工作的代码。 希望我没有在复制和粘贴中破坏它。 另外,非常欢迎反馈!
import time
import fcntl
import subprocess
import time
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
# Make stdout non-blocking when using read/readline
proc_stdout = proc.stdout
fl = fcntl.fcntl(proc_stdout, fcntl.F_GETFL)
fcntl.fcntl(proc_stdout, fcntl.F_SETFL, fl | os.O_NONBLOCK)
def handle_stdout(proc_stream, my_buffer, echo_streams=True, log_file=None):
"""A little inline function to handle the stdout business. """
# fcntl makes readline non-blocking so it raises an IOError when empty
try:
for s in iter(proc_stream.readline, ''): # replace '' with b'' for Python 3
my_buffer.append(s)
if echo_streams:
sys.stdout.write(s)
if log_file:
log_file.write(s)
except IOError:
pass
# The main loop while subprocess is running
stdout_parts = []
while proc.poll() is None:
handle_stdout(proc_stdout, stdout_parts)
# ...Check for other things here...
# For example, check a multiprocessor.Value('b') to proc.kill()
time.sleep(0.01)
# Not sure if this is needed, but run it again just to be sure we got it all?
handle_stdout(proc_stdout, stdout_parts)
stdout_str = "".join(stdout_parts) # Just to demo
我确定这里会增加开销,但在我的情况下这不是问题。 从功能上讲,它可以满足我的需要。 我唯一没有解决的是为什么这对日志消息非常有效,但我看到一些print
消息稍后会同时出现。
import time
import sys
import subprocess
import threading
import queue
cmd='esptool.py --chip esp8266 write_flash -z 0x1000 /home/pi/zero2/fw/base/boot_40m.bin'
cmd2='esptool.py --chip esp32 -b 115200 write_flash -z 0x1000 /home/pi/zero2/fw/test.bin'
cmd3='esptool.py --chip esp32 -b 115200 erase_flash'
class ExecutorFlushSTDOUT(object):
def __init__(self,timeout=15):
self.process = None
self.process_output = queue.Queue(0)
self.capture_output = threading.Thread(target=self.output_reader)
self.timeout=timeout
self.result=False
self.validator=None
def output_reader(self):
start=time.time()
while self.process.poll() is None and (time.time() - start) < self.timeout:
try:
if not self.process_output.full():
line=self.process.stdout.readline()
if line:
line=line.decode().rstrip("\n")
start=time.time()
self.process_output.put(line)
if self.validator:
if self.validator in line: print("Valid");self.result=True
except:pass
self.process.kill()
return
def start_process(self,cmd_list,callback=None,validator=None,timeout=None):
if timeout: self.timeout=timeout
self.validator=validator
self.process = subprocess.Popen(cmd_list,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
self.capture_output.start()
line=None
self.result=False
while self.process.poll() is None:
try:
if not self.process_output.empty():
line = self.process_output.get()
if line:
if callback:callback(line)
#print(line)
line=None
except:pass
error = self.process.returncode
if error:
print("Error Found",str(error))
raise RuntimeError(error)
return self.result
execute = ExecutorFlushSTDOUT()
def liveOUTPUT(line):
print("liveOUTPUT",line)
try:
if "Writing" in line:
line=''.join([n for n in line.split(' ')[3] if n.isdigit()])
print("percent={}".format(line))
except Exception as e:
pass
result=execute.start_process(cmd2,callback=liveOUTPUT,validator="Hash of data verified.")
print("Finish",result)
基于@jfs 的出色答案,这里有一个完整的工作示例供您使用。 需要 Python 3.7 或更新版本。
子.py
import time
for i in range(10):
print(i, flush=True)
time.sleep(1)
主文件
from subprocess import PIPE, Popen
import sys
with Popen([sys.executable, 'sub.py'], bufsize=1, stdout=PIPE, text=True) as sub:
for line in sub.stdout:
print(line, end='')
注意子脚本中使用的flush
参数。
如果要在进程运行时从 stdout 打印,请将-u
Python 选项与 subprocess.Popen subprocess.Popen()
一起使用。 ( shell=True
是必要的,尽管有风险......)
简单胜于复杂。
os
库有内置的模块system
。 您应该执行代码并查看输出。
import os
os.system("python --version")
# Output
"""
Python 3.8.6
0
"""
在版本之后,它也被打印返回值为0
。
在 Python 3.6 中,我使用了这个:
import subprocess
cmd = "command"
output = subprocess.call(cmd, shell=True)
print(process)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.