How to overwrite the previous print to stdout in python?

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

    The accepted answer is not perfect. The line that was printed first will stay there and if your second print does not cover the entire new line, you will end up with garbage text.

    To illustrate the problem save this code as a script and run it (or just take a look):

    import time
    
    n = 100
    for i in range(100):
        for j in range(100):
            print("Progress {:2.1%}".format(j / 100), end="\r")
            time.sleep(0.01)
        print("Progress {:2.1%}".format(i / 100))
    

    The output will look something like this:

    Progress 0.0%%
    Progress 1.0%%
    Progress 2.0%%
    Progress 3.0%%
    

    What works for me is to clear the line before leaving a permanent print. Feel free to adjust to your specific problem:

    import time
    
    ERASE_LINE = '\x1b[2K' # erase line command
    n = 100
    for i in range(100):
        for j in range(100):
            print("Progress {:2.1%}".format(j / 100), end="\r")
            time.sleep(0.01)
        print(ERASE_LINE + "Progress {:2.1%}".format(i / 100)) # clear the line first
    

    And now it prints as expected:

    Progress 0.0%
    Progress 1.0%
    Progress 2.0%
    Progress 3.0%
    

提交回复
热议问题