0

This is probably pretty simple, but I can't find the answer anywhere. I basically want some code that detects different key presses (enter, left etc) and then saves the type of key in a variable.

4
  • What OS are you using? Does it need to detect all key presses everywhere, or just ones that occur when your application has keyboard focus? Commented Mar 2, 2015 at 18:24
  • possible duplicate of Detect key input in Python Commented Mar 2, 2015 at 18:24
  • I am using Windows 8, and just ones that occur when my program asks for a key press (result must differ depending on key). I don't want a new pop-up window, just keep it in the command prompt. Commented Mar 2, 2015 at 18:25
  • 1
    There are a few libraries that support keyboard input like Tkinter and PyGame. Have you checked them out? Might add a little too much functionality than you probably want though. Commented Mar 2, 2015 at 18:33

1 Answer 1

1

If you're on Windows and only want to get input when your window has keyboard focus, you can use msvcrt.getch:

Read a keypress and return the resulting character. Nothing is echoed to the console.

Sign up to request clarification or add additional context in comments.

5 Comments

How would I make the console wait for a key press (input doesn't work)?
getch waits for a keypress.
When I run the code it just prints b'\xff' without waiting for me to press something.
Strange, works on my machine... Maybe that's behavior specific to Windows 8. I'm still on 7.
Found the reason, I was using IDLE instead of the command prompt. Thanks anyway

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.