Possible Duplicate:
How to flush output of Python print?
I have have an algorithm that I'm running that takes a while, so I want to keep track of how far it's through, by printing to the console.
So something like:
import sys
def myMethod():
i = 0
while (i<1000000):
i = i+1
output_str = str(i) + "\n"
sys.stdout.write(output_str) # same as print
sys.stdout.flush()
myMethod()
How can I have this print while it's running, rather than at the end?
Edit, Solution: - Posted amended code. This code works fine when you run it in the linux terminal using
python filename.py
But when I run it in Wing 101 IDE - by pressing the green play button ('Run the contents of the editor within the python shell') - it waits to till the program is finished before outputting.
Apparently it's not possible to flush stdout in the Wing IDE.
This is what threads are for. You can have a worker thread and a progress thread running at the same time:
The output of the command is:
Notice that the worker thread is counting by
1
very quickly, but the progress thread is just reporting the progress every second.This has already been discussed on SO.
Please check:
How to flush output of Python print?