How to overwrite the previous print to stdout in python?

后端 未结 16 1414
别那么骄傲
别那么骄傲 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:34

    Try this:

    import time
    while True:
        print("Hi ", end="\r")
        time.sleep(1)
        print("Bob", end="\r")
        time.sleep(1)
    

    It worked for me. The end="\r" part is making it overwrite the previous line.

    WARNING!

    If you print out hi, then print out hello using \r, you’ll get hillo because the output wrote over the previous two letters. If you print out hi with spaces (which don’t show up here), then it will output hi. To fix this, print out spaces using \r.

    0 讨论(0)
  • 2020-11-22 10:35

    Here's a cleaner, more "plug-and-play", version of @Nagasaki45's answer. Unlike many other answers here, it works properly with strings of different lengths. It achieves this by clearing the line with just as many spaces as the length of the last line printed print. Will also work on Windows.

    def print_statusline(msg: str):
        last_msg_length = len(print_statusline.last_msg) if hasattr(print_statusline, 'last_msg') else 0
        print(' ' * last_msg_length, end='\r')
        print(msg, end='\r')
        sys.stdout.flush()  # Some say they needed this, I didn't.
        print_statusline.last_msg = msg
    

    Usage

    Simply use it like this:

    for msg in ["Initializing...", "Initialization successful!"]:
        print_statusline(msg)
        time.sleep(1)
    

    This small test shows that lines get cleared properly, even for different lengths:

    for i in range(9, 0, -1):
        print_statusline("{}".format(i) * i)
        time.sleep(0.5)
    
    0 讨论(0)
  • 2020-11-22 10:38

    (Python3) This is what worked for me. If you just use the \010 then it will leave characters, so I tweaked it a bit to make sure it's overwriting what was there. This also allows you to have something before the first print item and only removed the length of the item.

    print("Here are some strings: ", end="")
    items = ["abcd", "abcdef", "defqrs", "lmnop", "xyz"]
    for item in items:
        print(item, end="")
        for i in range(len(item)): # only moving back the length of the item
            print("\010 \010", end="") # the trick!
            time.sleep(0.2) # so you can see what it's doing
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题