Clayton J Roberts
Clayton J Roberts

Reputation: 366

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.

Upvotes: 1

Views: 1375

Answers (2)

Praveenkumar
Praveenkumar

Reputation: 2182

You can do something like below. For better visibility I have added a sleep time.

import time


def myprint(msg):
    print(msg, end='', flush=True)
    time.sleep(1)
    print('\r', end='', flush=True)
    print(' ' * len(msg), end='', flush=True)
    print('\r', end='', flush=True)


print('These are some other lines 1')
print('These are some other lines 2')

for i in range(10):
    myprint('Hello Jim {}!'.format(i))

Upvotes: 0

Amadan
Amadan

Reputation: 198324

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:

  • 0: clear forward till end of line (default)
  • 1: clear backward till beginning of line
  • 2: clear whole line

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

Upvotes: 6

Related Questions