从python执行时如何打印和捕获7zip的%进度标记?

时间:2012-06-30 00:36:08

标签: python 7zip

当7zip从命令行运行时,它将使用一系列'%'符号打印进度条。

我想在Python中执行7zip时捕获并打印此进度条。 我该怎么做?

我目前正在使用的Python代码:

from subprocess import Popen, PIPE
pipe = Popen('7za.exe a -tgzip "e:\\backup\\sch Testerr 2012 06 23 17-27.gzip" "E:/archiv"' , stdout=PIPE)
text = pipe.communicate()[0]
print text

3 个答案:

答案 0 :(得分:1)

你想要的是sys.stdout.flush()。

但是,您可能需要在单独的线程上执行flush,因为主线程可能被阻塞,直到Popen中的基础进程完成。

编辑:使用Brian的答案来帮助(并避免多线程),我设想了这样的解决方案:

from subprocess import Popen, PIPE
pipe = Popen('7za.exe a -tgzip "e:\\backup\\sch Testerr 2012 06 23 17-27.gzip" "E:/archiv"' , stdout=PIPE)

# Assuming Python thread continues after POpen invoke (but before 7za is finished)
while (not pipe.poll()):
    sys.stdout.flush()
    time.sleep(1)

答案 1 :(得分:1)

来自communicate(强调我的):

  

从stdout和stderr读取数据,直到达到文件结尾。 等待进程终止。

请考虑使用poll

from subprocess import Popen, PIPE
pipe = Popen('7za.exe a -tgzip "e:\\backup\\sch Testerr 2012 06 23 17-27.gzip" "E:/archiv"', stdout=PIPE)
while True: # Feeling fancy?  add a timeout condition here...
    if pipe.poll():
        break
    # consider reading from stdin and printing as your needs indicate

答案 2 :(得分:0)

我发现当重定向stdout时,7za会抑制进度输出 所以,我写了一个补丁。
'sopg'选项即使在重定向或管道传输stdout时也会启用进度输出。 https://github.com/photom/p7zip/commit/2baacd6c354fbde19ebc83d185e73f6d9bd62517

$ 7za x -sopg ..7z