Python 3, how to clear a print string to override?

I am trying to override my last fingerprint with a new line, but I cannot clear the last line.

I thought a flash would clear the line, but I don’t see this have any effect.

import time

s = "qwertyuiopåasdfghjklæøzxccvbnm"

for num in range(len(s)):
    print("\r{}".format(str[:len(s)-num]), end="", flush=True)
    time.sleep(.1)

Here, in my example, I get the output:

qwertyuiopåasdfghjklæøzxccvbnm

But I wanted the output to be only "q". If the next print is smaller than the first line, I still see the end of the last line.

I could just override the first line with spaces, but I don’t like it, because if I change the size of the console, it will change everything.

Do I need to clear the last line and only the last line?

a solution that works on both Linux and Windows would be great.

Thank.

+4
source share
2 answers

format , .

import time
s = "qwertyuiopåasdfghjklæøzxccvbnm"

spacer = '\r{{:{}}}'.format(len(s)) # '\r{:30}' for this s

for num in range(len(s), 0, -1):
    print(spacer.format(s[:num]), end='')
    time.sleep(.1)

print()

-

+2

:

from os import get_terminal_size

def rprint(*args, **kwargs):
    try:
        cols, rows = get_terminal_size()
    except OSError:
        # If get_terminal_size is not supported, override with whitespaces is not needed.
        cols, rows = (1, 1)

    # Override the line with whitespace and return cursor(-1 because of cursor size)
    print("\r{:>{}}".format("", cols-1), end="\r")
    print(*args, **{**kwargs, **{"end": "", "flush": True}})


if __name__ == '__main__':
    import time

    s = "qwertyuiopåasdfghjklæøzxccvbnmq"

    # I want to end the loop with "q", not an empty string.
    for num in range(len(s)):
        rprint(s[:len(s) - num])
        time.sleep(.1)

    rprint("Override last line again")

python 3.5 +

, .

, stdout? , get_terminal_size.

0

Source: https://habr.com/ru/post/1691482/


All Articles