0

I have a script that makes many (hundreds of thousands of) files, and I want to so something like this:

from __future__ import print_function

print("Generating...", end = "")
doStuff()
print(" Done")

Because of the end = "", I'd expect Generating... to show up before the long task, and for it to change to Generating... Done when it's finished. However, the first print() doesn't show up until after doStuff() has completed, immediately before the second print(). a time.sleep(1) before doStuff() doesn't do anything, although it wouldn't be a permanent solution anyway.

tkbx
  • 15,602
  • 32
  • 87
  • 122

2 Answers2

2

You need to flush sys.stdout periodically for the characters to show up:

import sys

print 'Working',

while working():
    work()

    print '.',

    sys.stdout.flush()

print 'Done'
Blender
  • 289,723
  • 53
  • 439
  • 496
  • Worked like a charm, I just added `sys.stdout.flush()` before `doStuff()`. Seems like Python is the type of language not to have this kind of a problem, but works perfectly nonetheless. – tkbx Dec 12 '12 at 23:27
  • @tkbx: It might depend on your platform (and terminal emulator?). I have to do this under Linux, but Windows doesn't seem to have this issue. – Blender Dec 12 '12 at 23:31
  • I'm on Mac using the default emulator in bash, havent tested any other OSes yet (but I'll be using this on Linux primarily) – tkbx Dec 12 '12 at 23:45
  • Reopening stdout unbuffered `sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)` should save you repeated flushing. – Hyperboreus Dec 13 '12 at 03:01
0

It is possible your interpreter that buffers the output. Running "python -u yourfile.py" should fix that.

Hyperboreus
  • 31,997
  • 9
  • 47
  • 87
  • I'm running it as an executable (./script), and it's not really a permanent solution... – tkbx Dec 12 '12 at 23:28
  • OK, I thought your shell would invoke a python interpreter to interpret your script (maybe indicated by a shebang), this at least does mine. For general unbuffered output cf. http://stackoverflow.com/questions/881696/unbuffered-stdout-in-python-as-in-python-u-from-within-the-program et al. – Hyperboreus Dec 13 '12 at 02:57
  • It does, but I can't `python -u` this way. – tkbx Dec 13 '12 at 12:56