从控制台获取标准输出 [英] Getting stdout from console
问题描述
我正在尝试制作一个Python脚本,该脚本将使用dd if=/dev/sda of=/dev/sdb
I'm trying to make a python script that would clone(ISO image) one usb stick to another using dd if=/dev/sda of=/dev/sdb
这是我的问题: 我想创建进度条,显示已完成的操作.
Here's my problem: I want to create progress bar showing what is done.
我尝试过:
- 在第二个USB记忆棒上查看存储空间,但这无法正常工作,因为ISO映像还会扫描未使用的空间
- 通过将
status=progress
添加到dd
命令中,我可以在终端中获得进度,但是我不知道如何从python访问stdout.我尝试了subprocess.Popen,run(stdout = PIPE)
有无shell = True
用.read()
,.read(1)
,.readline()
或communicate()
读取process.stdout
.对我没有任何帮助.( https://www.endpoint.com/blog/2015/01/28/getting-realtime-output-using-python )
- Looking at storage space at second usb stick, but this doesn't work beacause ISO image scans also unused space
- By adding
status=progress
todd
command I can get progress in terminal but I can't figure how to access stdout from python. I triedsubprocess.Popen,run(stdout = PIPE)
with and withoutshell = True
readingprocess.stdout
with.read()
,.read(1)
,.readline()
orcommunicate()
. Nothing worked for me.(https://www.endpoint.com/blog/2015/01/28/getting-realtime-output-using-python)
我可以在python shell中看到进度,但是.read()
函数总是卡住.
I can see progress going on in python shell but .read()
function always get stuck.
我关注的部分代码:
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())
我想要可以工作的东西:
I want something that would work like:
while True:
progress = cloning.stdout.read()
update_bar(progress)
我在Raspberry上使用python 3.7
I'm using python 3.7 on Raspberry
感谢帮助
推荐答案
您使用status=progress
处于正确的轨道,但是它输出到stderr,而不是stdout.如果您执行stderr = PIPE
,然后从cloning.stderr
而不是cloning.stdout
读取,它将起作用.
You were on the right track with status=progress
, but it outputs to stderr, not stdout. If you do stderr = PIPE
and then read from cloning.stderr
instead of cloning.stdout
, it will work.
这篇关于从控制台获取标准输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!