我有一个程序,可以将其进度打印到控制台。每20步,它就会打印出步数,如10、20、30等。但在此范围内,它会打印一个点。这是使用末尾带有逗号的print语句打印的(python 2.x)
if epoch % 10 == 0:
print epoch,
else:
print ".",
不幸的是,我注意到这些点是分开打印的,就像这样:
0 . . . . . . . . . 10 . . . . . . . . . 20 . . . . . . . . . 30
我希望这个更紧,如下所示:
0.........10.........20.........30
在visual basic语言中,如果在print语句的末尾添加分号而不是逗号,则可以得到此表单。在Python中是否有类似的方法,或者通过演练获得更紧凑的输出?
注:
非常感谢和尊重所有回复者,我注意到他们中的一些人认为“纪元”的变化是及时发生的。实际上,事实并非如此,因为它发生在完成一些迭代之后,可能需要几分之一秒到几分钟的时间。
如果要对格式进行更多控制,则需要使用以下任一选项:
import sys
sys.stdout.write('.')
sys.stdout.flush() # otherwise won't show until some newline printed
.. 不要打印,也可以使用Python 3打印函数。这将在Python 2的后续版本中作为将来的导入提供。x组件:
from __future__ import print_function
print('.', end='')
在Python 3中,可以传递关键字参数flush:
print('.', end='', flush=True)
这与上面的sys.stdout
两行具有相同的效果。
import itertools
import sys
import time
counter = itertools.count()
def special_print(value):
sys.stdout.write(value)
sys.stdout.flush()
while True:
time.sleep(0.1)
i = next(counter)
if i % 10 == 0:
special_print(str(i))
else:
special_print('.')
以下是一个可能的解决方案:
import time
import sys
width = 101
for i in xrange(width):
time.sleep(0.001)
if i % 10 == 0:
sys.stdout.write(str(i))
sys.stdout.flush()
else:
sys.stdout.write(".")
sys.stdout.flush()
sys.stdout.write("\n")