Python print statement prints nothing with carriage return

I am trying to write a simple tool that reads files from disk, does some image processing and returns the result of the algorithm. Since a program can sometimes take some time, I like to have a progress bar, so I know where it is in the program. And since I don't like cluttering my command line, and I'm on a Unix platform, I wanted to use the "\ r" character to print the execution line on only one line.

But when I have this code, it doesn't print anything.

# 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 also tried:

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

Now, to make sure this worked in python, I tried this:

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

This code works fine. What's happening? My understanding of carriage return in Linux was that it would just move the line character to the beginning, and then I could overwrite the old text that was written earlier, until I print a new line anywhere. This does not seem to be happening.

Also, is there a better way to display a progress bar on the command line than what I'm trying to do now?

+7
python command-line carriage-return
source share
3 answers

Try adding sys.stdout.flush() after the print statement. It is possible that print does not flush the output until it writes a new line, which is not happening here.

+10
source share

Linux carriage return handling is very different between terminal emulators.

As a rule, you can use terminal escape codes that will allow the terminal emulator to move the virtual "carriage" around the screen (think that full-screen programs work on BBS lines). I know these are VT100 escape codes:

\e[A : up
\e[B : down
\e[C : right
\e[D : left
\e[1~ : home
\e[4~ : end

Where \e is the escape character, \x1b .

Try replacing all \r with \e[1~

Also see this post.

+2
source share

If your terminal is line-buffered, you may need sys.stdout.flush() to see your print if you do not return a line feed.

+2
source share

All Articles