subprocess.popen()的实时输出,而不是逐行输出 [英] Real time output of subprocess.popen() and not line by line

查看:1178
本文介绍了subprocess.popen()的实时输出,而不是逐行输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在用python重写一个小包装程序,我曾经用C ++编写过.它从文件中提取文件,然后以另一种格式将它们装箱.

I'm currently rewriting a little wrapper program in python that I once wrote in C++. It extracts files from a file and boxes them in another format.

在C ++中,我需要运行的系统命令的输出是实时"的,即实时显示的状态栏和某些命令的百分比指示器.使用python,我可以将每个百分比"分别转储到屏幕上(因为我逐行阅读).这是一个示例:这就是状态栏在python版本中的外观(一直持续到100).在C ++中,它确实会自动更新.

In C++ the output from the system commands I need to run was "real time" i.e the status bar and the percentage indicator of some commands where shown in real time. With python I get each 'percent' dumped on the screen individually (because I read it line by line). Here's an example: Thats how a status bar looks in the python version (this goes on until 100). In C++ it does update itself though.

| (02/100)\rImporting AVC-H264: |                    | (03/100)\rImporting AVC-H264: |                       | (04/100)\rImporting AVC-H264: |=

那是相应的python代码:

Thats the corresponding python code:

p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
for line in iter(p.stdout.readline, ""):
   print line,

关于如何使它在C ++中看起来如何的任何想法?

Any ideas on how I could make it look like in C++ ?

推荐答案

可能是两件事...

readline可能会改变您的输出中的某些内容 程序.我相信\r是回车并告诉终端 返回到开始 行,然后程序可以在刚输出的文本上方输出. Readline最有可能将其删除.

It's likely that readline is changing some things from the output of your program. I believe \r is carriage return and tells the terminal to return to the beginning of the line and then the program can output overtop the text it just output. Readline is most likely removing this.

首先要尝试的

p = subprocess.Popen(args, stdout=subprocess.PIPE, \
                     stderr=subprocess.PIPE, \
                     universal_newlines=True)
for line in iter(p.stdout.readline, ""):
    sys.stdout.write('\r'+line[:-1])
    sys.stdout.flush()

必须进行刷新,因为stdout会缓冲直到获得\n和 当然你不是写一个.

You have to do the flush because stdout buffers until it gets a \n and of course you're not writing one.

这篇关于subprocess.popen()的实时输出,而不是逐行输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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