Preventing keystrokes from appearing on the screen

I am working on some basic animations for the python cli interfaces that appear when the script runs. This is a problem that I encounter in almost every script I wrote. If I perform the following animation,

def animatedSpinner(*arg):
    animation = ["|","/","-","\\"]
    a = 0
    while True:
        print(animation[a % len(animation)], end="\r")
        a += 1
        time.sleep(0.1)

It works fine, but it presses the key that the user presses while he is working on the screen. How can I prevent keystrokes from appearing on the screen during animation or at any time?

+4
source share
1 answer

POSIX Windows , , - ( , , , , , ), . , POSIX - , , .


- termios. , .

, stty:

import subprocess

def echooff():
    subprocess.run(['stty', '-echo'], check=True)
def echoon():
    subprocess.run(['stty', 'echo'], check=True)

, , echoon , . , ( ) reset stty echo.

, :

try:
    echooff()
    # do stuff
finally:
    echoon()

, , contextlib:

@contextlib.contextmanager
def echo_disabled():
    try:
        echooff()
        yield
    finally:
        echoon()

:

with echo_disabled():
    # do stuff    

tty , , , termios:

@contextlib.contextmanager
def echo_disabled():
    fd = sys.stdin.fileno()
    old = termios.tcgetattr(fd)
    new = termios.tcgetattr(fd)
    new[3] = new[3] & ~termios.ECHO          # lflags
    try:
        yield
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old)
+3

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


All Articles