如何在python输出控制台中仅清除最后一行? [英] How to clear only last one line in python output console?
问题描述
我正在尝试仅清除输出控制台窗口中的最后几行.为此,我决定使用create秒表,并实现了在键盘中断和Enter键上进行中断,从而创建了圈速,但是我的代码仅创建了一次圈速,并且我的当前代码正在清除整个输出屏幕.
I am trying to clear only last few line from output console window. To achieve this I have decided to use create stopwatch and I have achieved to interrupt on keyboard interrupt and on enter key press it creates lap but my code only create lap once and my current code is clearing whole output screen.
clear.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
在我的ipython shell中,我只能创建一个圈,但不能永久保留.
in my ipython shell I am able to create only one lap but it is not staying for permanent.
推荐答案
仅清除输出中的一行:
print ("\033[A \033[A")
这将清除前一行,并将光标放置在该行的开头.
如果您删除尾随的换行符,则它将移至上一行,因为\033[A
意味着将光标向上一行
This will clear the preceding line and will place the cursor onto the beginning of the line.
If you strip the trailing newline then it will shift to the previous line as \033[A
means put the cursor one line up
这篇关于如何在python输出控制台中仅清除最后一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!