我想做几个语句,给出标准输出,而不看到换行之间的语句。
具体来说,假设我有:
for item in range(1,100):
print item
结果是:
1
2
3
4
.
.
.
如何让它看起来像:
1 2 3 4 5 ...
更好的是,是否可以将单个数字打印在最后一个数字之上,这样一次只有一个数字出现在屏幕上?
我想做几个语句,给出标准输出,而不看到换行之间的语句。
具体来说,假设我有:
for item in range(1,100):
print item
结果是:
1
2
3
4
.
.
.
如何让它看起来像:
1 2 3 4 5 ...
更好的是,是否可以将单个数字打印在最后一个数字之上,这样一次只有一个数字出现在屏幕上?
当前回答
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.
其他回答
这么多复杂的答案。如果你使用的是python3,只需在打印的开头放置\r,并添加end= ", flush=True:
import time
for i in range(10):
print(f'\r{i} foo bar', end='', flush=True)
time.sleep(0.5)
这将在原地写入0 foo bar,然后是1 foo bar等。
或者更简单:
import time
a = 0
while True:
print (a, end="\r")
a += 1
time.sleep(0.1)
End ="\r"将覆盖第一次打印的开头[0:]。
我在2.7中使用的另一个答案是,每当循环运行时,我只是打印出一个“。”(向用户表明事情仍在运行):
print "\b.",
它输出“。”字符,每个字符之间没有空格。它看起来好一点,工作得很好。\b是一个退格字符。
和其他例子一样, 我使用类似的方法,但不是花时间计算最后的输出长度,等等,
我简单地使用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
点击这里查看更多信息
实现这一点的最佳方法是使用\r字符
试试下面的代码:
import time
for n in range(500):
print(n, end='\r')
time.sleep(0.01)
print() # start new line so most recently printed number stays