【问题标题】:how to replace output on first line with different output如何用不同的输出替换第一行的输出
【发布时间】:2021-04-03 19:00:24
【问题描述】:

我正在尝试创建一行代码,像通常那样打印第一行,然后在打印之后,它会擦除​​该输出并写其他内容

print("This text is about to vanish - from first line",end='')
import time
time.sleep(3)
print("\rSame line output by Thirumalai")

我有这个来自另一个用户的代码,我将如何让它显示第一行,因为当我在终端中运行 py 时它不会这样做,我使用的是 ubuntu

【问题讨论】:

    标签: python-3.x linux ubuntu terminal


    【解决方案1】:

    要使第一行出现,您需要关闭缓冲。你可以指定

    print("This text is about to vanish - from first line",end='', flush=True)
    #                                                              ~~~~~~~~~~
    

    对于print(需要 Python 3.3+,请参阅here 了解详细信息以及如何在旧版本中执行此操作的方法)。

    您还需要在第二个print 的末尾打印一些空格以覆盖剩余的文本。

    print("\rSame line output by Thirumalai", ' ' * 15)
    

    【讨论】:

    • StackOverflow 上的“谢谢” = 赞成/接受
    • 是否始终启用flush=True,以便 if 影响代码的所有行,直到它明确告知停止,而不是一直输入它
    • 查看链接的问题和答案了解更多详情。
    猜你喜欢
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    • 2018-06-24
    • 1970-01-01
    • 2020-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多