【问题标题】:How To Clear A Single Line of Text in a Console [duplicate]如何在控制台中清除单行文本 [重复]
【发布时间】:2021-12-26 09:32:35
【问题描述】:

我正在尝试像这样在控制台中清除一行:

Confirm? yes

Placing Order...

然后:

Confirm? yes

Order is at the location that you've provided!

我不想这样:

Confirm? yes

Placing Order...
Order is at the location that you've provided!

这就像你用 pip 安装模块时,进度条只是停留在同一行而不是另一行。

我正在使用 Python 3.10

【问题讨论】:

  • 如果终端支持 ANSI 则使用sys.stdout.write("\033[2K"),否则使用sys.stdout.write('\r' + (' ' * shutil.get_terminal_size()[0]))。现在这里是笔记。 1. sys.stdout.write 类似于 printend 参数不是 '\n'。 2.你需要导入sysimport sys才能使用我的功能,另外你需要在第二选择中导入shutil。 3.你可以在这里看到ANSI序列ANSI SEQUENCES GIST
  • 我刚刚发现只是在 print 的end 参数中放了一个\r
  • 这不会清除行,只是将光标位置放在起始行的开头。使用它可以覆盖写在该行上的文本,但不会清除它。
  • @UltraStudioLTD 是的,我知道,但我会暂时使用它
  • stdout.write 只输出整数

标签: python console


【解决方案1】:

你可以使用python的os模块来使用控制台的clear命令。例如,

confirm = input("confirm? ")
if confirm.lower() in ["yes", "y"]:
    print("Placing Order...")
os.system("clear")
addressConfirm = input("confirm? ")
if addressConfirm.lower() in ["yes", "y"]:
    print("Order is at the location that you've provided!")

【讨论】:

  • OP 要求清除一行而不是整个控制台屏幕。此外,clear 命令仅适用于 Linux类 Unix 终端。
猜你喜欢
  • 1970-01-01
  • 2013-01-27
  • 1970-01-01
  • 1970-01-01
  • 2010-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-28
相关资源
最近更新 更多