我试图从输出控制台窗口中清除最后几行。为了实现这一点,我决定使用创建秒表,并且我已经实现了中断键盘中断和按下回车键时它会创建一圈但我的代码只创建一圈并且我当前的代码正在清除整个输出屏幕。
清除.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 中,我只能创建一圈,但它不会永久保留。
原文由 Gahan 发布,翻译遵循 CC BY-SA 4.0 许可协议
要从输出中仅清除一行:
这将清除前一行并将光标置于该行的开头。如果你去掉尾随的换行符,那么它将移到上一行,因为
\033[A
意味着将光标放在一行上