简体   繁体   English

Python print语句不带回车符

[英]Python print statement prints nothing with a carriage return

I'm trying to write a simple tool that reads files from disc, does some image processing, and returns the result of the algorithm. 我正在尝试编写一个简单的工具,从光盘读取文件,进行一些图像处理,并返回算法的结果。 Since the program can sometimes take awhile, I like to have a progress bar so I know where it is in the program. 由于该程序有时需要一段时间,我喜欢有一个进度条,所以我知道它在程序中的位置。 And since I don't like to clutter up my command line and I'm on a Unix platform, I wanted to use the '\\r' character to print the progress bar on only one line. 由于我不喜欢混乱我的命令行而且我在Unix平台上,所以我想使用'\\ r'字符仅在一行上打印进度条。

But when I have this code here, it prints nothing. 但是当我在这里有这个代码时,它什么都不打印。


# Files is a list with the filenames
for i, f in enumerate(files):
    print '\r%d / %d' % (i, len(files)),
    # Code that takes a long time

I have also tried: 我也尝试过:


print '\r', i, '/', len(files),

Now just to make sure this worked in python, I tried this: 现在只是为了确保这在python中有效,我尝试了这个:


heartbeat = 1
while True:
    print '\rHello, world', heartbeat,
    heartbeat += 1

This code works perfectly. 这段代码完美无缺。 What's going on? 这是怎么回事? My understanding of carriage returns on Linux was that it would just move the line feed character to the beginning and then I could overwrite old text that was written previously, as long as I don't print a newline anywhere. 我对Linux上回车的理解是它只是将换行符移动到开头然后我可以覆盖以前写过的旧文本,只要我不在任何地方打印换行符。 This doesn't seem to be happening though. 但这似乎并没有发生。

Also, is there a better way to display a progress bar in a command line than what I'm current trying to do? 此外,是否有更好的方法在命令行中显示进度条,而不是我当前尝试做的?

Try adding sys.stdout.flush() after the print statement. 尝试在print语句后添加sys.stdout.flush() It's possible that print isn't flushing the output until it writes a newline, which doesn't happen here. 在写入换行符之前, print可能不会刷新输出,这在此处不会发生。

Handling of carriage returns in Linux differs greatly between terminal-emulators. Linux中回车的处理在终端仿真器之间存在很大差异。

Normally, one would use terminal escape codes that would tell the terminal emulator to move the virtual "carriage" around the screen (think full-screen programs running over BBS lines). 通常,可以使用终端转义码来告诉终端仿真器在屏幕上移动虚拟“托架”(想想在BBS线路上运行的全屏程序)。 The ones I'm aware of are the VT100 escape codes: 我所知道的是VT100转义码:

\\e[A : up \\e[A :向上
\\e[B : down \\e[B :向下
\\e[C : right \\e[C :对
\\e[D : left \\e[D :离开
\\e[1~ : home \\e[1~ :家
\\e[4~ : end \\e[4~ :结束

Where \\e is the escape character, \\x1b . 其中\\e是转义字符\\x1b

Try replacing all \\r 's with \\e[1~ 尝试用\\r \\e[1~替换所有\\r

Also see this post 另见这篇文章

如果您的终端是行缓冲的,如果您不发出换行符,则可能需要sys.stdout.flush()才能看到您的打印。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM