Remove and Replace Printed items
Just use CR to go to beginning of the line.
import time
for x in range (0,5):
b = "Loading" + "." * x
print (b, end="\r")
time.sleep(1)
C - Remove and replace printed items
Use the \b
(backspace) character.
printf("Quick brown fox");
int i;
for(i=0; i < 9; i++)
{
printf("\b");
}
printf("green fox\n");
I noticed that putting a \n
on the first printf()
messed up the output.
How to overwrite the previous print to stdout?
Simple Version
One way is to use the carriage return ('\r'
) character to return to the start of the line without advancing to the next line.
Python 3
for x in range(10):
print(x, end='\r')
print()
Python 2.7 forward compatible
from __future__ import print_function
for x in range(10):
print(x, end='\r')
print()
Python 2.7
for x in range(10):
print '{}\r'.format(x),
print
Python 2.0-2.6
for x in range(10):
print '{0}\r'.format(x),
print
In the latter two (Python 2-only) cases, the comma at the end of the print statement tells it not to go to the next line. The last print statement advances to the next line so your prompt won't overwrite your final output.
Line Cleaning
If you can’t guarantee that the new line of text is not shorter than the existing line, then you just need to add a “clear to end of line” escape sequence, '\x1b[1K'
('\x1b'
= ESC):
for x in range(75):
print('*' * (75 - x), x, end='\x1b[1K\r')
print()
Is it possible to update a line of already printed text in python?
You might be able to do this in a limited way by writing out '\b'
to erase and rewrite.
import sys
def foo()
sys.stdout.write('foo')
sys.stdout.flush()
sys.stdout.write('\b\b\b')
sys.stdout.write('bar')
sys.stdout.flush()
I'm doing a similar thing on the command line, on a Mac. And this has worked so far, as long as I haven't already written out a newline. (Hence sys.stdout.write
and not print
.)
Print updated string without showing previous one
You can use the curses
library
import time
import curses
screen = curses.initscr()
now = time.time()
future = now + 10
while time.time() < future:
screen.erase()
screen.addstr(str(time.time()))
screen.refresh()
pass
curses.endwin()
How to overwrite previous printed text?
Here is a solution that updates both time, and currency.
It's by simply clearing the terminal window before each time you get updated data.
import requests
import os
import sys
import time
def clear():
if sys.platform=="win32":
os.system("cls") # cmd clear command for Windows systems
elif sys.platform in ["linux", "darwin"]:
os.system("clear") # terminal clear command for Linux and Mac OS
else:
raise OSError("Uncompatible Operating-System.")
while True:
main_api = ('https://api.coindesk.com/v1/bpi/currentprice.json')
json_data = requests.get(main_api).json()
json_updated = json_data['time']['updated']
json_value = json_data['bpi']['USD']['rate']
time.sleep(1)
clear()
print('\n' 'Last Updated: ' + json_updated)
print('\n' "Bitcoin price: " + json_value + " USD")
You can also add a line for the current hour if it looks freezed.
import requests
import os
import sys
import time
from datetime import datetime
def clear():
if sys.platform=="win32":
os.system("cls") # cmd clear command for Windows systems
elif sys.platform in ["linux", "darwin"]:
os.system("clear") # terminal clear command for Linux and Mac OS
else:
raise OSError("Uncompatible Operating-System.")
while True:
main_api = ('https://api.coindesk.com/v1/bpi/currentprice.json')
json_data = requests.get(main_api).json()
json_updated = json_data['time']['updated']
json_value = json_data['bpi']['USD']['rate']
time.sleep(1)
clear()
print('\n' "Current date and time :", str(datetime.now())[:-7])
print('\n' 'Last Updated: ' + json_updated)
print('\n' "Bitcoin price: " + json_value + " USD")
It should help, unless you don't want your screen cleared.
Python 3.8: Overwrite and clear previous shorter line in terminal
I have found a decent work around for this problem. You can just fill the end of the string with white spaces with f strings. The full code for the problem I stated in the question would then be:
print('Tessst', end='\r')
print(f'{"Test" : <10}')
I found this way here
How can I replace a printed line with a new printed line?
use end=""
in the first print
, default value of end
is a new line
but you can change it by passing your own value:
print("Downloading...",end="")
#your code here
print("Done!")
output:
Downloading...Done!
help on print
:
In [3]: print?
Type: builtin_function_or_method
String Form:<built-in function print>
Namespace: Python builtin
Docstring:
print(value, ..., sep=' ', end='\n', file=sys.stdout)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
Replace the printed line above with a different value
\r
doesn't clear the line. It simply moves the cursor to the start of the line. You need to actually clear the line, either by explicitly clearing it before you write Loading.
, or by writing Loading.
(notice the extra spaces after the period) to overwrite the extra periods.
import time
def exitpro(t):
a=0
while t>=0:
dotcount = (a % 3) + 1
timer="Loading" + "." * dotcount + " " * (3 - dotcount)
print(timer, end='\r', flush=True)
time.sleep(1)
t-=1
a+=1
t=int(input("enter time in seconds "))
exitpro(t)
flush=True
forces the output to print immediately instead of waiting to be buffered.
Related Topics
Including Non-Python Files with Setup.Py
Multiprocessing: Sharing a Large Read-Only Object Between Processes
Insert a Row to Pandas Dataframe
Importing an Ipynb File from Another Ipynb File
How to Make an Exe File from a Python Program
Numpy "Where" with Multiple Conditions
Find and Replace String Values in List
How to Manually Install a Pypi Module Without Pip/Easy_Install
How to Access the Child Classes of an Object in Django Without Knowing the Name of the Child Class
How to Verify If One List Is a Subset of Another
Generate a Random Date Between Two Other Dates
Generating a List of Random Numbers, Summing to 1
Python String Prints as [U'String']
How to Clear the Screen in Python
Finding Median of List in Python