subprocess.popen() 的实时输出,而不是逐行输出
我目前正在用 python 重写一个我曾经用 C++ 编写的小包装程序。它从文件中提取文件并将它们以另一种格式装箱。
在 C++ 中,我需要运行的系统命令的输出是“实时”的,即状态栏和某些命令的百分比指示器实时显示。使用 python,我将每个“百分比”单独转储到屏幕上(因为我逐行读取它)。这是一个例子:这就是 python 版本中状态栏的样子(一直持续到 100)。但在 C++ 中它确实会自我更新。
| (02/100)\rImporting AVC-H264: | | (03/100)\rImporting AVC-H264: | | (04/100)\rImporting AVC-H264: |=
这就是相应的 python 代码:
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
for line in iter(p.stdout.readline, ""):
print line,
关于如何使它看起来像 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.
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: |=
Thats the corresponding python code:
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
for line in iter(p.stdout.readline, ""):
print line,
Any ideas on how I could make it look like in C++ ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
可能有两件事......
readline 可能正在改变你的输出的一些东西
程序。我相信
\r
是回车符并告诉终端返回到开头
行,然后程序可以输出覆盖刚刚输出的文本。
Readline 很可能会删除这个。
首先要尝试的是,
您必须进行刷新,因为标准输出会缓冲,直到它获得
\n
和当然你不会写一个。
Could be two things...
It's likely that readline is changing some things from the output of your
program. I believe
\r
is carriage return and tells the terminalto 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.
First thing to try,
You have to do the flush because stdout buffers until it gets a
\n
and ofcourse you're not writing one.
在 Windows 上,您可以输出退格字符(ASCII 代码 8)。示例(仅使用一位数字打印当前迭代):
您需要跟踪当前行上的字符数......我确信一定有更好的方法。
在 Linux 上,您似乎可以编写回车符来重置光标位置。请参阅擦除当前打印的控制台行和终端或控制台中的就地进度输出。
On Windows, you can output the backspace character (ASCII code 8). Example (prints the current iteration using only single digit numbers):
You would need to keep track of the number of characters on the current line... I'm sure there must be a better way.
On Linux, it appears that you can write carriage returns to reset the cursor position. See Erase the current printed console line and In-place progress output in the terminal or console.
抱歉,但我不太了解实时部分,但也许我可以帮助“自我更新”部分,试试这个:
Sorry but i didn't understand well the real time part, but maybe i can help with "update it self" part, try this: