Jesvi Jonathan
Jesvi Jonathan

Reputation: 19

how to get user input without pressing enter in python?

I am a c++ User and im am newly learning python, i used to use getch() statements in c++ to get user input without having to press enter although it had some limitation ... I am looking for a similar function in python (anything other than raw_input() & input() which require enter key stroke). would prefer the code to have cross platform support

for eg in c++ :

void getkey()
{
_getch();
cout<<"You Hit A Key";
}

Upvotes: 1

Views: 8085

Answers (3)

Clarius
Clarius

Reputation: 1419

Was writing a simple drum machine on a Raspberry Pi using Python and Sonic Pi: press a key, play a sound. Here's the core of the input routine.

pip install getch

import getch

while True:
     key = getch.getch()
     if key == 'x':
          break

Upvotes: 0

maciek97x
maciek97x

Reputation: 7390

Here is a simple example using keyboard:

import keyboard

while True:
    event = keyboard.read_event()
    if event.event_type == keyboard.KEY_DOWN:
        key = event.name
        print(f'Pressed: {key}')
        if key == 'q':
            break

Upvotes: 2

Data_Is_Everything
Data_Is_Everything

Reputation: 2019

You could do this if you are on a windows OS.

import msvcrt
print("Press y or n to continue: \n")
getLetter = msvcrt.getch()
if getLetter.upper() == 'S': 
   print("cool it works...")
else:
   print("no it doesn't work...")

Upvotes: 0

Related Questions