I want to see the progress of my for loop by repeatedly overwriting the print function. I expected the printed line to be overwritten every time the loop progresses. What happened was that after every loop a new line was printed right under the previous printed line. This was solved by removing the \n from the print line, because the \n caused a new empty line to be overwritten each time, instead of overwriting the first printed line.
import sys
import time
count1=0
x=10
for i in range(x):
count1+=1
sys.stdout.write("\r{} out of {}...\n".format(count1, x))
sys.stdout.flush()
time.sleep(.1)
I am using Python 3.6 (64-bit) in Jupter Notebook 4.3.1. on Windows 10.
I have looked over several issues posted on Stack Overflow, but I haven't been able to solve it yet.
Thanks!
Remove the "\n" that creates a new line.
sys.stdout.write("\r{} out of {}...".format(count1, x))
Related
I've seen a chunck of code like this :
def print_L(msg):
sys.stdout.write(str(msg) + '\n')
sys.stdout.flush()
I'm wondering what's the difference between the code above and function print() without setting anything inside.
for if you didnt know:
Unlike print, sys.stdout.write doesn’t switch to a new line after one text is displayed. use \n to do a new line. heres an article on flush. https://www.geeksforgeeks.org/python-sys-stdout-flush/
from what i've seen, there should be no visual difference - however i think that in earlier versions that there were some time bugs that flush() fixed - and there are probably different things happening internally in the python compiler
I wrote a little python3 script, that runs another program with Popen and processes its output to create a little dashboard for it. The script generates a long string with information about the other program, clears the terminal and prints it. Everytime the screen refreshes, the whole terminal flickers.
here are the important parts of my script:
def screen_clear():
if os.name == 'posix':
os.system('clear')
else:
os.system('cls')
def display(lines):
# lines as a list of, well, lines i guess
s=''
for line in lines:
s=s + '\n' + str(line)
screen_clear()
print(s)
I bet theres a more elegant way without flickering to this, right?
Thanks for any help in advance!
the only solution to try out I can think of would be using print(s, end='\r') instead of clearing the screen first and printing again. The \r marker tells the console to override the last line.
In the end I'm sorry to say that consoles are simply not made for using them as a dashboard with permanently changing values. If the aforementioned solution doesn't work, maybe try implementing your dashboard in another way, python offers lots of solutions for that.
I'm looking for the cleanest way to print a variable dynamically in python 3.
I want to repeatedly call psutil.virtual_memory() and print its return-value in place.
Something like this:
import psutil
import time
memory = psutil.virtual_memory()
while True:
print(f"Memory: {memory}")
time.sleep(0.5)
Ofcourse that wouldn't be dynamic. I want "memory" to update every 0.5 seconds on the same line.
I couldn't seem to find a clean example of how to do this in this manner.
UPDATE: I'm also wanting to learn how I can do this with multi-line print statements.
Like this
Memory: 500MB
CPU Usage: 25%
Just add print(..., end='\r') to the end of your printing statement.
This brings the cursor to the beginning of the line, so subsequent prints will overwrite it.
f-strings allow you to directly print a function call or expression in the first place, so do that. (No need to store the stale return value to a variable, in the first place)
while True:
print(f"Memory: {psutil.virtual_memory()}")
time.sleep(0.5)
UPDATE: after you accepted an answer, we infer that when you say "print the value in-place", you actually mean "overwrite the output (on console) from previous print"
"in-place" is actually a different term that usually refers to "variable assignment without allocating new memory". Better to say "overwrite on the console".
Add carriage return with flush for print.
import psutil
import time
def memory():
return psutil.virtual_memory()
while True:
print(f"Memory: {memory()}", end="\r", flush=True)
time.sleep(0.5)
There are already lots of other questions about the print statement, but I have not found an answer to my problem:
When I do:
for idx in range(10):
print(idx, end="\r")
in the (ipython) terminal directly, it works fine and always overwrites the previous line. However, when running this in a module with PyCharm, I don't see any lines printed in the stdout.
Is this a known PyCharm issue?
Try to add \r at the beginning of your printed string (not at the end):
for idx in range(10):
print('\r', idx, end='')
Carriage return at front, and end with '' to avoid new line '\n'. One solution to avoid the space is to use the format convention:
for idx in range(10):
print("'\r{0}".format(idx), end='')
I had the same issue. While a solution using print() has eluded me, I have found sys.stdout.write works fine. (Win10, Python 3.5.1, Pycharm 2016.3.2)
import sys
import time
def countdown(n):
for x in reversed(range(n)):
sys.stdout.write('\r' + str(x))
time.sleep(1)
countdown(60)
I have a code where I iterate a certain scheme using a loop. At each iteration I want a printout of what happened. A silly minimal working example is shown below:
import time
Iter=0
for k in range(1,10):
Iter=Iter+1
print('At iteration ',Iter,': k=',k,'.',sep='')
time.sleep(1)
The time.sleep(1) is there to make my problem visible for such a short iteration scheme: At each iteration, the print() function only prints the first string. The rest appears only after the print() function is called in the next iteration. If I use the exact same syntax for the print() function outside of the loop, then I obtain the output I want. How can I get the same output when I'm inside the loop?
I'm new at this, but I suspect it could be relevant that I use the Anaconda3 (64-bit) distribution of Python 3.5 with the Spyder IDE on a Win10 machine.
Edit 1: SOLVED using the suggestion by #RemcoGerlich: "Try adding 'import sys' and then after the print sys.stdout.flush()." Many thanks!