'How can I use curses to respond to a key press without pausing the program to wait for an input?
An example of what I would like to do is the following:
import curses
while True:
key = stdscr.getch()
if key == 119:
print("key w pressed")
else:
print("w key not pressed")
Where the else statement prints constantly, not only when a key is entered and getch does not return 119. In other words, I don't want the getch function to wait for a key press, I only want it to only return a key if a key is being pressed, otherwise return None or something like that.
Solution 1:[1]
In curses the window has a nodelay flag. If it is set to true, the getch function won't wait for user input, but will return -1 if no input is to be read.
import curses
stdscr.nodelay(True)
while True:
key = stdscr.getch()
if key == -1:
print("no key was pressed")
elif key == 119:
print("key w pressed")
else:
print("different key than w was pressed")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Glitch__ |
