我想做几个语句,给出标准输出,而不看到换行之间的语句。

具体来说,假设我有:

for item in range(1,100):
    print item

结果是:

1
2
3
4
.
.
.

如何让它看起来像:

1 2 3 4 5 ...

更好的是,是否可以将单个数字打印在最后一个数字之上,这样一次只有一个数字出现在屏幕上?


当前回答

我认为一个简单的连接应该工作:

nl = []
for x in range(1,10):nl.append(str(x))
print ' '.join(nl)

其他回答

for Python 2.7

for x in range(0, 3):
    print x,

for python3

for x in range(0, 3):
    print(x, end=" ")

改变

print item

to

print "\033[K", item, "\r",
sys.stdout.flush()

“\033[K”清除到行尾 \r返回行首 flush语句确保它立即显示,以便获得实时输出。

和其他例子一样, 我使用类似的方法,但不是花时间计算最后的输出长度,等等,

我简单地使用ANSI代码转义移回行开始,然后在打印当前状态输出之前清除整行。

import sys

class Printer():
    """Print things to stdout on one line dynamically"""
    def __init__(self,data):
        sys.stdout.write("\r\x1b[K"+data.__str__())
        sys.stdout.flush()

为了在你的迭代循环中使用,你只需要调用如下代码:

x = 1
for f in fileList:
    ProcessFile(f)
    output = "File number %d completed." % x
    Printer(output)
    x += 1   

点击这里查看更多信息

注意:我之所以指出这个解决方案,是因为如果下一次打印的长度小于前一次打印的长度,我所见过的大多数其他解决方案都不起作用。

如果您知道要删除什么,并且可以使用全局变量,那么只需用空格覆盖最后一行。

在打印之前,将字符串的长度存储为' n '。 打印它,但以' \r '结尾(它返回行首)。 下次,在打印信息之前,在该行上打印“n”个空格。

_last_print_len = 0
def reprint(msg, finish=False):
    global _last_print_len
    
    # Ovewrites line with spaces.
    print(' '*_last_print_len, end='\r')
    
    if finish:
        end = '\n'
        # If we're finishing the line, we won't need to overwrite it in the next print.
        _last_print_len = 0
    else:
        end = '\r'
        # Store len for the next print.
        _last_print_len = len(msg)
    
    # Printing message.
    print(msg, end=end)

例子:

for i in range(10):
    reprint('Loading.')
    time.sleep(1)
    reprint('Loading..')
    time.sleep(1)
    reprint('Loading...')
    time.sleep(1)

for i in range(10):
    reprint('Loading.')
    time.sleep(1)
    reprint('Loading..')
    time.sleep(1)
    reprint('Loading...', finish=True)
    time.sleep(1)

顺便说一下......如何每次刷新它,所以它打印mi在一个地方,只是改变数字。

一般来说,这样做的方法是使用终端控制代码。这是一个特别简单的情况,你只需要一个特殊的字符:U+000D CARRIAGE RETURN,它在Python(和许多其他语言)中被写成'\r'。下面是一个基于你的代码的完整示例:

from sys import stdout
from time import sleep
for i in range(1,20):
    stdout.write("\r%d" % i)
    stdout.flush()
    sleep(1)
stdout.write("\n") # move the cursor to the next line

有些事情可能会令人惊讶:

\r位于字符串的开头,以便在程序运行时,光标始终位于数字后面。这不仅仅是表面上的:如果你反过来做,一些终端模拟器会非常混乱。 如果您不包括最后一行,那么在程序终止后,shell将在数字上方打印提示符。 stdout。在某些系统上Flush是必要的,否则将得不到任何输出。其他系统可能不需要它,但它不会造成任何损害。

如果你发现这不起作用,你应该怀疑的第一件事是你的终端模拟器有bug。vttest程序可以帮助你测试它。

可以替换stdout。写与打印语句,但我不喜欢混合打印与直接使用文件对象。