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! "
How do I
"Hello Jim!"
and not "Hello Jim! "
(both obviously without quotations)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.
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")