multiple prints on the same line in Python

前端 未结 17 2266
独厮守ぢ
独厮守ぢ 2020-11-22 06:06

I want to run a script, which basically shows an output like this:

Installing XXX...               [DONE]

Currently, I print Installi

相关标签:
17条回答
  • 2020-11-22 06:28

    Found this Quora post, with this example which worked for me (python 3), which was closer to what I needed it for (i.e. erasing the whole previous line).

    The example they provide:

    def clock():
       while True:
           print(datetime.now().strftime("%H:%M:%S"), end="\r")
    

    For printing the on the same line, as others have suggested, just use end=""

    0 讨论(0)
  • 2020-11-22 06:30

    sys.stdout.write will print without return carriage

    import sys
    sys.stdout.write("installing xxx")
    sys.stdout.write(".")
    

    http://en.wikibooks.org/wiki/Python_Programming/Input_and_output#printing_without_commas_or_newlines

    0 讨论(0)
  • 2020-11-22 06:32

    This simple example will print 1-10 on the same line.

    for i in range(1,11):
        print (i, end=" ")
    
    0 讨论(0)
  • 2020-11-22 06:34

    You can use the print statement to do this without importing sys.

    def install_xxx():
       print "Installing XXX...      ",
    
    install_xxx()
    print "[DONE]"
    

    The comma on the end of the print line prevents print from issuing a new line (you should note that there will be an extra space at the end of the output).

    The Python 3 Solution
    Since the above does not work in Python 3, you can do this instead (again, without importing sys):

    def install_xxx():
        print("Installing XXX...      ", end="", flush=True)
    
    install_xxx()
    print("[DONE]")
    

    The print function accepts an end parameter which defaults to "\n". Setting it to an empty string prevents it from issuing a new line at the end of the line.

    0 讨论(0)
  • 2020-11-22 06:41

    If you want to overwrite the previous line (rather than continually adding to it), you can combine \r with print(), at the end of the print statement. For example,

    from time import sleep
    
    for i in xrange(0, 10):
        print("\r{0}".format(i)),
        sleep(.5)
    
    print("...DONE!")
    

    will count 0 to 9, replacing the old number in the console. The "...DONE!" will print on the same line as the last counter, 9.

    In your case for the OP, this would allow the console to display percent complete of the install as a "progress bar", where you can define a begin and end character position, and update the markers in between.

    print("Installing |XXXXXX              | 30%"),
    
    0 讨论(0)
提交回复
热议问题