如何只清除python输出控制台中的最后一行?

Gah*_*han 5 python ipython python-3.x python-3.4

我试图从输出控制台窗口中只清除最后几行。为了实现这一点,我决定使用创建秒表,我已经实现了在键盘中断和回车键按下时中断它创建圈,但我的代码只创建圈一次,我当前的代码正在清除整个输出屏幕。

清除.py

import os
import msvcrt, time
from datetime import datetime
from threading import Thread

def threaded_function(arg):
    while True:
        input()

lap_count = 0
if __name__ == "__main__":
    # thread = Thread(target = threaded_function)
    # thread.start()
    try:
        while True:
            t = "{}:{}:{}:{}".format(datetime.now().hour, datetime.now().minute, datetime.now().second, datetime.now().microsecond)
            print(t)
            time.sleep(0.2)
            os.system('cls||clear') # I want some way to clear only previous line instead of clearing whole console
            if lap_count == 0:
                if msvcrt.kbhit():
                    if msvcrt.getwche() == '\r': # this creates lap only once when I press "Enter" key
                        lap_count += 1
                        print("lap : {}".format(t))
                        time.sleep(1)
                        continue            
    except KeyboardInterrupt:
        print("lap stop at : {}".format(t))
        print(lap_count)
Run Code Online (Sandbox Code Playgroud)

当我跑

%run <path-to-script>/clear.py 
Run Code Online (Sandbox Code Playgroud)

在我的 ipython shell 中,我只能创建一圈,但它不会永久停留。

Jas*_*son 10

我认为最简单的方法是使用两个print()来实现清理最后一行。

print("something will be updated/erased during next loop", end="")
print("\r", end="")
print("the info")
Run Code Online (Sandbox Code Playgroud)

第一个print()只是确保光标在行尾结束而不是开始新行

第二个print()会将光标移动到同一行的开头而不是开始新行

然后第三个就自然而然地print()开始打印光标当前所在位置的内容。

我还制作了一个玩具函数,使用循环打印进度条time.sleep(),然后去查看一下

def progression_bar(total_time=10):
    num_bar = 50
    sleep_intvl = total_time/num_bar
    print("start: ")
    for i in range(1,num_bar):
        print("\r", end="")
        print("{:.1%} ".format(i/num_bar),"-"*i, end="")
        time.sleep(sleep_intvl)
Run Code Online (Sandbox Code Playgroud)

  • 这实际上是关于删除一行的最佳答案! (2认同)

小智 7

从输出中只清除一行:

print ("\033[A                             \033[A")
Run Code Online (Sandbox Code Playgroud)

这将清除前一行并将光标置于该行的开头。如果你去掉尾随的换行符,那么它会移到上一行,因为\033[A意味着把光标放在一行上

  • print ("\033[A\033[A") &lt;- 这似乎工作得很好 (2认同)

小智 7

Ankush Rathi 在此评论上方共享的代码可能是正确的,除了在打印命令中使用括号之外。我个人建议这样做。

print("This message will remain in the console.")

print("This is the message that will be deleted.", end="\r")
Run Code Online (Sandbox Code Playgroud)

但要记住的一件事是,如果您通过按 F5 在空闲状态下运行它,shell 仍会显示这两条消息。但是,如果通过双击运行该程序,输出控制台会将其删除。这可能是 Ankush Rathi 的回答(在上一篇文章中)发生的误解。


Ank*_*thi -2

如果您打算从控制台输出中删除特定行,

print "I want to keep this line"
print "I want to delete this line",
print "\r " # this is going to delete previous line
Run Code Online (Sandbox Code Playgroud)

或者

print "I want to keep this line"
print "I want to delete this line\r "
Run Code Online (Sandbox Code Playgroud)

  • 这不是删除该行。它只是将光标移动到行的开头。除非您写了其他内容,否则内容将保留。 (2认同)