python在同一行上覆盖输出

时间:2013-12-10 21:07:34

标签: python list while-loop

我有以下

foo = ['a', 'b', 'c', 'd', 'e']
from random import choice
while True:
    print choice(foo)

输出结果为:

a
c
a
e
...

我希望终端输出覆盖同一行的旧输出

感谢

2 个答案:

答案 0 :(得分:2)

您可以通过

删除旧输出
import sys
sys.stdout.write( '\b' ) # removes the last outputed character

您可能需要在每个flush

之后使用print
sys.stdout.flush()

类似的东西:

from __future__ import print_function
import time

for j in range( 10 ):
   print( j, end='' )
   sys.stdout.flush()
   time.sleep( 2 )
   sys.stdout.write( '\b' )

答案 1 :(得分:2)

你要覆盖两件事:一,python会在print时自动添加换行符。通过在最后添加一个逗号来覆盖它,就像@SteveP所说(或至少说: - ))。

接下来,您需要在字符串的前面显式添加回车控制字符,以便终端输出覆盖您之前的输出,而不是将其附加到最后。

foo = ['a', 'b', 'c', 'd', 'e']
from random import choice
while True:
    print '\r' + choice(foo),

(可能需要time.sleep,以便您可以真正了解发生了什么)

相关问题