简体   繁体   中英

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)

'\\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.

改为这样做:

print "\r%d" % x,

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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