Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace console output in Python

Tags:

python

People also ask

How do you overwrite text in console Python?

Approach. By default, Python's print statement ends each string that is passed into the function with a newline character, \n . This behavior can be overridden with the function's end parameter, which is the core of this method. Rather than ending the output with a newline, we use a carriage return.

How do you change print lines in Python?

The new line character in Python is \n . It is used to indicate the end of a line of text. You can print strings without adding a new line with end = <character> , which <character> is the character that will be used to separate the lines.

How do you clear the console in Python?

The commands used to clear the terminal or Python shell are cls and clear.


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 startProgress(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 endProgress():
    sys.stdout.write("#" * (40 - progress_x) + "]\n")
    sys.stdout.flush()

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


A more elegant solution could be:

def progressBar(current, total, barLength = 20):
    percent = float(current) * 100 / total
    arrow   = '-' * int(percent/100 * barLength - 1) + '>'
    spaces  = ' ' * (barLength - len(arrow))

    print('Progress: [%s%s] %d %%' % (arrow, spaces, percent), end='\r')

call this function with value and endvalue, result should be

Progress: [------------->      ] 69 %

Note: Python 2.x version here.


In python 3 you can do this to print on the same line:

print('', end='\r')

Especially useful to keep track of the latest update and progress.

I would also recommend tqdm from here if one wants to see the progress of a loop. It prints the current iteration and total iterations as a progression bar with an expected time of finishing. Super useful and quick. Works for python2 and python3.


I wrote this a while ago and really happy with it. Feel free to use it.

It takes an index and total and optionally title or bar_length. Once done, replaces the hour glass with a check-mark.

⏳ Calculating: [████░░░░░░░░░░░░░░░░░░░░░] 18.0% done

✅ Calculating: [█████████████████████████] 100.0% done

I included an example that can be run to test it.

import sys
import time

def print_percent_done(index, total, bar_len=50, title='Please wait'):
    '''
    index is expected to be 0 based index. 
    0 <= index < total
    '''
    percent_done = (index+1)/total*100
    percent_done = round(percent_done, 1)

    done = round(percent_done/(100/bar_len))
    togo = bar_len-done

    done_str = '█'*int(done)
    togo_str = '░'*int(togo)

    print(f'\t⏳{title}: [{done_str}{togo_str}] {percent_done}% done', end='\r')

    if round(percent_done) == 100:
        print('\t✅')


r = 50
for i in range(r):
    print_percent_done(i,r)
    time.sleep(.02)

I also have a version with responsive progress bar depending on the terminal width using shutil.get_terminal_size() if that is of interest.


It can be done without using the sys library if we look at the print() function

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Here is my code:

def update(n):
    for i in range(n):
        print("i:",i,sep='',end="\r",flush=True)
        #time.sleep(1)