如何在同一行上一次打印多个内容?

发布于 2024-10-31 09:09:18 字数 578 浏览 7 评论 0原文

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

Installing XXX...               [DONE]

当前,我首先打印 Installing XXX...,然后打印 [DONE]

如何在同一行打印 Installing xxx...[DONE]


对于在同一行写入新消息替换之前的消息的具体问题,请参阅如何覆盖以前的打印到标准输出?。这里的大多数答案将问题解释为关于在当前行的末尾写入新文本。

对于使用单个 print 要一次输出多个内容,请参阅如何在同一行,一次?.

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

How can I instead print Installing xxx... and [DONE] on the same line?


For the specific problem of writing a new message on the same line, replacing what was there before, please see How to overwrite the previous print to stdout?. Most answers here interpreted the question as being about writing new text at the end of the current line.

For the problem of using a single print to output multiple things at once, see How can I print multiple things (fixed text and/or variable values) on the same line, all at once?.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(18

生来就爱笑 2024-11-07 09:09:18

Python 3 解决方案

print() 函数接受 end 参数,默认为 \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]"

Python 3 Solution

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

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

install_xxx()
print("[DONE]")

Python 2 Solution

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

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

install_xxx()
print "[DONE]"
棒棒糖 2024-11-07 09:09:18

您可以简单地使用这个:

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

爱情眠于流年 2024-11-07 09:09:18

您应该使用退格键 '\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%

在这种情况下有关刷新的其他信息在这里:为什么包含 'end=' 参数的 python print 语句在 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?

围归者 2024-11-07 09:09:18

使用 sys.stdout.write('安装 XXX...') 和 sys.stdout.write('完成')。这样,如果您想重新创建打印功能,则必须使用 "\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.

夏至、离别 2024-11-07 09:09:18

最简单:

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.

心凉怎暖 2024-11-07 09:09:18

所有答案都不适合我,因为它们都暂停直到遇到新行。我写了一个简单的助手:

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.

时光暖心i 2024-11-07 09:09:18

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

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

心头的小情儿 2024-11-07 09:09:18

Python 附加换行符作为打印的结尾。对于 python3 的 print 方法使用 end=' ' 来附加空格而不是换行符。对于 python2,在 print 语句末尾使用逗号。

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')
地狱即天堂 2024-11-07 09:09:18

这个简单的示例将在同一行上打印 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=" ")
被翻牌 2024-11-07 09:09:18

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="")

心凉怎暖 2024-11-07 09:09:18

如果要覆盖上一行(而不是不断添加),可以在 print 语句末尾将 \rprint(), 结合起来。例如,

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%"),
夏至、离别 2024-11-07 09:09:18

这里是 @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 解决方案看起来有点臃肿。例如,退格方法不使用整数参数,可能可以完全取消。

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.

笔落惊风雨 2024-11-07 09:09:18

这是一个非常古老的线程,但这里有一个非常彻底的答案和示例代码。

\r 是 ASCII 字符集中回车符的字符串表示形式。它与八进制 015 [chr(0o15)] 或十六进制 0d [chr(0x0d)] 相同或十进制 13 [chr(13)]。请参阅 man ascii 进行无聊的阅读。它(\r)是一种非常可移植的表示形式,并且很容易让人们阅读。它的意思很简单,就是将打字机上的滑架一直移回到起始位置,而不推进纸张。它是 CRLFCR 部分,表示回车换行

print() 是 Python 3 中的一个函数。在 Python 2(您有兴趣使用的任何版本)中,可以通过导入 print 来将其强制为函数来自 __future__ 模块的定义。 print 函数的好处是您可以指定在末尾打印什么内容,覆盖 \n 的默认行为以在每个 末尾打印换行符>print() 调用。

sys.stdout.flush 告诉 Python 刷新标准输出的输出,这是您使用 print() 发送输出的位置,除非您另外指定。您还可以通过使用 python -u 运行或设置环境变量 PYTHONUNBUFFERED=1 来获得相同的行为,从而跳过 import syssys.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()
岁月无声 2024-11-07 09:09:18

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!

This solution in Python 3.X specific:

When I need to do this, I'll generally just use

end=' '

For example:

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

This outputs as:

Welcome to stackoverflow

The space in end= can be replaced with any character. For example,

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

Which outputs as:

Welcome to...stackoverflow!
昵称有卵用 2024-11-07 09:09:18

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 ="")

青朷 2024-11-07 09:09:18

如果您已将值预先存储在数组中,则可以按以下格式调用它们:

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],
最好是你 2024-11-07 09:09:18

找到了这个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=""

明明#如月 2024-11-07 09:09:18

我找到了这个解决方案,它适用于 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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文