Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 376
LWZ Avatar asked Sep 17 '14 18:09

LWZ


People also ask

How do I remove items from console in Python?

The commands used to clear the terminal or Python shell are cls and clear.


1 Answers

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
like image 59
2 revs, 2 users 75% Avatar answered Sep 24 '22 09:09

2 revs, 2 users 75%