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.
To print on the same line in Python, add a second argument, end=' ', to the print() function call. print("It's me.")
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'.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With