从控制台获取标准输出
Getting stdout from console
我正在尝试制作一个 python 脚本,该脚本将使用 dd if=/dev/sda of=/dev/sdb
将一个 usb 棒克隆(ISO 映像)到另一个
这是我的问题:
我想创建进度条来显示已完成的内容。
我试过了:
- 正在查看第二个 U 盘上的存储 space,但这不起作用,因为 ISO 图像扫描也未使用 space
- 通过将
status=progress
添加到 dd
命令,我可以在终端中取得进展,但我不知道如何从 python 访问标准输出。我尝试了 subprocess.Popen,run(stdout = PIPE)
有无 shell = True
用 .read()
、.read(1)
、.readline()
或 communicate()
阅读 process.stdout
。没有什么对我有用。 (https://www.endpointdev.com/blog/2015/01/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
感谢帮助
你在 status=progress
的正确轨道上,但它输出到 stderr,而不是 stdout。如果您执行 stderr = PIPE
然后从 cloning.stderr
而不是 cloning.stdout
读取,它将起作用。
我正在尝试制作一个 python 脚本,该脚本将使用 dd if=/dev/sda of=/dev/sdb
这是我的问题: 我想创建进度条来显示已完成的内容。
我试过了:
- 正在查看第二个 U 盘上的存储 space,但这不起作用,因为 ISO 图像扫描也未使用 space
- 通过将
status=progress
添加到dd
命令,我可以在终端中取得进展,但我不知道如何从 python 访问标准输出。我尝试了subprocess.Popen,run(stdout = PIPE)
有无shell = True
用.read()
、.read(1)
、.readline()
或communicate()
阅读process.stdout
。没有什么对我有用。 (https://www.endpointdev.com/blog/2015/01/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感谢帮助
你在 status=progress
的正确轨道上,但它输出到 stderr,而不是 stdout。如果您执行 stderr = PIPE
然后从 cloning.stderr
而不是 cloning.stdout
读取,它将起作用。