简体   繁体   中英

Python carriage return not working

I have a long-running script that loops over rows in a database. Every so often I'd like it to print how many rows it's processed, but without creating a new line each time. This is essentially what I have:

import sys
mystr = "{} rows complete\r"

for i in range(0, 100):
    if i % 10 == 0:
        sys.stdout.write(mystr.format(i))
        sys.stdout.flush()

When I run this (on Python 2.7.5 64-bit, Windows) I get:

0 rows complete
10 rows complete
20 rows complete
...
100 rows complete

Can anyone think of why the carriage return isn't working? I've seen some similar questions here about Python and \\r , but all the answers say to include sys.stdout.flush() , which I have.

Using \\r is probably the correct way to go here, but the behaviour depends very much on how the text is being output. Not all terminals will respect a bare carriage return:

cmd.exe and powershell.exe should both output the text the way you expect (Powershell ISE doesn't but that's a red herring here).

Python's own idle will ignore the carriage return, all output comes on one long line.

As you noted, your own editor's command window also ignores \\r .

Also, if you try from an interactive window you also get some numbers output at the end of each line: that's because the interactive windows helpfully outputs the result of the call to sys.stdout.flush() .

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