2

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.

serverpunk
  • 10,665
  • 15
  • 61
  • 95
  • Is this executing on windows? – yxre Oct 26 '14 at 16:11
  • Yes it's on Windows. – serverpunk Oct 26 '14 at 16:16
  • Works for me on Python 2.7.7 and 3.3 (though a call to `time.sleep()` helps to see the earlier lines. The difference could be that I'm running the 32-bit version, or the 0.0.2 version difference, or could be how you are running it: how are you running the script? I tried both from powershell and from cmd.exe and it works either way for me. – Duncan Oct 26 '14 at 16:47
  • It does however go wrong if run from Powershell ISE. Are you using Powershell ISE to run your script? – Duncan Oct 26 '14 at 16:49
  • Ahhh you know what -- I was running it from the console of my text editor (Sublime Text). When I ran it through cmd.exe it worked fine! Thanks for pointing me in the right direction. – serverpunk Oct 26 '14 at 17:11

1 Answers1

5

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().

Duncan
  • 92,073
  • 11
  • 122
  • 156