问题:在Python的同一行上有多个打印
我想运行一个脚本,该脚本基本上显示如下输出:
Installing XXX... [DONE]
目前,我Installing XXX...
先打印,然后再打印[DONE]
。
不过,我现在想打印Installing xxx...
并[DONE]
在同一行。
有任何想法吗?
I want to run a script, which basically shows an output like this:
Installing XXX... [DONE]
Currently, I print Installing XXX...
first and then I print [DONE]
.
However, I now want to print Installing xxx...
and [DONE]
on the same line.
Any ideas?
回答 0
您可以使用该print
语句执行此操作,而无需导入sys
。
def install_xxx():
print "Installing XXX... ",
install_xxx()
print "[DONE]"
行尾的逗号会print
阻止print
发出新行(您应注意,输出末尾会有多余的空格)。
Python 3解决方案
由于上述内容在Python 3中不起作用,因此您可以改为这样做(同样,不导入sys
):
def install_xxx():
print("Installing XXX... ", end="", flush=True)
install_xxx()
print("[DONE]")
打印功能接受end
默认值为的参数"\n"
。将其设置为空字符串可防止它在该行的末尾发出新行。
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.
回答 1
您可以简单地使用:
print 'something',
...
print ' else',
和输出将是
something else
无需过度杀伤import sys
。注意末尾的逗号符号。
Python 3+
print("some string", end="");
删除结尾处的换行符。阅读更多help(print);
You can simply use this:
print 'something',
...
print ' else',
and the output will be
something else
no need to overkill by import sys
. Pay attention to comma symbol at the end.
Python 3+
print("some string", end="");
to remove the newline insert at the end. Read more by help(print);
回答 2
您应使用退格键’ \ r ‘或(’ \ x08 ‘)char返回控制台输出中的上一个位置
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%
在这种情况下,有关刷新的其他信息在这里:为什么包含’end =’参数的python打印语句在while循环中的行为不同?
You should use backspace ‘\r‘ or (‘\x08‘) char to go back on previous position in console output
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
This code will count from 0% to 100% on one line. Final value will be:
> python test.py
100%
Additional info about flush in this case here: Why do python print statements that contain ‘end=’ arguments behave differently in while-loops?
回答 3
使用sys.stdout.write('Installing XXX... ')
和sys.stdout.write('Done')
。这样,"\n"
如果要重新创建打印功能,则必须手动添加新行。我认为可能不必为此专门使用诅咒。
Use sys.stdout.write('Installing XXX... ')
and sys.stdout.write('Done')
. In this way, you have to add the new line by hand with "\n"
if you want to recreate the print functionality. I think that it might be unnecessary to use curses just for this.
回答 4
没有一个答案对我有用,因为它们都暂停了,直到遇到新的一行。我写了一个简单的助手:
def print_no_newline(string):
import sys
sys.stdout.write(string)
sys.stdout.flush()
要测试它:
import time
print_no_newline('hello ')
# Simulate a long task
time.sleep(2)
print('world')
“ hello”将首先打印出来,然后在睡眠前冲洗到屏幕。之后,您可以使用标准打印。
None of the answers worked for me since they all paused until a new line was encountered. I wrote a simple helper:
def print_no_newline(string):
import sys
sys.stdout.write(string)
sys.stdout.flush()
To test it:
import time
print_no_newline('hello ')
# Simulate a long task
time.sleep(2)
print('world')
“hello ” will first print out and flush to the screen before the sleep. After that you can use standard print.
回答 5
回答 6
最简单的:
Python 3
print('\r' + 'something to be override', end='')
这意味着它将把光标返回到开始处,而不是打印一些内容并在同一行结束。如果处于循环中,它将在开始的位置开始打印。
Most simple:
Python 3
print('\r' + 'something to be override', end='')
It means it will back the cursor to beginning, than will print something and will end in the same line. If in a loop it will start printing in the same place it starts.
回答 7
这个简单的示例将在同一行上打印1-10。
for i in range(1,11):
print (i, end=" ")
This simple example will print 1-10 on the same line.
for i in range(1,11):
print (i, end=" ")
回答 8
Print有一个可选end
参数,它是最终输出的内容。默认值为换行符,但您可以将其更改为空字符串。例如print("hello world!", end="")
Print has an optional end
argument, it is what printed in the end.
The default is a newline, but you can change it to empty string. e.g. print("hello world!", end="")
回答 9
如果你想覆盖前一行(而不是不断地增加它),你可以结合\r
使用 print(),
,在打印语句的结束。例如,
from time import sleep
for i in xrange(0, 10):
print("\r{0}".format(i)),
sleep(.5)
print("...DONE!")
将计数0到9,替换控制台中的旧数字。的"...DONE!"
将打印在同一行作为最后的反击,9。
对于OP,这将允许控制台将安装的完成百分比显示为“进度条”,您可以在其中定义开始和结束字符位置,并在其间更新标记。
print("Installing |XXXXXX | 30%"),
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%"),
回答 10
这里是@ Vadim-Zin4uk从3.0版本派生的2.7兼容版本:
Python 2
import time
for i in range(101): # for 0 to 100
s = str(i) + '%' # string for output
print '{0}\r'.format(s), # just print and flush
time.sleep(0.2)
为此,提供的3.0解决方案看起来有些looks肿。例如,退格方法不使用整数参数,可能完全可以使用。
Python 3
import time
for i in range(101): # for 0 to 100
s = str(i) + '%' # string for output
print('{0}\r'.format(s), end='') # just print and flush
time.sleep(0.2) # sleep for 200ms
两者都已经过测试和工作。
Here a 2.7-compatible version derived from the 3.0 version by @Vadim-Zin4uk:
Python 2
import time
for i in range(101): # for 0 to 100
s = str(i) + '%' # string for output
print '{0}\r'.format(s), # just print and flush
time.sleep(0.2)
For that matter, the 3.0 solution provided looks a little bloated. For example, the backspace method doesn’t make use of the integer argument and could probably be done away with altogether.
Python 3
import time
for i in range(101): # for 0 to 100
s = str(i) + '%' # string for output
print('{0}\r'.format(s), end='') # just print and flush
time.sleep(0.2) # sleep for 200ms
Both have been tested and work.
回答 11
这是一个非常古老的线程,但是这里有一个非常详尽的答案和示例代码。
\r
是ASCII字符集的回车的字符串表示形式。与八进制015
[ chr(0o15)
]或十六进制0d
[ chr(0x0d)
]或十进制13
[ chr(13)
]相同。请参阅man ascii
无聊的阅读。它(\r
)是一种可移植的表示形式,足以让人们阅读。这很简单,就是在不推进纸张的情况下将打字机上的笔架一直移动到起点。这是CR
一部分CRLF
,这意味着回车和换行。
print()
是Python 3中的函数。在Python 2(您可能会感兴趣的任何版本)中,print
可以通过从__future__
模块中导入函数的定义来强制使用该函数。该print
功能的好处在于,您可以指定在\n
结尾处打印的内容,而不是在每次print()
调用结束时打印换行符的默认行为。
sys.stdout.flush
告诉Python刷新标准输出的输出,print()
除非您另外指定,否则发送标准输出的位置。您还可以通过运行python -u
或设置环境变量来获得相同的行为PYTHONUNBUFFERED=1
,从而跳过import sys
和sys.stdout.flush()
调用。通过这样做,您获得的收益几乎完全为零,并且如果您方便地忘记了必须在应用程序正常运行之前执行该步骤,那么调试起来就不太容易。
和一个样本。请注意,这可以在Python 2或3中完美运行。
from __future__ import print_function
import sys
import time
ANS = 42
FACTORS = {n for n in range(1, ANS + 1) if ANS % n == 0}
for i in range(1, ANS + 1):
if i in FACTORS:
print('\r{0:d}'.format(i), end='')
sys.stdout.flush()
time.sleep(ANS / 100.0)
else:
print()
This is a very old thread, but here’s a very thorough answer and sample code.
\r
is the string representation of Carriage Return from the ASCII character set. It’s the same as octal 015
[chr(0o15)
] or hexidecimal 0d
[chr(0x0d)
] or decimal 13
[chr(13)
]. See man ascii
for a boring read. It (\r
) is a pretty portable representation and is easy enough for people to read. It very simply means to move the carriage on the typewriter all the way back to the start without advancing the paper. It’s the CR
part of CRLF
which means Carriage Return and Line Feed.
print()
is a function in Python 3. In Python 2 (any version that you’d be interested in using), print
can be forced into a function by importing its definition from the __future__
module. The benefit of the print
function is that you can specify what to print at the end, overriding the default behavior of \n
to print a newline at the end of every print()
call.
sys.stdout.flush
tells Python to flush the output of standard output, which is where you send output with print()
unless you specify otherwise. You can also get the same behavior by running with python -u
or setting environment variable PYTHONUNBUFFERED=1
, thereby skipping the import sys
and sys.stdout.flush()
calls. The amount you gain by doing that is almost exactly zero and isn’t very easy to debug if you conveniently forget that you have to do that step before your application behaves properly.
And a sample. Note that this runs perfectly in Python 2 or 3.
from __future__ import print_function
import sys
import time
ANS = 42
FACTORS = {n for n in range(1, ANS + 1) if ANS % n == 0}
for i in range(1, ANS + 1):
if i in FACTORS:
print('\r{0:d}'.format(i), end='')
sys.stdout.flush()
time.sleep(ANS / 100.0)
else:
print()
回答 12
print()具有内置参数“ end”,默认情况下设置为“ \ n”。调用print(“ This is America”)实际上是调用print(“ This is America”,end =“ \ n”)。一种简单的方法是调用print(“ This is America”,end =“”)
print() has a built in parameter “end” that is by default set to “\n”
Calling print(“This is America”) is actually calling print(“This is America”, end = “\n”).
An easy way to do is to call print(“This is America”, end =””)
回答 13
以防万一您已将值预先存储在数组中,可以按以下格式调用它们:
for i in range(0,n):
print arr[i],
Just in case you have pre-stored the values in an array, you can call them in the following format:
for i in range(0,n):
print arr[i],
回答 14
Python附加换行符作为打印结束。对于print3的python3使用end =”来添加空格而不是换行符。对于python2,请在打印语句末尾使用逗号。
print("Foo",end=' ')
print('Bar')
Python appends newline as an end to print. Use end=’ ‘ for python3 for print method to append a space instead of a newline. for python2 use comma at end of print statement.
print("Foo",end=' ')
print('Bar')
回答 15
找到此Quora帖子,并找到适用于我的示例(python 3),该示例更接近于我需要的示例(即,删除了前一行)。
他们提供的示例:
def clock():
while True:
print(datetime.now().strftime("%H:%M:%S"), end="\r")
如其他人所建议,要在同一行上打印,只需使用 end=""
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=""
回答 16
我找到了这个解决方案,并且可以在Python 2.7上运行
# Working on Python 2.7 Linux
import time
import sys
def backspace(n):
print('\r', end='') # use '\r' to go back
for i in range(101): # for 0 to 100
s = str(i) + '%' # string for output
sys.stdout.write(string)
backspace(len(s)) # back for n chars
sys.stdout.flush()
time.sleep(0.2) # sleep for 200ms
I found this solution, and it’s working on Python 2.7
# Working on Python 2.7 Linux
import time
import sys
def backspace(n):
print('\r', end='') # use '\r' to go back
for i in range(101): # for 0 to 100
s = str(i) + '%' # string for output
sys.stdout.write(string)
backspace(len(s)) # back for n chars
sys.stdout.flush()
time.sleep(0.2) # sleep for 200ms