【发布时间】:2019-05-22 15:29:56
【问题描述】:
我正在使用 subprocess 模块来运行 bash 命令。我想实时显示结果,包括在没有添加新行的情况下,但输出仍然被修改。
我正在使用 python 3。我的代码使用子进程运行,但我对任何其他模块都是开放的。我有一些代码为添加的每个新行返回一个生成器。
import subprocess
import shlex
def run(command):
process = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE)
while True:
line = process.stdout.readline().rstrip()
if not line:
break
yield line.decode('utf-8')
cmd = 'ls -al'
for l in run(cmd):
print(l)
例如,rsync -P file.txt file2.txt 形式的命令会出现问题,该命令会显示进度条。
例如,我们可以先在 bash 中创建一个大文件:
base64 /dev/urandom | head -c 1000000000 > file.txt
然后尝试使用python显示rsync命令:
cmd = 'rsync -P file.txt file2.txt'
for l in run(cmd):
print(l)
有了这段代码,进度条只在流程结束时打印,但我想实时打印进度。
【问题讨论】:
标签: python-3.x bash subprocess