How to Overwrite the Previous Print to Stdout

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()

Overwrite the previous print value in python?

Check this curses library, The curses library supplies a terminal-independent screen-painting and keyboard-handling facility for text-based terminals. An example:

x.py:

from curses import wrapper
def main(stdscr):
stdscr.addstr(1, 0, 'Program is running..')
# Clear screen
stdscr.clear() # clear above line.
stdscr.addstr(1, 0, 'hello')
stdscr.addstr(2, 0, 'dude')
stdscr.addstr(3, 0, 'Press Key to exit: ')
stdscr.refresh()
stdscr.getkey()

wrapper(main)
print('bye')

run it python x.py

Output to the same line overwriting previous output?

Here's code for Python 3.x:

print(os.path.getsize(file_name)/1024+'KB / '+size+' KB downloaded!', end='\r')

The end= keyword is what does the work here -- by default, print() ends in a newline (\n) character, but this can be replaced with a different string. In this case, ending the line with a carriage return instead returns the cursor to the start of the current line. Thus, there's no need to import the sys module for this sort of simple usage. print() actually has a number of keyword arguments which can be used to greatly simplify code.

To use the same code on Python 2.6+, put the following line at the top of the file:

from __future__ import print_function

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 to overwrite a long string print in python?

Maybe you can try this:

import time
import sys

CURSOR_UP_ONE = '\x1b[1A'
ERASE_LINE = '\x1b[2K'

for x in range(100):
print(x, "timesjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj")
sys.stdout.write(CURSOR_UP_ONE*2)
sys.stdout.write(ERASE_LINE)

time.sleep(0.2)

And the count of CURSOR_UP_ONE depends on the length of the string and the width of the terminal window.

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.

How to overwrite console output?

Once you print something, then to erase it, you have not other alternative else than clear the screen. In Windows use:

import os
os.system('cls')

And in linux call clear command. And then print other things.



Related Topics



Leave a reply



Submit