Unprint a line on the console in Python?

后端 未结 3 1745
难免孤独
难免孤独 2020-12-17 03:16

Is it possible to manipulate lines of text that have already been printed to the console?

For example,

import time
for k in range(1,100):
     print(         


        
相关标签:
3条回答
  • 2020-12-17 03:24

    The simplest method (at least for Python 2.7) is to use the syntax:

    print 'message', '\r',
    print 'this new message now covers the previous'
    

    Notice the extra ',' at the end of the first print. This makes print stay on the same line. Meanwhile, the '\r' puts the print at the beginning of that line. So the second print statement overwrites the first.

    0 讨论(0)
  • 2020-12-17 03:36

    What you're looking for is:

    print("{}/100".format(k), "\r", end="")
    

    \r is carriage return, which returns the cursor to the beginning of the line. In effect, whatever is printed will overwrite the previous printed text. end="" is to prevent \n after printing (to stay on the same line).

    A simpler form as suggested by sonrad10 in the comments:

    print("{}/100".format(k), end="\r")
    

    Here, we're simply replacing the end character with \r instead of \n.

    In Python 2, the same can be achieved with:

    print "{}/100".format(k), "\r",
    
    0 讨论(0)
  • 2020-12-17 03:47

    What you need are ANSI Command Codes. http://en.wikipedia.org/wiki/ANSI_escape_code#CSI_codes
    You also need code to activate ANSI Command Codes. I would use Colorama. https://pypi.python.org/pypi/colorama

    OR

    Use curses (Python 3.4+) module.

    0 讨论(0)
提交回复
热议问题