Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear only last one line in python output console?

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.

like image 590
Gahan Avatar asked Jun 15 '17 10:06

Gahan


People also ask

How do you clear the last line in Python terminal?

The following works to clear the terminal: ctrl + L. clear command in the terminal.

How do you clear a line of output in Python?

Method 1: Clear screen in Python using cls You can simply “cls” to clear the screen in windows.

How do you print the last line of output in Python?

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).

How do you clear inputs in Python?

The clear() method removes all elements in a set.


2 Answers

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

like image 194
mr_pool_404 Avatar answered Dec 15 '22 05:12

mr_pool_404


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).

like image 38
Gonzalo Alcala Avatar answered Dec 15 '22 06:12

Gonzalo Alcala