-3

I was wondering how do I get a key pressed in python

I tried doing:

import msvcrt as keys
while True:
    key = keys.getch()
    if key == "a":
        print("You have pressed a") 

Does anyone know how to fix it?

Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
David Callanan
  • 5,601
  • 7
  • 63
  • 105
  • 7
    You didn't really say what your problem is. – Jordan Kaye Sep 27 '12 at 20:07
  • 3
    This code works how I would expect. How do you expect it to work? – Steven Rumbalski Sep 27 '12 at 20:13
  • What is this for? If you plan on more advanced console input/drawing/refreshing take a look at 'curses' library. Depending what you are doing, it might be easier to write in a non-console app, like pygame/pyglet even if you render mostly text. (Like a modern roguelike) – ninMonkey Sep 28 '12 at 00:40
  • Take a look at PyHook.(Also possible duplicate of http://stackoverflow.com/questions/4501700/how-to-get-in-python-the-key-pressed-without-press-enter) – serk Sep 28 '12 at 05:00
  • Check This Out http://www.ehow.com/how_12166842_key-presses-python.html – Afshin Sep 29 '12 at 06:29

1 Answers1

0

This might help you:

import msvcrt
while True:
    if msvcrt.kbhit() and msvcrt.getch() == chr(97): # chr(97) = 'a'
        print("You have pressed a")

Note: your code and my code won't work in many Python IDE's! You need to execute the python file, e.g. in a command window.

mawueth
  • 2,668
  • 1
  • 14
  • 12
  • 1
    This is like the OP's code except it will take 100% CPU. And why write `chr(97)` when it is the same as `'a'`? – interjay Sep 27 '12 at 20:34
  • Looking back at this question years later, it seems to work fine. I mustn't have tried it in the console. Thanks for your help! – David Callanan Aug 04 '17 at 12:10