print something dynamically to replace the old printed thing and so on - python

I'm trying to figure out how to do something that seems quite simple, but haven't achieved to do it yet.
Basically, I just want to print something on the exact same line so that this new printed thing replace the old printed thing.
Let's take this piece of code of example:
import time
for i in range (0, 20):
print(i)
time.sleep(0.3)
I want the second output ("2") to replace the first one ("1"), then the third output ("3") to replace the second one, and so one.
I've seen some old answers on the Internet, that say there's the "flush" parameter which I can add my print statement. So I tried:
import time
for i in range (0, 20):
print(i, flush=True)
time.sleep(0.3)
Doesn't really change anything.
I'm on Mac OS X if that implies anything -
Thanks for any help

Use stdout
from sys import stdout
from time import sleep
for i in range(10):
stdout.write("\r%d" % i)
stdout.flush()
sleep(1)
Update
for i in range(10):
print("\r%d" % i, end="")
time.sleep(0.3)

if you are using terminal to run the program then :
for i in range(10):
stdout.write("\r%d" % i)
stdout.flush()
sleep(1)
but if you are running the program with idle then it wont work !

Assuming you use python 3, use '\r' to go to beginning of line and end="" to stay on the same line. Combined they give the effect you are looking for.
For example:
import time
print("\r[]", end="")
time.sleep(1)
print("\r []", end="")
time.sleep(1)
print("\r []", end="")
time.sleep(1)
print("\r []", end="")
time.sleep(1)
print("\r []", end="")

Related

How do I overwrite a line in Python

I have created a simple python program that will count up to 10
What I am trying to achieve is for the program to delete the previous number and print the new number
This is the code that I have created:
import sys
import time
for i in range(10):
text = "\r" + str(i)
sys.stdout.write(text)
sys.stdout.flush()
time.sleep(1)
Which outputs:
0123456789
Changing the code to have the "\r" after the str(i) didn't work either
import sys
import time
for i in range(10):
text = str(i) + "\r"
sys.stdout.write(text)
sys.stdout.flush()
time.sleep(1)
Which also resulted in:
0123456789
I was looking for it to count up, and display at the end only the 9 however it doesn't overwrite the previous numbers
Edit:
I am using Windows, Python3
Edit 2:
How to overwrite the previous print to stdout in python? Does not give me a working answer, it still doesn't do what I want
Therefore due to my excellent reasoning it is not a duplicate :P
As an alternative, you can clear the whole window, by using os.system("cls")
There are some control symbols accepted by virtual terminals. One of them is '\b' that moves a carret for one place back. This one is accepted on Windows too and I will use it in my example below. Unix terminals accept a lot more of controls including color changes and more.
from time import sleep
import sys, os
def clear ():
os.system("cls" if sys.platform.startswith("win") else "clear")
clear()
s = "1"
sys.stdout.write(s)
for x in range(2, 21):
sleep(1)
# Return carret to beginning of line:
l = len(s)
s = l*"\b"
sys.stdout.write(s)
# Clear line (just in case):
s = l*" "
sys.stdout.write(s)
# Return to the beginning again:
s = l*"\b"
sys.stdout.write(s)
# Write over new text:
s = str(x)
sys.stdout.write(s)
Use the end parameter to specify a "\r" as the line ending.
import time
for i in range(10):
print(i, end="\r")
time.sleep(1)
I would do it like this:
for x in range(10):
print("{}".format(x), end="\r")
I believe your code should work perfectly fine. The problem should be that you are using a Windows terminal. Try using Linux. Most code does not work in Windows. You can refer this link to know why you have to stop using python on Windows.
This is also an alternate code you can try.
import time
for i in range(10):
text = str(i)
print(text,end = "\r")
time.sleep(1)
Why not use the standard print of python? Althougth given in many debugger screens this tends to not work. In terminal (ubuntu) it does
import time
for i in range (10):
print(i, end='\r')
time.sleep(1)
Probably for stdout something exists too but in this case I usually use the print of python3

How to clear only last one line in python output console?

I am trying to clear only last few line from output console window. To achieve this I have decided to use create stopwatch and I have achieved to interrupt on keyboard interrupt and on enter key press it creates lap but my code only create lap once and my current code is clearing whole output screen.
clear.py
import os
import msvcrt, time
from datetime import datetime
from threading import Thread
def threaded_function(arg):
while True:
input()
lap_count = 0
if __name__ == "__main__":
# thread = Thread(target = threaded_function)
# thread.start()
try:
while True:
t = "{}:{}:{}:{}".format(datetime.now().hour, datetime.now().minute, datetime.now().second, datetime.now().microsecond)
print(t)
time.sleep(0.2)
os.system('cls||clear') # I want some way to clear only previous line instead of clearing whole console
if lap_count == 0:
if msvcrt.kbhit():
if msvcrt.getwche() == '\r': # this creates lap only once when I press "Enter" key
lap_count += 1
print("lap : {}".format(t))
time.sleep(1)
continue
except KeyboardInterrupt:
print("lap stop at : {}".format(t))
print(lap_count)
when I run
%run <path-to-script>/clear.py
in my ipython shell I am able to create only one lap but it is not staying for permanent.
To clear only a single line from the output :
print ("\033[A \033[A")
This will clear the preceding line and will place the cursor onto the beginning of the line.
If you strip the trailing newline then it will shift to the previous line as \033[A means put the cursor one line up
I think the simplest way is to use two print() to achieve clean the last line.
print("something will be updated/erased during next loop", end="")
print("\r", end="")
print("the info")
The 1st print() simply make sure the cursor ends at the end of the line and not start a new line
The 2nd print() would move the cursor to the beginning of the same line and not start a new line
Then it comes naturally for the 3rd print() which simply start print something where the cursor is currently at.
I also made a toy function to print progress bar using a loop and time.sleep(), go and check it out
def progression_bar(total_time=10):
num_bar = 50
sleep_intvl = total_time/num_bar
print("start: ")
for i in range(1,num_bar):
print("\r", end="")
print("{:.1%} ".format(i/num_bar),"-"*i, end="")
time.sleep(sleep_intvl)
The codes shared by Ankush Rathi above this comment are probably correct, except for the use of parenthesis in the print command. I personally recommend doing it like this.
print("This message will remain in the console.")
print("This is the message that will be deleted.", end="\r")
One thing to keep in mind though is that if you run it in IDLE by pressing F5, the shell will still display both messages. However, if you run the program by double clicking, the output console will delete it. This might be the misunderstanding that happened with Ankush Rathi's answer (in a previous post).
I know this is a really old question but i couldn't find any good answer at it. You have to use escape characters. Ashish Ghodake suggested to use this
print ("\033[A \033[A")
But what if the line you want to remove has more characters than the spaces in the string?
I think the better thing is to find out how many characters can fit in one of your terminal's lines and then to add the correspondent number of " " in the escape string like this.
import subprocess, time
tput = subprocess.Popen(['tput','cols'], stdout=subprocess.PIPE)
cols = int(tput.communicate()[0].strip()) # the number of columns in a line
i = 0
while True:
print(i)
time.sleep(0.1)
print("\033[A{}\033[A".format(' '*cols))
i += 1
finally I would say that the "function" to remove last line is
import subprocess
def remove():
tput = subprocess.Popen(['tput','cols'], stdout=subprocess.PIPE)
cols = int(tput.communicate()[0].strip())
print("\033[A{}\033[A".format(' '*cols))
For Python 3's, using f-String.
from time import sleep
for i in range(61):
print(f"\r{i}", end="")
sleep(0.1)
Found a solution on this page that works. Here is the helper function:
import sys
def delete_last_line():
"Deletes the last line in the STDOUT"
# cursor up one line
sys.stdout.write('\x1b[1A')
# delete last line
sys.stdout.write('\x1b[2K')
I hope it helps someone.
None of the other answers worked for me. Putting print("Sentence to be overwritten", end='\r') would instantly clear my sentence and it would never be visible to begin with. I'm using PyCharm on a Mac if that could be making the difference. What I had to do is the following:
from time import sleep
print("Sentence to be overwritten", end='')
sleep(1)
print("\r", end='')
print("Sentence to stay")
end='' makes it so the print doesn't automatically put a '\n' character at the end. Then print("\r", end='') will put the cursor at the beginning of the line. Then the 2nd print statement will be printed in the same spot as the first, overwriting it.
If you intend to delete certain line from the console output,
print "I want to keep this line"
print "I want to delete this line",
print "\r " # this is going to delete previous line
or
print "I want to keep this line"
print "I want to delete this line\r "

replace previous print output with new print output or add characters to previous output

I'm pretty new to Python programming, and I'm attempting to create a simple little game with a little "initialization" on boot up.
I pretty much want it to spell out "Welcome", but with all of the letters popping up every 100ms.
I've got the sleep function down pat, however, rather than adding on each character to the end of the previous line, it is simply printing it all out on a new line.
This is what I'm currently getting:
W
e
l
c
o
m
e
.
I'd prefer it to just be Welcome.
This is my current code:
print("W")
time.sleep(0.1)
print("e")
time.sleep(0.1)
print("l")
time.sleep(0.1)
print("c")
time.sleep(0.1)
print("o")
time.sleep(0.1)
print("m")
time.sleep(0.1)
print("e")
I have looked around, but have failed to understand how to implement the function into Python. So an explanation would be extremely appreciated!
Thanks.
Use end='' when calling print():
import time
for c in "Welcome":
print(c, end='')
time.sleep(0.1)
Python's print() function normally prints outputs on a new line, meaning that every time you print something, it appears on another line. To print everything on the same line, as you're asking, use the print() function like this:
print("W", end="")
Notice the second argument which tells Python to continue printing on the same line. The print() function defaults to an ending of \n, or new line. Setting end equal to "" replaced the \n with an empty string.
In the event that you need to use the print() function after you print out "Welcome", the last print() function you use to print out the 'e' should be normal, like this:
print("e")
This way if you print anything after "Welcome", it will print on a new line.
How about this -
for c in "Welcome":
print '\b%s' % c,
time.sleep(0.1)

Strange print behavior with time.sleep in python [duplicate]

This question already has an answer here:
Why doesn't print output show up immediately in the terminal when there is no newline at the end?
(1 answer)
Closed last month.
I was trying to create a progress-like thing by printing a dot every second on the same line. Something like "Fishing.....". This is what I used:
import time
print('Fishing', end='')
for i in range(5):
time.sleep(1)
print('.', end='')
But it waits for 5 seconds and prints Fishing..... all at once. But when I don't use the end='', it prints dots every second, but on separate lines like so
Fishing.
.
.
.
.
My questions:
Why does print behave this way?
How can I print a dot every second, but on the same line?
Why does print behave this way?
This has less to do with print and more with your terminal. For performance reasons, the text only gets "flushed" everytime there's a newline character, and not one character at a time.
How can I print a dot every second, but on the same line?
By "flushing" the standard output manually everytime you printed something:
import time
import sys
print('Fishing', end='')
sys.stdout.flush()
for i in range(5):
time.sleep(1)
print('.', end='', flush=True) # another way
If you need this all the time, you could define a seperate flushing print function:
from functools import partial
myprint = partial(print, end='', flush=True)
myprint('Fishing')
for i in range(5):
time.sleep(1)
myprint('.')
This is because print is considered to be an expensive operation: it will usually wait until it has to print a lot of data, or until a new line is encountered (usually only if output is written to a terminal):
Output buffering is determined by file. Use file.flush() to ensure, for instance, immediate appearance on a screen.
Evidently it is not expensive in the sense that it takes minutes: but asking the terminal operator to print new content, or the operating system to write data to a file (in case of I/O redirection) is still not "lightning fast".
You can force to print all data that is still in the queue, by using a flush on the standard output channel.
use
print('.', end="", flush=True)

Loading animation in python

Im new to python and was wondering how to make a loading animation while my program runs. I need this because I don't want users thinking that the program is caught in a dead loop. I prefer a something like...
Loading...(with the dots disappearing and reappearing one by one)
Thanks!
If your output window supports the carriage return character, you can print it to make the cursor return to the beginning of the current line (provided you end your print statement with a comma, so a newline character isn't automatically printed). Then subsequent prints will overwrite what was already printed. You can use this to do very simple one line animation. Example:
import time
print "Starting program."
print "Loading ",
time.sleep(1) #do some work here...
print "\rLoading. ",
time.sleep(1) #do some more work here...
print "\rLoading.. ",
time.sleep(1) #do even more work...
print "\rLoading...",
time.sleep(1) #gratuitious amounts of work...
print "\rLoading ",
... Where time.sleep(1) is a placeholder representing the actual work you want to do.
Result:
Starting program.
Loading
Then, one second later:
Starting program.
Loading.
Then, one second later:
Starting program.
Loading..
Then, one second later:
Starting program.
Loading...
Then, one second later:
Starting program.
Loading
etc.
Compatibility note: in 3.X, print is no longer a statement, and the "end with a comma" trick no longer works. Instead, specify the end parameter:
print("\rLoading...", end="")
The most proper way I can think of to do it would be using threading.
You would initiate a thread that starts displaying some indication that the program is doing something and then open a new thread that actually does the work.
When the thread doing the work finished then you can move on with whatever else the program does.
This looks ok when ran in windows command prompt, not sure how linux will like it:
import threading
import time
import os
import queue
q = queue.Queue()
q.put(False)
class counter(object):
def __init__(self):
wait_label = "Loading"
self.stop_flag = q.get()
while not self.stop_flag:
try:
self.stop_flag = q.get_nowait()
except:
pass
os.system('cls') # might need to change this command for linux
wait_label += "."
print(wait_label)
time.sleep(1)
class other(counter):
def __init__(self):
time.sleep(15)
q.put(True)
counter_thread = threading.Thread(None, counter)
counter_thread.start()
other_thread = threading.Thread(None, other)
other_thread.start()
To reduce the code length, we can loop it.
import time
# flag variable to print the dots and it's value increases inside the while loop.
flag = 1
# To print the dots we use while loop. In total, 4 dots will be printed.
while flag < 5:
print("\rLoading, Please Wait " + ("." * flag), end=" ")
time.sleep(1)
flag = flag + 1

Categories

Resources