且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Python 中的同一行上打印多个

更新时间:2023-11-22 13:33:46

您可以使用 print 语句完成此操作,而无需导入 sys.

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

def install_xxx():
   print "Installing XXX...      ",

install_xxx()
print "[DONE]"

print 行末尾的逗号阻止 print 发出新行(您应该注意输出末尾会有一个额外的空格).

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).

Python 3 解决方案
由于以上在 Python 3 中不起作用,您可以改为执行此操作(同样,无需导入 sys):

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

install_xxx()
print("[DONE]")

打印函数接受一个 end 参数,默认为 " ".将其设置为空字符串可防止它在行尾发出新行.

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