Print in one line dynamically

后端 未结 20 3238
梦谈多话
梦谈多话 2020-11-21 23:32

I would like to make several statements that give standard output without seeing newlines in between statements.

Specifically, suppose I have:

for it         


        
20条回答
  •  臣服心动
    2020-11-21 23:49

    By the way...... How to refresh it every time so it print mi in one place just change the number.

    In general, the way to do that is with terminal control codes. This is a particularly simple case, for which you only need one special character: U+000D CARRIAGE RETURN, which is written '\r' in Python (and many other languages). Here's a complete example based on your code:

    from sys import stdout
    from time import sleep
    for i in range(1,20):
        stdout.write("\r%d" % i)
        stdout.flush()
        sleep(1)
    stdout.write("\n") # move the cursor to the next line
    

    Some things about this that may be surprising:

    • The \r goes at the beginning of the string so that, while the program is running, the cursor will always be after the number. This isn't just cosmetic: some terminal emulators get very confused if you do it the other way around.
    • If you don't include the last line, then after the program terminates, your shell will print its prompt on top of the number.
    • The stdout.flush is necessary on some systems, or you won't get any output. Other systems may not require it, but it doesn't do any harm.

    If you find that this doesn't work, the first thing you should suspect is that your terminal emulator is buggy. The vttest program can help you test it.

    You could replace the stdout.write with a print statement but I prefer not to mix print with direct use of file objects.

提交回复
热议问题