How do I overwrite a line in Python - 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

Related

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 "

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

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="")

PyCharm print end='\r' statement not working

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)

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

Is there a way to clear your printed text in python?

I have wanted for a long time to find out how to clear something like print("example") in python, but I cant seem to find anyway or figure anything out.
print("Hey")
>Hey
Now I need to clear it, and write some new text.
print("How is your day?")
It would print.
Hey
>How is your day?
But I want to clear the "Hey" so the user shouldnt look at both at same time, and it looks kinda messy.
import os
os.system('cls')
Or os.system('clear') on unix (mac and linux). If you don't want the scroll up either, then you can do this:
os.system("printf '\033c'") should get rid of scroll back too. Something that works on all systems:
import os
os.system('cls' if os.name == 'nt' else "printf '\033c'")
I think this is what you want to do:
take the cursor one line up and delete the line
this can be done like using the code below
import sys
import time
def delete_last_line():
"Use this function to delete the last line in the STDOUT"
#cursor up one line
sys.stdout.write('\x1b[1A')
#delete last line
sys.stdout.write('\x1b[2K')
########## FOR DEMO ################
if __name__ == "__main__":
print("hello")
print("this line will be delete after 2 seconds")
time.sleep(2)
delete_last_line()
####################################
Small addition into #Aniket Navlur 's answer in order to delete multiple lines:
def delete_multiple_lines(n=1):
"""Delete the last line in the STDOUT."""
for _ in range(n):
sys.stdout.write("\x1b[1A") # cursor up one line
sys.stdout.write("\x1b[2K") # delete the last line
Well I have a temporary way:
print("Hey", end="")
for i in range(4):
print('\b', end = '')
print("How is your day?")
The escape character \r (carriage return), means "start printing from beginning of this line".
But some of operating systems use it as 'newline'.
Following would work in Linux:
import time
import sys
#first text
print('Hey.', end="")
#flush stdout
sys.stdout.flush()
#wait a second
time.sleep(1)
#write a carriage return and new text
print('\rHow is your day?')

Categories

Resources