首页 > 解决方案 > python的subprocess.Popen()实时刷新颜色输出

问题描述

Linux中有一些带有“花式”输出的命令-“花式”是指它是彩色的并且是实时的,即它会覆盖自己,最好的示例是top命令的输出,另一个示例可能是 docker build(它刷新次(0.5s在下面的示例中)在构建期间交互,请参阅演示):

[+] Building 0.5s (3/3) FINISHED                                                                                                                                
 => [internal] load .dockerignore                                0.0s
 => => transferring context: 2B                                  0.0s
 => [internal] load build definition from Dockerfile             0.0s
 => => transferring dockerfile: 518B                             0.0s
 => ERROR resolve image config for ...                           0.5s
...

我的问题是,在 Python 中运行进程时如何获得相同的输出(大概使用subprocess.Popen)?我主要对 Linux 感兴趣。


PS我能达到的最接近的是通过分配tty的彩色输出:

out_r, out_w = pty.openpty()
p = subprocess.Popen(command, stdout=out_w, stderr=subprocess.STDOUT, shell=True)
os.close(out_w)
while True:
   try:
      output = os.read(out_r, 1000).decode()
      print(output)

但不出所料,它会打印下面的所有内容,而不会重写内容。

标签: pythonpython-3.x

解决方案


好吧,谷歌的正确词是ncurses/curses,这立即让我得到了这个答案

以下几行对我来说就像一个魅力:

import pexpect
child = pexpect.spawn(<command_line_str>)
child.interact()

推荐阅读