python - 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)
但不出所料,它会打印下面的所有内容,而不会重写内容。
解决方案
好吧,谷歌的正确词是ncurses/curses,这立即让我得到了这个答案。
以下几行对我来说就像一个魅力:
import pexpect
child = pexpect.spawn(<command_line_str>)
child.interact()
推荐阅读
- flutter - 点击效果不流畅
- c# - .net 核心:模型中的 ICollection 始终为空
- html - 像“src =”这样的html部分是什么?
- algorithm - 如何快速检查有向图的边缘是一座坚固的桥梁
- php - 将 Wordpress 用户管理迁移到自定义 CMS
- android - 从android中的服务器下载内容时屏幕冻结
- python - 如何使用python pandas检查日期是否在开始和结束之间的范围内
- emacs - Emacs 定期冻结:如何确定原因?
- javascript - 画布:onMouseDown 未定义
- laravel - 如何在 laravel 中配置重置密码