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

具体来说,假设我有:

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

结果是:

1
2
3
4
.
.
.

如何让它看起来像:

1 2 3 4 5 ...

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


当前回答

改变

print item

to

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

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

其他回答

为了让数字相互覆盖,你可以这样做:

for i in range(1,100):
    print "\r",i,

只要把数字打印在第一列,这就可以工作。

编辑: 这里有一个版本,即使没有打印在第一列,也可以工作。

prev_digits = -1
for i in range(0,1000):
    print("%s%d" % ("\b"*(prev_digits + 1), i)),
    prev_digits = len(str(i))

我应该指出,这段代码经过测试,在Windows上的Python 2.5中,在Windows控制台中工作得很好。根据其他一些方法,可能需要刷新stdout才能查看结果。YMMV。

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

我简单地使用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   

点击这里查看更多信息

对于那些像我一样挣扎的人,我提出了以下似乎在python 3.7.4和3.5.2中都可以工作的方法。

I expanded the range from 100 to 1,000,000 because it runs very fast and you may not see the output. This is because one side effect of setting end='\r' is that the final loop iteration clears all of the output. A longer number was needed to demonstrate that it works. This result may not be desirable in all cases, but was fine in mine, and OP didn't specify one way or another. You could potentially circumvent this with an if statement that evaluates the length of the array being iterated over, etc. The key to get it working in my case was to couple the brackets "{}" with .format(). Otherwise, it didn't work.

以下应按原样工作:

#!/usr/bin/env python3

for item in range(1,1000000):
    print("{}".format(item), end='\r', flush=True)

将打印项更改为:

在Python 2.7中,打印项 print(item, end=" "

如果你想动态打印数据,请使用以下语法:

打印(item, sep=' ', end= ", flush=True

In [9]: print?
Type:           builtin_function_or_method
Base Class:     <type 'builtin_function_or_method'>
String Form:    <built-in function print>
Namespace:      Python builtin
Docstring:
    print(value, ..., sep=' ', end='\n', file=sys.stdout)

Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep:  string inserted between values, default a space.
end:  string appended after the last value, default a newline.