You can suppress keyboard input using built-in (standard) Python modules.
It is common to also want to suppress signals while keyboard input is blocked. Therefore, this utility class facilitates that too (by default).
from termios import tcgetattr, tcsetattr, TCSAFLUSH
from sys import stdin
from tty import setraw
import signal
class Blocker:
def __init__(self, ignore_signals=True):
self._ignore_signals = ignore_signals
@staticmethod
def siglist():
signames = [
"SIGABRT",
"SIGINT",
"SIGTERM",
"SIGBREAK",
"SIGALRM",
"SIGCONT",
"SIGHUP",
"SIGUSR1",
"SIGUSR2",
"SIGWINCH",
]
_siglist = []
for signame in signames:
if (sig := getattr(signal, signame, None)) is not None:
_siglist.append(sig)
return _siglist
def __enter__(self):
self._fd = stdin.fileno()
self._attr = tcgetattr(self._fd)
setraw(self._fd)
if self._ignore_signals:
self._sigfuncs = {
s: signal.signal(s, signal.SIG_IGN) for s in Blocker.siglist()
}
else:
self._sigfuncs = None
return self
def __exit__(self, *_):
if self._sigfuncs is not None:
for kv in self._sigfuncs.items():
signal.signal(*kv)
if self._attr is not None:
tcsetattr(self._fd, TCSAFLUSH, self._attr)
import time
# during sleep, keyboard input and observable signals will be ignored
with Blocker():
time.sleep(5)