我想做几个语句,给出标准输出,而不看到换行之间的语句。
具体来说,假设我有:
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 ...
更好的是,是否可以将单个数字打印在最后一个数字之上,这样一次只有一个数字出现在屏幕上?
当前回答
和其他例子一样, 我使用类似的方法,但不是花时间计算最后的输出长度,等等,
我简单地使用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
点击这里查看更多信息
其他回答
你可以在你的print语句中添加一个尾随逗号,在每次迭代中打印一个空格而不是换行符:
print item,
或者,如果你使用的是Python 2.6或更高版本,你可以使用新的print函数,它允许你指定甚至不应该在打印的每一项的结尾出现空格(或者允许你指定任何你想要的结尾):
from __future__ import print_function
...
print(item, end="")
最后,你可以通过从sys模块导入标准输出直接写入标准输出,它会返回一个类文件对象:
from sys import stdout
...
stdout.write( str(item) )
将打印项更改为:
在Python 2.7中,打印项 print(item, end=" "
如果你想动态打印数据,请使用以下语法:
打印(item, sep=' ', end= ", flush=True
“顺便说一下......如何刷新它,所以它打印mi在一个地方,只要改变数字。”
这真的是个棘手的话题。zack所建议的(输出控制台控制代码)是实现这一目标的一种方法。
你可以使用(n)诅咒,但这主要适用于*nix。
在Windows上(这里有有趣的部分),这很少被提及(我不明白为什么),你可以使用Python绑定到WinAPI (http://sourceforge.net/projects/pywin32/默认也带有ActivePython) -这并不难,而且工作得很好。这里有一个小例子:
import win32console, time
output_handle = win32console.GetStdHandle( win32console.STD_OUTPUT_HANDLE )
info = output_handle.GetConsoleScreenBufferInfo()
pos = info["CursorPosition"]
for i in "\\|/-\\|/-":
output_handle.WriteConsoleOutputCharacter( i, pos )
time.sleep( 1 )
或者,如果你想使用print(语句或函数,没有区别):
import win32console, time
output_handle = win32console.GetStdHandle( win32console.STD_OUTPUT_HANDLE )
info = output_handle.GetConsoleScreenBufferInfo()
pos = info["CursorPosition"]
for i in "\\|/-\\|/-":
print i
output_handle.SetConsoleCursorPosition( pos )
time.sleep( 1 )
Win32console模块可以让你用Windows控制台做更多有趣的事情…我不是WinAPI的忠实粉丝,但最近我意识到我对它的反感至少有一半是由用C语言编写WinAPI代码引起的——python绑定更容易使用。
当然,所有其他的答案都很棒,而且很深奥,但是……如果我想打印上一行呢?或者写多行文本,而不是清除它,再写相同的行?我的解决方案使之成为可能。
对于那些像我一样挣扎的人,我提出了以下似乎在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)
打印语句末尾的逗号省略了新行。
for i in xrange(1,100):
print i,
但这不会覆盖。