Domanda

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)
È stato utile?

Soluzione

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)

Altri suggerimenti

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

Do this instead:

print "\r%d" % x,

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top