使用python获取pv的输出 [英] Get output of pv using python
问题描述
有没有办法在python中使用pv程序来获取操作的进度?
Is there a way to use the program pv from within python so as to get the progress of an operation?
到目前为止,我有以下几点:
So far I have the following:
p0 = sp.Popen(["pv", "-f", args.filepath],
bufsize=0,
stdout=sp.PIPE,
stderr=sp.PIPE)
p1 = sp.Popen(["awk", "{print $1, $2, $1, $3, $4 }", "{}".format(args.filepath)],
stdout=sp.PIPE,
stdin=p0.stdout)
但是我无法从 p0
获取连续输出.我试过了:
But I'm having trouble getting continuous output from p0
. I tried:
for line in p0.stderr:
print("line:", line)
但这会等待进程完成,然后只打印 pv
的最后一个进度报告.有谁知道如何让它打印不断更新的状态?
But this waits for the process to finish and then only prints the last progress report from pv
. Does anybody know how I can get it to print the continuously updating status?
推荐答案
结果 pv
输出每一行,并在末尾有一个回车符 (\r
).为了能够连续读取输出,Popen
需要用 universal_lines=True
初始化,如下所示:
It turns out pv
outputs each line with a carriage return at end (\r
). To be able to continuously read from the output, Popen
needs to be initialized with universal_lines=True
, like this:
p0 = sp.Popen(['pv', '-f', args.filepath],
stdout=sp.PIPE,
stderr=sp.PIPE,
universal_newlines=True)
这会导致持续输出进度报告:
This leads to a continuous output of progress reports:
line: 7.12MB 0:00:01 [ 7.1MB/s] [=> ] 8% ETA 0:00:11
line: 14.6MB 0:00:02 [7.42MB/s] [====> ] 16% ETA 0:00:10
line: 22.1MB 0:00:03 [7.55MB/s] [=======> ] 24% ETA 0:00:09
line: 29.5MB 0:00:04 [7.36MB/s] [==========> ] 33% ETA 0:00:08
这是对类似问题的引用:
Here's a reference to a similar question:
subprocess.popen 的实时输出() 而不是逐行
这篇关于使用python获取pv的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!