How to overwrite the previous print to stdout in python?

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

提交回复
热议问题