pythonconsoleurwid

How to clear console line using `print` function


Premise

I'm trying to basically clear the console line, but not the entire console window without using whitespace, so that I don't have extra characters from what was last printed. For example:

# This causes characters from the last thing printed:
print("I don't know you.", end="\r")
print("Hello Jim!", end="\r")

# Yields the following (without the quotations) -->
# "Hello Jim!ow you."

Now to solve this one can do this:

import os

def new_print(message, end):
    """
    Clears console, no matter the size of the previous line 
    without wrapping to a new line
    """
    width_of_console = int(os.popen("stty size", "r").read().split()[1])
    # = 17

    print(f"{message :<{width_of_console}}", end=end)

new_print("I don't know you.", end="\r")
new_print("Hello Jim!", end="\r")
# Yields the following (without the quotations) -->
# "Hello Jim!       "

Question

How do I

  1. Just print out "Hello Jim!" and not "Hello Jim! " (both obviously without quotations)
  2. Clear that line
  3. While not clearing the entire console (so that I have the output of other things besides the last line)

Specifically things like this occur in the console when shifting sizes (from say a console width of 17 to 30), which in my case, happens quite often:

Hello Jim!       Hello Jim!   
    Hello Jim!       Hello Jim
!       Hello Jim!       Hello
 Jim!       Hello Jim!       H
ello Jim!       Hello Jim!    

I'm open to an entire new way of doing things, like using urwid or something of that nature.


Solution

  • You can use the EL (Erase Line) control sequence. In Python, the easiest way to construct it is:

    "\033[2K"
    

    The number controls the behaviour of the EL sequence:

    EL sequence does not move the cursor.

    This behaviour is rather standard, but if you want to be sure, you can query the terminfo database using tput.

    tl;dr:

    print("I don't know you.", end="\r")
    print("\033[2KHello Jim!", end="\r")