How to overwrite the previous print to stdout in python?

后端 未结 16 1411
别那么骄傲
别那么骄傲 2020-11-22 09:46

If I had the following code:

for x in range(10):
     print x

I would get the output of

1
2
etc..

What I

16条回答
  •  北海茫月
    2020-11-22 10:38

    One more answer based on the prevous answers.

    Content of pbar.py: import sys, shutil, datetime

    last_line_is_progress_bar=False
    
    
    def print2(print_string):
        global last_line_is_progress_bar
        if last_line_is_progress_bar:
            _delete_last_line()
            last_line_is_progress_bar=False
        print(print_string)
    
    
    def _delete_last_line():
        sys.stdout.write('\b\b\r')
        sys.stdout.write(' '*shutil.get_terminal_size((80, 20)).columns)
        sys.stdout.write('\b\r')
        sys.stdout.flush()
    
    
    def update_progress_bar(current, total):
        global last_line_is_progress_bar
        last_line_is_progress_bar=True
    
        completed_percentage = round(current / (total / 100))
        current_time=datetime.datetime.now().strftime('%m/%d/%Y-%H:%M:%S')
        overhead_length = len(current_time+str(current))+13
        console_width = shutil.get_terminal_size((80, 20)).columns - overhead_length
        completed_width = round(console_width * completed_percentage / 100)
        not_completed_width = console_width - completed_width
        sys.stdout.write('\b\b\r')
    
        sys.stdout.write('{}> [{}{}] {} - {}% '.format(current_time, '#'*completed_width, '-'*not_completed_width, current,
                                            completed_percentage),)
        sys.stdout.flush()
    

    Usage of script:

    import time
    from pbar import update_progress_bar, print2
    
    
    update_progress_bar(45,200)
    time.sleep(1)
    
    update_progress_bar(70,200)
    time.sleep(1)
    
    update_progress_bar(100,200)
    time.sleep(1)
    
    
    update_progress_bar(130,200)
    time.sleep(1)
    
    print2('some text that will re-place current progress bar')
    time.sleep(1)
    
    update_progress_bar(111,200)
    time.sleep(1)
    
    print('\n') # without \n next line will be attached to the end of the progress bar
    print('built in print function that will push progress bar one line up')
    time.sleep(1)
    
    update_progress_bar(111,200)
    time.sleep(1)
    

提交回复
热议问题