user2538722
user2538722

Reputation:

How can I use \r to make Python print on the same line?

Can someone please thoroughly explain how a '\r' works in Python? Why isn't the following code printing out anything on the screen?

#!/usr/bin/python

from time import sleep

for x in range(10000):
    print "%d\r" % x,
    sleep(1)

Upvotes: 0

Views: 5444

Answers (4)

Fred Larson
Fred Larson

Reputation: 62053

Your output is being buffered, so it doesn't show up immediately. By the time it does, it's being clobbered by the shell or interpreter prompt.

Solve this by flushing each time you print:

#!/usr/bin/python

from time import sleep
import sys

for x in range(10000):
    print "%d\r" % x,
    sys.stdout.flush()
    sleep(1)

Upvotes: 2

Eugene C.
Eugene C.

Reputation: 515

Do this instead:

print "\r%d" % x,

Upvotes: 1

Octopus
Octopus

Reputation: 8325

'\r' is just a another ASCII code character. By definition it is a CR or carriage return. It's the terminal or console being used that will determine how to interpret it. Windows and DOS systems usually expect every line to end in CR/LF ('\r\n') while Linux systems are usually just LF ('\n'), classic Mac was just CR ('\r'); but even on these individual systems you can usually tell your terminal emulator how to interpret CR and LF characters.

Historically (as a typewriter worked), LF bumped the cursor to the next line and CR brought it back to the first column.

To answer the question about why nothing is printing: remove the comma at the end of your print line.

Upvotes: 1

Jim Stewart
Jim Stewart

Reputation: 17323

This has nothing to do with \r. The problem is the trailing , in your print statement. It's trying to print the last value on the line, and the , is creating a tuple where the last value is empty. Lose the , and it'll work as intended.

Edit:

I'm not sure it's actually correct to say that it's creating a tuple, but either way that's the source of your problem.

Upvotes: 0

Related Questions