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)
when I run
%run <path-to-script>/clear.py
in my ipython shell I am able to create only one lap but it is not staying for permanent.
The following works to clear the terminal: ctrl + L. clear command in the terminal.
Method 1: Clear screen in Python using cls You can simply “cls” to clear the screen in windows.
specially res_line = line -> res_line (a variable to store the final result) will capture the value of line only if it is lower than the last captured value (inside the for loop execution).
The clear() method removes all elements in a set.
To clear only a single line from the output :
print ("\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
The codes shared by Ankush Rathi above this comment are probably correct, except for the use of parenthesis in the print command. I personally recommend doing it like this.
print("This message will remain in the console.")
print("This is the message that will be deleted.", end="\r")
One thing to keep in mind though is that if you run it in IDLE by pressing F5, the shell will still display both messages. However, if you run the program by double clicking, the output console will delete it. This might be the misunderstanding that happened with Ankush Rathi's answer (in a previous post).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With