【发布时间】:2014-11-13 10:58:23
【问题描述】:
我正在尝试从“apt-get download firefox”之类的命令中读取最后一行。通常输出会像
Get:1 http://archive.ubuntu.com/ubuntu/ utopic/main firefox amd64 32.0+build1-0ubuntu2 [34.9 MB]
2% [1 firefox 646 kB/34.9 MB 2%]
最后一行不断更新(直到达到 100% 才写入换行符)。我现在的目标是实时阅读进度。这是我当前的示例代码:
#!/usr/bin/python3 -u
# coding=utf-8
import subprocess, sys
pipe = subprocess.Popen(['apt-get', 'download', 'firefox'], 0, stderr = subprocess.PIPE, stdout = subprocess.PIPE)
while True:
content = pipe.stdout.read(1).decode()
if content == '':
break
sys.stdout.write(content)
sys.stdout.flush()
pipe.wait()
我已禁用子进程调用的输出缓冲以及 Python 进程的二进制输出(使用 -u 参数)。但我只得到第一行而不是第二行的进展。有人知道我如何做到这一点吗?
【问题讨论】:
-
您需要线程或 async.io 来同时读取 both 流。见Displaying subprocess output to stdout and redirecting it。
-
您需要捕获
Get:1 http://..行(stdout?)还是仅获取最后(进度)行(stderr?)就足够了? -
检查事项: 1.
apt-get是否只写入 stdout/stderr 还是 write to the terminal directly? 2.是use the block-buffering if the stdout is a pipe吗? 3、stderr重定向到管道是否显示进度条? -
在你的情况下合并标准输出/标准错误是否可以接受(或者只是忽略标准错误)?
-
输出通常来自标准输出。捕获 stderr 只是为了将来的开发,删除它并不会改变结果。
标签: python-3.x subprocess pty