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

34,194

Solution 1

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

Solution 2

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

Solution 3

I think the simplest way is to use two print() to achieve clean the last line.

print("something will be updated/erased during next loop", end="")
print("\r", end="")
print("the info")

The 1st print() simply make sure the cursor ends at the end of the line and not start a new line

The 2nd print() would move the cursor to the beginning of the same line and not start a new line

Then it comes naturally for the 3rd print() which simply start print something where the cursor is currently at.

I also made a toy function to print progress bar using a loop and time.sleep(), go and check it out

def progression_bar(total_time=10):
    num_bar = 50
    sleep_intvl = total_time/num_bar
    print("start: ")
    for i in range(1,num_bar):
        print("\r", end="")
        print("{:.1%} ".format(i/num_bar),"-"*i, end="")
        time.sleep(sleep_intvl)

Solution 4

I know this is a really old question but i couldn't find any good answer at it. You have to use escape characters. Ashish Ghodake suggested to use this

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

But what if the line you want to remove has more characters than the spaces in the string? I think the better thing is to find out how many characters can fit in one of your terminal's lines and then to add the correspondent number of " " in the escape string like this.

import subprocess, time
tput = subprocess.Popen(['tput','cols'], stdout=subprocess.PIPE)
cols = int(tput.communicate()[0].strip()) # the number of columns in a line
i = 0
while True:
    print(i)
    time.sleep(0.1)
    print("\033[A{}\033[A".format(' '*cols))
    i += 1

finally I would say that the "function" to remove last line is

import subprocess
def remove():
    tput = subprocess.Popen(['tput','cols'], stdout=subprocess.PIPE)
    cols = int(tput.communicate()[0].strip())
    print("\033[A{}\033[A".format(' '*cols))
Share:
34,194
Gahan
Author by

Gahan

I am Firmware Engineer with excellent skill and understanding in Python, UEFI Firmware, DevOps along with architectural skills. I also like to contribute in open source too and spreading the knowledge (#philanthropist for knowledge!). Interested to work in Quantum Computing, Data Analysis, Artificial Intelligence, Soft Computing, Complex Algorithms, Augmented Reality.

Updated on July 14, 2022

Comments

  • Gahan
    Gahan almost 2 years

    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.