How to reset cursor to the beginning of the same line in Python

后端 未结 6 1301
暖寄归人
暖寄归人 2020-12-05 06:48

Most of questions related to this topics here in SO is as follows:

How to print some information on the same line without introducing a new line

6条回答
  •  被撕碎了的回忆
    2020-12-05 07:18

    Python 3

    You can use keyword arguments to print:

    print('string', end='\r', flush=True)

    • end='\r' replaces the default end-of-line behavior with '\r'
    • flush=True flushes the buffer, making the printed text appear immediately.

    Python 2

    In 2.6+ you can use from __future__ import print_function at the start of the script to enable Python 3 behavior. Or use the old way:

    Python's print puts a newline after each command, unless you suppress it with a trailing comma. So, the print command is:

    print 'You have finished {0}%\r'.format(percentage),
    

    Note the comma at the end.

    Unfortunately, Python only sends the output to the terminal after a complete line. The above is not a complete line, so you need to flush it manually:

    import sys
    sys.stdout.flush()
    

提交回复
热议问题