Python print statement prints nothing with a carriage return

Posted by Jonathan Sternberg on Stack Overflow See other posts from Stack Overflow or by Jonathan Sternberg
Published on 2010-05-12T18:05:08Z Indexed on 2010/05/12 18:24 UTC
Read the original article Hit count: 351

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.

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:


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. 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?

© Stack Overflow or respective owner

Related posts about python

Related posts about carriage-return