This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Python Progress Bar
I am running a for loop 10,000 times,
but inside the loop there are a lot of calculations going on.
I would like to print out a progress message to the console informing me how far along in the loop the program is how much longer I might have to wait.
the basic loop is
n = 10000
for i in range(n):
do_stuff_method()
if(i%100 == 0):
print (float(i)/n)*100,
This prints out a percentage message on the same line, but the problem is that the next thing that I print out is also printed out on the same screen. That, and since there are 99 prinouts, the console gets pretty wide and there is a lot of scrolling across.
What I would really like is for the console to print out the current % done, and an estimated time to finsih on the one line replace that which had been previously printed, so there doesn't have to be a lot scrolling.
Can this be done?
Cheers,
Davy
In your case you can do it simply by changing your print line to be:
print "\r{0}".format((float(i)/n)*100),
Or you can try it like this instead of print:
sys.stdout.write("\r{0}".format((float(i)/n)*100))
sys.stdout.flush()
Related
I'm trying to make a script to calculate pi, but by increasing the steps in the main for loop, it drastically increases in the time it takes to calculate. Sometimes its hard to tell if its doing anything at all. So to fix this I put the following in the main for loop:
# prints the progress percentage (or pp)
pp = (i/rolls)*100
print(pp.__round__(pp_decimals))
rolls in the total number of times the loop will execute.
But this presents a new problem, this ends up printing ALOT of text, and all the print calls end up lagging my pc as well as clogging up the terminal. So my question is, how can I edit the text or delete previous text in order to clear up the output?
It is best to approach your problem in a different way. I assume that i is loop counter so you can print progress percentage in every t times instead clearing the output:
# prints the progress percentage (or pp)
if i % 10 == 0: # t is 10 in this example
pp = (i/rolls)*100
print(pp.__round__(pp_decimals))
This question already has answers here:
Printing on the same line with time.sleep()
(2 answers)
Closed 3 years ago.
While trying to solve a bigger issue, I reduced my code to two simple commands and I found out that they are not executed in order.
My idea is to give a kind of feedback to the user after clicking on a button(3D Slicer) while running a function. So, what I would expect is to freeze the button immediately after clicking it until the action is finished. So I tried the following to check if the very first command is executed on first position:
def onStartSegmentation(self):
self.segmentButton.setEnabled(False)
sleep(3)
print("2nd step: Starting segmentation")
However, the result is sleeping for 3 seconds and then executing both commands immediately one after the other.
I know this might sound silly, but I can't guess why it's acting like that.
print() function is buffered. That means the output will be buffered before displaying to the screen until the buffer is full or new line character is encountered. If you want to have your output to be displayed on the screen immediately, you need to flush the buffer by using sys.stdout.flush() or you need to explicitly specify it in the argument to print function.
def onStartSegmentation(self):
print("1st step: Starting segmentation", flush = True)
sleep(3)
print("2nd step: Starting segmentation", flush = True)
OR
def onStartSegmentation(self):
print("1st step: Starting segmentation")
sys.stdout.flush()
sleep(3)
print("2nd step: Starting segmentation")
sys.stdout.flush()
This question already has answers here:
How to print without a newline or space
(26 answers)
Closed 3 years ago.
I am making a command line game engine in python. However, when I attempt to print a command, it newlines and creates a jittery frame.
Adding the end attribute bogs down my computer and nearly crashes the shell. The dupe uses sys.stdout.write('') newline sys.stdout.flush or print'', or print('',end=''). all bog down shell and crash it. print('') doesn't bog down though which is weird.
#this is enough code to demonstrate the problem
while true:
print(' = === ===== ======= ========= =========== ============= YYYYYYYYYYY ================================================================================')
#crash issue
import sys
while True:
sys.stdout.write('mooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo')
sys.stdout.flush()
I expect the screen to fill, instead it wobbles up and down.
I am not sure if I understood your question correctly, but I’m thinking you do not want to print a new line with each call to the print() function.
If so, the print function has an optional argument end, that is set by default as \n (this, creating a new line if not specified otherwise). If you don’t want this to happen, you can simply use the print function as:
print(your_argument, end=“”)
Replacing your_argument with whatever you want to print out.
This question already has answers here:
How do I ensure that a Python while-loop takes a particular amount of time to run?
(3 answers)
Closed 9 years ago.
I have the following problem: I need a program that runs every minute. I have managed to do this with python's time-module and an infinite while-loop. It looks like this:
while True:
time_now = tm.gmtime(tm.time())
min_now = time_now.tm_min
if min_now - min_then == 1 or min_now - min_then == -59:
min_then = min_now
......
The loop runs about 150.000 times a second and while I don't think that the general performance is harmed worthy of mention, I wonder if there are alternatives.
Can I modify the number of reruns of a while loop? Or does the algorithm (in assembler, machine code etc.) just jump back to the beginning when finished? Can I use something like a 'wait'-command and will that help?
Thanks for listening (and answering ;) ),
best wishes,
Max
EDIT:
A sleep-command indeed solved my problems. I forget to mention that the rerun must take place every full clock-minute. A sleep for 60 seconds wouldn't be satisfying, however, I used a way that Xi Huan's link mentioned: After the execution of a loop, I use sleep(59.9-time_now.tm_sec). That reduces the CPU usage to 1%. Excellent.
And: Thank you all for your help! I'd like to upvote you, but I don't have enough reputation :D sry
bye!
An easy way would be to sleep in the loop, e.g.
import time
while True:
# do some stuff
time.sleep(60) #sleeps for a minute
EDIT:
Also be aware that you will need to 'import time' for this to work. Also, if you wish to limit the number of times it loops, this could be useful. The example below will loop once per minute and will loop 10 times in total.
import time
for x in xrange(0, 10):
#do stuff
time.sleep(60)
A common way to do this is by calling time.sleep, which is essentially the 'wait' command you ask about. If you do:
while True:
time.sleep(60)
# do stuff
The loop will end up running approximately once every minute, plus however long the do stuff takes. There are caveats mentioned in the docs that this isn't guaranteed to be an exact wait time, so you probably still want to check the time at each iteration (depending how strict the 'once per minute' is).
use a time.sleep method:
import time
while True:
#do something
time.sleep(60)
This question already has answers here:
How to print one character at a time on one line?
(4 answers)
Closed 9 years ago.
I'm writing a Python app involving a database. For the hell of it, I'm including an easter egg. If the user decides to nuke his database, all this from a terminal, he'll be prompted to confirm with a simple (y/n). But if he types DLG2209TVX instead, the lines from that scene of WarGames will print. Doubt anybody will ever find it unless they look through my source, but that's okay.
The problem is that simply printing the lines plays the scene way too fast and really just ruins it. I implemented a timer between each character's lines to slow things down, and it's better, but it still seems unnatural. Is there a standardized way to slowly print each word or character out instead of doing it lines at a time? Or should I just start adding timers between words?
Standardized? Not that I know of. But try this:
import random
import sys
import time
def slowprint(s):
for c in s + '\n':
sys.stdout.write(c)
sys.stdout.flush() # defeat buffering
time.sleep(random.random() * 0.1)
slowprint('Hello, world.')
Adjust the 0.1 to change the maximum delay between characters, and add lengthy time.sleep()s between lines to add more dramatic effect.
import sys
import time
for c in gettysburg_address:
sys.stdout.write(c)
sys.stdout.flush()
# 110 baud:
time.sleep( 8./110 )
# 300 baud:
# time.sleep( 8./300 )
You can also try curses.delay_output():
In [48]: import curses
In [49]: for x in "foo bar":
sys.stdout.write(x) #prints each char with a delay of 100ms
curses.delay_output(100)
....:
foo bar