【发布时间】:2019-11-12 02:13:30
【问题描述】:
在保存结果的同时打印子进程的输出并不是一个新问题,之前已经回答过很多次例如:https://stackoverflow.com/a/28319191/5506400
这对我不起作用,因为我试图保持打印的外壳颜色。例如。当一个人去systemctl status application时,它的印刷品以绿色运行。
上述方法都依赖于从子进程中逐行读取,但在我看来,颜色信息被剥离并丢失了。
我试图制作一个从标准输出打印出来的对象并将它们保存到一个变量中:
from subprocess import *
import sys
class Tee():
def __init__(self):
self.content = ''
self.stdout = sys.stdout
sys.stdout = self
def __enter__(self):
return self
def __exit__(self, *args):
pass
def __del__(self):
sys.stdout = self.stdout
def write(self, data):
self.content += data
self.stdout.write(data)
def flush(self):
self.content = ''
with Tee() as tee:
# Saves print to tee.content
print("Hello World")
# This line does not save prints to tee.content
run(['apt-get', 'update'])
# raises an error that tee.fileno is not supported
run(['systemctl', 'status', 'nginx'], stdout=tee)
content = tee.content
print("---------------------")
print(content)
但问题是子进程的标准输出需要一个实际的文件:https://stackoverflow.com/a/2298003/5506400
是否可以实时打印子进程的输出,同时保持颜色,并将值存储到变量中(无需通过临时文件)?
【问题讨论】:
标签: python python-3.x subprocess systemd