【发布时间】:2021-11-29 09:04:39
【问题描述】:
我有以下简单的程序来运行一个子进程并将tee 输出到stdout 和一些缓冲区
import subprocess
import sys
import time
import unicodedata
p = subprocess.Popen(
"top",
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
stdout_parts = []
while p.poll() is None:
for bytes in iter(p.stdout.readline, b''):
stdout_parts.append(bytes)
str = bytes.decode("utf-8")
sys.stdout.write(str)
for ch in str:
if unicodedata.category(ch)[0]=="C" and ord(ch) != 10:
raise Exception(f"control character! {ord(ch)}")
time.sleep(0.01)
当运行一些终端更新程序时,例如top 或docker pull,我也希望能够捕获它的整个输出,即使它不能立即读取。
例如阅读How do commands like top update output without appending in the console?,它似乎是通过控制字符实现的。 但是,从进程输出流(stdout/stderr)中读取行时,我没有收到任何消息。还是他们使用的技术不同,我无法从子流程中捕捉到它?
【问题讨论】:
-
我回滚了你最近的编辑(文本仍然可以从revision history获得);非常欢迎您将其发布为答案,但您的问题应严格保留。
标签: python subprocess tty control-characters python-module-unicodedata