【问题标题】:python overwrite output on same line [duplicate]python覆盖同一行上的输出[重复]
【发布时间】:2013-12-28 14:30:25
【问题描述】:

我有以下

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

输出是:

a
c
a
e
...

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

谢谢

【问题讨论】:

  • 我建议不要写退格字符,而是使用 curses 模块。

标签: python list while-loop


【解决方案1】:

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

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

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

(可能需要一个time.sleep,这样你就可以真正看到发生了什么)

【讨论】:

    【解决方案2】:

    你可以删除旧的输出

    import sys
    sys.stdout.write( '\b' ) # removes the last outputed character
    

    您可能需要在每个print 之后使用flush

    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' )
    

    【讨论】:

      猜你喜欢
      • 2023-03-17
      • 2014-12-22
      • 2012-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-19
      • 1970-01-01
      相关资源
      最近更新 更多