在保存结果的同时打印子进程的输出并不是一个新问题,并且之前已经多次回答过,例如: 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 …Run Code Online (Sandbox Code Playgroud)