How can I print to console while the program is running in python?

dwjohnston picture dwjohnston · Sep 30, 2012 · Viewed 31.2k times · Source

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.

Answer

monkut picture monkut · Sep 30, 2012
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()