This question already has answers here:
Closed 7 years ago.
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.
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()
This is what threads are for. You can have a worker thread and a progress thread running at the same time:
import time
from threading import Thread
class WorkerThread(Thread):
def __init__(self, value=0):
super(WorkerThread, self).__init__()
self.value = value
def run(self):
while self.value < 1000:
self.value += 1
time.sleep(0.01)
class ProgressThread(Thread):
def __init__(self, worker):
super(ProgressThread, self).__init__()
self.worker = worker
def run(self):
while True:
if not self.worker.is_alive():
print 'Worker is done'
return True
print 'Worker is at', self.worker.value
time.sleep(1.0)
if __name__ == '__main__':
worker = WorkerThread()
progress = ProgressThread(worker)
worker.start()
progress.start()
progress.join()
The output of the command is:
Worker is at 1
Worker is at 99
Worker is at 197
Worker is at 295
Worker is at 394
Worker is at 492
Worker is at 590
Worker is at 689
Worker is at 787
Worker is at 885
Worker is at 983
Worker is done
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?