我想运行一个脚本,它基本上显示如下输出:

Installing XXX...               [DONE]

目前,我打印安装XXX…首先,然后打印[完成]。

我怎么能打印安装xxx…和[DONE]在同一行?


关于在同一行上写入新消息,替换之前的内容的具体问题,请参见如何将先前的打印内容覆盖到标准输出?。这里的大多数答案都把这个问题理解为在当前行的末尾写新的文本。

有关使用单个打印一次输出多个内容的问题,请参见如何在同一行上一次性打印多个内容(固定文本和/或变量值)。


当前回答

Sys.stdout.write将输出没有返回符

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

其他回答

Python 3解决方案

print()函数接受一个结束参数,默认为\n(新行)。将其设置为空字符串可防止它在行尾发出新行。

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

install_xxx()
print("[DONE]")

Python 2解决方案

在print()行末尾使用逗号可以防止print()输出新的行(您应该注意,在输出的末尾会有一个额外的空格)。

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

install_xxx()
print "[DONE]"

Sys.stdout.write将输出没有返回符

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

您应该使用退格'\r'或('\x08')字符返回控制台输出中的先前位置

Python 2 +:

import time
import sys

def backspace(n):
    sys.stdout.write((b'\x08' * n).decode()) # use \x08 char to go back   

for i in range(101):                        # for 0 to 100
    s = str(i) + '%'                        # string for output
    sys.stdout.write(s)                     # just print
    sys.stdout.flush()                      # needed for flush when using \x08
    backspace(len(s))                       # back n chars    
    time.sleep(0.2)                         # sleep for 200ms

Python 3:

import time   

def backline():        
    print('\r', end='')                     # use '\r' to go back


for i in range(101):                        # for 0 to 100
    s = str(i) + '%'                        # string for output
    print(s, end='')                        # just print and flush
    backline()                              # back to the beginning of line    
    time.sleep(0.2)                         # sleep for 200ms

这段代码将在一行中从0%计算到100%。最终值为:

> python test.py
100%

关于这种情况下flush的其他信息:为什么python打印包含'end='参数的语句在while循环中表现不同?

Python 3中的解决方案。X具体:

当我需要这样做的时候,我通常只用

end=' '

例如:

# end='' ends the output with a <space> 
print("Welcome to" , end = ' ') 
print("stackoverflow", end = ' ')

输出如下:

Welcome to stackoverflow

end=中的空格可以替换为任何字符。例如,

print("Welcome to" , end = '...') 
print("stackoverflow", end = '!')

输出如下:

Welcome to...stackoverflow!

你可以简单地使用这个:

print 'something',
...
print ' else',

输出将是

something else

不需要过多的导入系统。注意结尾的逗号符号。

Python 3 + Print ("some string", end="");删除末尾的换行插入。阅读更多帮助(打印);