How to overwrite the previous print to stdout in python?

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

提交回复
热议问题