从控制台获取标准输出 [英] Getting stdout from console

查看:232
本文介绍了从控制台获取标准输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个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.

我尝试过:

  1. 在第二个USB记忆棒上查看存储空间,但这无法正常工作,因为ISO映像还会扫描未使用的空间
  2. 通过将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 )
  1. Looking at storage space at second usb stick, but this doesn't work beacause ISO image scans also unused space
  2. By adding status=progress to dd command I can get progress in terminal but I can't figure how to access stdout from python. I tried subprocess.Popen,run(stdout = PIPE) with and without shell = True reading process.stdout with .read(), .read(1), .readline() or communicate(). 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆