How to overwrite the previous print to stdout in python?

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

    Here's my solution! Windows 10, Python 3.7.1

    I'm not sure why this code works, but it completely erases the original line. I compiled it from the previous answers. The other answers would just return the line to the beginning, but if you had a shorter line afterwards, it would look messed up like hello turns into byelo.

    import sys
    #include ctypes if you're on Windows
    import ctypes
    kernel32 = ctypes.windll.kernel32
    kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)
    #end ctypes
    
    def clearline(msg):
        CURSOR_UP_ONE = '\033[K'
        ERASE_LINE = '\x1b[2K'
        sys.stdout.write(CURSOR_UP_ONE)
        sys.stdout.write(ERASE_LINE+'\r')
        print(msg, end='\r')
    
    #example
    ig_usernames = ['beyonce','selenagomez']
    for name in ig_usernames:
        clearline("SCRAPING COMPLETE: "+ name)
    

    Output - Each line will be rewritten without any old text showing:

    SCRAPING COMPLETE: selenagomez
    

    Next line (rewritten completely on same line):

    SCRAPING COMPLETE: beyonce
    
    0 讨论(0)
  • 2020-11-22 10:19

    Simple Version

    One way is to use the carriage return ('\r') character to return to the start of the line without advancing to the next line.

    Python 3

    for x in range(10):
        print(x, end='\r')
    print()
    

    Python 2.7 forward compatible

    from __future__ import print_function
    for x in range(10):
        print(x, end='\r')
    print()
    

    Python 2.7

    for x in range(10):
        print '{}\r'.format(x),
    print
    

    Python 2.0-2.6

    for x in range(10):
        print '{0}\r'.format(x),
    print
    

    In the latter two (Python 2-only) cases, the comma at the end of the print statement tells it not to go to the next line. The last print statement advances to the next line so your prompt won't overwrite your final output.

    Line Cleaning

    If you can’t guarantee that the new line of text is not shorter than the existing line, then you just need to add a “clear to end of line” escape sequence, '\x1b[1K' ('\x1b' = ESC):

    for x in range(75):
        print(‘*’ * (75 - x), x, end='\x1b[1K\r')
    print()
    
    0 讨论(0)
  • 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%
    
    0 讨论(0)
  • 2020-11-22 10:24
    for x in range(10):
        time.sleep(0.5) # shows how its working
        print("\r {}".format(x), end="")
    

    time.sleep(0.5) is to show how previous output is erased and new output is printed "\r" when its at the start of print message , it gonna erase previous output before new output.

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

    This works on Windows and python 3.6

    import time
    for x in range(10):
        time.sleep(0.5)
        print(str(x)+'\r',end='')
    
    0 讨论(0)
  • 2020-11-22 10:27

    Suppress the newline and print \r.

    print 1,
    print '\r2'
    

    or write to stdout:

    sys.stdout.write('1')
    sys.stdout.write('\r2')
    
    0 讨论(0)
提交回复
热议问题