Python: multiple prints on the same line

2018-12-31 17:51发布

I want to run a script, which basicly shows things like:

Installing XXX...               [DONE]

Now, at the moment, I use print to print the whole line AFTER the function has succeeded. However, I now want it to print "Installing xxx..." first, and AFTER the function has run, to add the "DONE" tag; but on the same line.

Any ideas?

14条回答
梦该遗忘
2楼-- · 2018-12-31 18:46

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.

查看更多
伤终究还是伤i
3楼-- · 2018-12-31 18:46

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%"),
查看更多
登录 后发表回答