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

2024-05-14 21:11:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我只想清除输出控制台窗口的最后几行。为了实现这一点,我决定使用create stopwatch,我已经实现了在键盘中断时中断,按enter键时创建lap,但我的代码只创建lap一次,而我的当前代码正在清除整个输出屏幕。

清除.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 <path-to-script>/clear.py 

在我的iPythonShell中,我只能创造一圈,但它并不是永久的。


Tags: 代码frompyimportformatdatetimeiftime
3条回答

要从输出中仅清除一行:

print ("\033[A                             \033[A")

这将清除前一行,并将光标放在行的开头。 如果去掉尾随的换行符,则它将移到前一行,因为\033[A意味着将光标向上放一行

除了在print命令中使用括号外,Ankush Rathi在该注释上面共享的代码可能是正确的。我个人建议这样做。

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

print("This is the message that will be deleted.", end="\r")

不过,要记住的一点是,如果通过按F5在空闲状态下运行它,shell仍然会显示这两条消息。但是,如果通过双击运行程序,则输出控制台将删除该程序。这可能是安库什·拉蒂的回答所造成的误解。(在上一篇文章中)

我希望这能有帮助。

如果要从控制台输出中删除某些行

print "I want to keep this line"
print "I want to delete this line",
print "\r " # this is going to delete previous line

或者

print "I want to keep this line"
print "I want to delete this line\r "

相关问题 更多 >

    热门问题