【问题标题】:How to clean a specific thing on command line如何在命令行上清理特定的东西
【发布时间】:2016-04-23 10:07:12
【问题描述】:

我想知道是否可以在 Python 脚本运行的命令 shell 上清除特定的东西?

例如一个脚本包含:

print ("Hello world")

当我双击这个脚本时,会弹出 cmd,我会在命令行上看到Hello world。现在我想知道,是否可以从 shell 中清除 Hello World 并在 在 cmd 运行时在那里写其他东西?喜欢:

print ("Hello world")
time.sleep(1)

# a module replace New Text with Hello world
print("New Text")

【问题讨论】:

  • 我觉得cmd中有特殊字符可以移动光标并删除特定部分
  • 一个模块用 Hello world 替换新文本
  • 查看 curses 模块。

标签: python python-3.x command-line cmd


【解决方案1】:

您可以为此使用 ANSI 转义字符:

sys.stdout.write("\033[F")  # Cursor up to line
sys.stdout.write("\033[K")  # Clear line

或者虽然这有时在 Windows cmd 中不起作用,但试试这个:

sys.stdout.write("\r")  # Move to line beginning

或者如你所愿:

import time

print("Hello world", end="\r")
time.sleep(1)
print("New text   ")  # Trailing slashes to completely override "Hello world"

【讨论】:

    【解决方案2】:

    刷新打印的文本,不要在末尾写一个换行符,而是一个\r 为了在下一行的开头开始打印:

    from __future__ import print_function  # to make it work with Python 2, just in case
    import time
    
    print ("Hello world", end='\r', flush=True)
    time.sleep(1)
    print ("New Text     ", end='\r', flush=True)
    time.sleep(1)
    print ("Last Text    ")
    

    【讨论】:

    • 这就是我想要的。
    猜你喜欢
    • 1970-01-01
    • 2017-04-16
    • 2017-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-31
    • 1970-01-01
    • 2017-11-28
    相关资源
    最近更新 更多