Sometimes, we want to use raw_input without pressing enter in Python.
In this article, we’ll look at how to use raw_input without pressing enter in Python.
How to use raw_input without pressing enter in Python?
To use raw_input without pressing enter in Python, we can use the pynput library.
To install it, we run
pip install pynput
Then we use it by writing
from pynput import keyboard
print('Press s or n to continue:')
with keyboard.Events() as events:
event = events.get(1e6)
if event.key == keyboard.KeyCode.from_char('s'):
print("hello")
We use keyboard.Events
to create an event object.
Then we get the keyboard event with
event = events.get(1e6)
We then check if the s key pressed with
event.key == keyboard.KeyCode.from_char('s')
If it is, then we print 'hello'
.
Otherwise, pynput will block the program until s is pressed.
Conclusion
To use raw_input without pressing enter in Python, we can use the pynput library.