Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 856
dwjohnston Avatar asked Sep 30 '12 04:09

dwjohnston


People also ask

How do you print on the same line in Python console?

To print on the same line in Python, add a second argument, end=' ', to the print() function call. print("It's me.")

How do you print a function twice in Python?

The multiplication operator (*) prints a string multiple times in the same line. Multiplying a string with an integer n concatenates the string with itself n times. To print the strings multiple times in a new line, we can append the string with the newline character '\n'.


1 Answers

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()
like image 141
monkut Avatar answered Oct 23 '22 20:10

monkut