Why `print` content doesn't show immediately in terminal?

11,944

How can I print the dots inline as it runs?

Try flushing your output, like so:

for _ in range(10):
    print '.',
    sys.stdout.flush()
    time.sleep(.2)  # or other time-consuming work

Or for Python 3.x:

for _ in range(10):
    print('.', end=' ', flush=True)
    time.sleep(.2)  # or other time-consuming work
Share:
11,944
LWZ
Author by

LWZ

I'm learning Python.

Updated on June 03, 2022

Comments

  • LWZ
    LWZ almost 2 years

    I have a python script for simulation, it takes fairly long time to run through a for loop and each loop takes different time to run, so I print a . after each loop as a way to monitor how fast it runs and how far it went through the for statement as the script runs.

    for something:
        do something
        print '.',
    

    However, as I run the script in iPython in terminal, the dots does not print one by one, instead it prints them all at once when the loop finishes, which made the whole thing pointless. How can I print the dots inline as it runs?