Replace console output in Python
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Lost Jungle Looping
--
Chapters
00:00 Replace Console Output In Python
00:31 Accepted Answer Score 210
01:07 Answer 2 Score 75
01:37 Answer 3 Score 45
02:07 Answer 4 Score 14
02:21 Thank you
--
Full question
https://stackoverflow.com/questions/6169...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python
#avk47
ACCEPTED ANSWER
Score 210
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()
ANSWER 2
Score 75
A more elegant solution could be:
def progress_bar(current, total, bar_length=20):
    fraction = current / total
    arrow = int(fraction * bar_length - 1) * '-' + '>'
    padding = int(bar_length - len(arrow)) * ' '
    ending = '\n' if current == total else '\r'
    print(f'Progress: [{arrow}{padding}] {int(fraction*100)}%', end=ending)
Call this function with current and total:
progress_bar(69, 100)
The result should be
Progress: [------------->      ] 69%
Note:
- For Python 3.6 and below
 - For Python 2.x.
 
ANSWER 3
Score 45
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.
ANSWER 4
Score 14
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)