As stated on "How about nope"'s answer, that is not straightforward.
One can either go into the low level of the input system and change some settings to allow for non-blocking keyboard reading, or makeuse of a thirdy party library that will do that and provide some friendly interface.
terminedia
is one such 3rdy party project - among other niceties, it implements the inkey()
call which is similar to old-time BASIC function with the same name: it returns the key currently pressed, if there is one, or an empty string.
You just have to call it inside a context block using the terminedia keyboard: with terminedia.keyboard:
So, you have to first install terminedia in your Python environment with pip install terminedia
. Then your code could be like this:
import terminedia as TM
n = 1
with TM.keyboard:
while True:
# do something
n += 1
if (pressed:=TM.inkey()) == "p":
# do task 1
if pressed == "f":
# exit while
break
Another advantage over writing the code to set stdin settings is that
terminedia keyboard input is multiplatform and will work in windows (though much of the other functionalities in the lib will be Unix only)
(disclaimer: I am the project author)