从控制台获取标准输出

时间:2020-05-08 21:53:19

标签: python python-3.x subprocess pipe

我正在尝试制作一个Python脚本,该脚本使用dd if=/dev/sda of=/dev/sdb将一个USB盘(ISO映像)克隆到另一个USB存储器

这是我的问题: 我要创建进度条以显示已完成的操作。

我尝试过:

  1. 在第二个USB记忆棒上查看存储空间,但这无法正常工作,因为ISO映像还会扫描未使用的空间
  2. 通过将status=progress添加到dd命令中,我可以在终端中获得进度,但是我不知道如何从python访问stdout。我尝试了subprocess.Popen,run(stdout = PIPE),有无shell = True 使用process.stdout.read().read(1).readline()阅读communicate()。对我没有任何帮助。(https://www.endpoint.com/blog/2015/01/28/getting-realtime-output-using-python

我可以在python shell中看到进度,但是.read()函数总是卡住。

我关注的部分代码:

comm = 'sudo dd if=/dev/sda of=/dev/sdb'
cloning = subprocess.Popen(shlex.split(comm),stdout = PIPE,text = True)
while True:
    print(cloning.stdout.read())

我想要类似的东西

while True:
    progress = cloning.stdout.read()
    update_bar(progress)

我在Raspberry上使用python 3.7

感谢帮助

1 个答案:

答案 0 :(得分:0)

使用status=progress使您处在正确的轨道上,但是它输出到stderr,而不是stdout。如果您执行stderr = PIPE,然后从cloning.stderr而不是cloning.stdout读取,它将起作用。

相关问题