Replace Console Output in Python

Replace console output in Python

An easy solution is just writing "\r" before the string and not adding a newline; if the string never gets shorter this is sufficient...

sys.stdout.write("\rDoing thing %i" % i)
sys.stdout.flush()

Slightly more sophisticated is a progress bar... this is something I am using:

def start_progress(title):
global progress_x
sys.stdout.write(title + ": [" + "-"*40 + "]" + chr(8)*41)
sys.stdout.flush()
progress_x = 0

def progress(x):
global progress_x
x = int(x * 40 // 100)
sys.stdout.write("#" * (x - progress_x))
sys.stdout.flush()
progress_x = x

def end_progress():
sys.stdout.write("#" * (40 - progress_x) + "]\n")
sys.stdout.flush()

You call start_progress passing the description of the operation, then progress(x) where x is the percentage and finally end_progress()

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.

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

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

Is there a way to make the console or terminal output change by just changing a variale in the python script

Since a,b,c are variables they are stored in memory that is allocated to the script during run time.

you can't change those values without re-running the script, which will freeup the old memory, reallocate new memory, and run your code.

I suspect your need for implementing such a solution, changing vars like this; will be way more work than you'll be comfortable implementing (the solution to this can be intermediate project on its own)

you are better of reading values into these vars from a file or db.

with open('filefora.txt', 'r') as f:
a = int(f.readline())
with open('fileforb.txt', 'r') as f:
b = int(f.readline())
while True:
if a and b:
print(True)
else:
print(False)
with open('filefora.txt', 'r') as f:
a = int(f.readline())
with open('fileforb.txt', 'r') as f:
b = int(f.readline())

Now every time you change the value in the file for the respective var, the code will use that new value without having to rerun the script.

Even better would be to just rerun the file.

python: replace a printed line's text with another line

You can use \r (carriage return). Also you don't need num as en extra variable to index lst you can use existing i to index lst

import time
lst = ["|","/","-","\\"]
num = 0
for i in range(500):
print(lst[i % 4], end="\r") # i will be between 0 and 3 both inclusive
time.sleep(0.2)

How to edit console output

Well, if You want to gain full control over the terminal, I would suggest to use the curses library.

The curses module provides an interface to the curses library, the
de-facto standard for portable advanced terminal handling.

Using it, You can edit multiple lines in terminal like this:

import curses
import time

stdscr = curses.initscr()

stdscr.addstr("line 1\n")
stdscr.addstr("line 2\n")
stdscr.refresh()
time.sleep(3)

stdscr.erase()
stdscr.addstr("edited line 1\n")
stdscr.addstr("edited line 2\n")
stdscr.refresh()
time.sleep(3)

curses.endwin()

The capabilities of this library are much greater though. Full tutorial here.



Related Topics



Leave a reply



Submit