run*_*ace 11 python subprocess python-3.x systemd
在保存结果的同时打印子进程的输出并不是一个新问题,并且之前已经多次回答过,例如: 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)
Run Code Online (Sandbox Code Playgroud)
但问题是子进程的标准输出需要一个实际的文件: https: //stackoverflow.com/a/2298003/5506400
无论如何,是否可以实时打印子进程的输出,同时保持颜色,并将值存储到变量(无需通过临时文件)?
你不能用 来做到这一点subprocess,但是pty可以。pty创建伪终端,以便正在执行的命令检测到它正在使用 tty 运行并启用颜色输出。
import pty, os
output_bytes = []
def read(fd):
data = os.read(fd, 1024)
output_bytes.append(data)
return data
pty.spawn([command], read)
output = str(output_bytes)
# parse output as you need
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6480 次 |
| 最近记录: |