Python method for reading keypress?

156,128

Solution 1

Figured it out by testing all the stuff by myself. Couldn't find any topics about it tho, so I'll just leave the solution here. This might not be the only or even the best solution, but it works for my purposes (within getch's limits) and is better than nothing.

Note: proper keyDown() which would recognize all the keys and actual key presses, is still valued.

Solution: using ord()-function to first turn the getch() into an integer (I guess they're virtual key codes, but not too sure) works fine, and then comparing the result to the actual number representing the wanted key. Also, if I needed to, I could add an extra chr() around the number returned so that it would convert it to a character. However, I'm using mostly down arrow, esc, etc. so converting those to a character would be stupid. Here's the final code:

from msvcrt import getch
while True:
    key = ord(getch())
    if key == 27: #ESC
        break
    elif key == 13: #Enter
        select()
    elif key == 224: #Special keys (arrows, f keys, ins, del, etc.)
        key = ord(getch())
        if key == 80: #Down arrow
            moveDown()
        elif key == 72: #Up arrow
            moveUp()

Also if someone else needs to, you can easily find out the keycodes from google, or by using python and just pressing the key:

from msvcrt import getch
while True:
    print(ord(getch()))

Solution 2

See the MSDN getch docs. Specifically:

The _getch and_getwch functions read a single character from the console without echoing the character. None of these functions can be used to read CTRL+C. When reading a function key or an arrow key, each function must be called twice; the first call returns 0 or 0xE0, and the second call returns the actual key code.

The Python function returns a character. you can use ord() to get an integer value you can test, for example keycode = ord(msvcrt.getch()).

So if you read an 0x00 or 0xE0, read it a second time to get the key code for an arrow or function key. From experimentation, 0x00 precedes F1-F10 (0x3B-0x44) and 0xE0 precedes arrow keys and Ins/Del/Home/End/PageUp/PageDown.

Solution 3

I really did not want to post this as a comment because I would need to comment all answers and the original question.

All of the answers seem to rely on MSVCRT Microsoft Visual C Runtime. If you would like to avoid that dependency :

In case you want cross platform support, using the library here:

https://pypi.org/project/getkey/#files

https://github.com/kcsaff/getkey

Can allow for a more elegant solution.

Code example:

from getkey import getkey, keys
key = getkey()
if key == keys.UP:
  ...  # Handle the UP key
elif key == keys.DOWN:
  ...  # Handle the DOWN key
elif key == 'a':
  ...  # Handle the `a` key
elif key == 'Y':
  ...  # Handle `shift-y`
else:
  # Handle other text characters
  buffer += key
  print(buffer)

Solution 4

from msvcrt import getch

pos = [0, 0]

def fright():
    global pos
    pos[0] += 1

def fleft():
    global pos 
    pos[0] -= 1

def fup():
    global pos
    pos[1] += 1

def fdown():
    global pos
    pos[1] -= 1

while True:
    print'Distance from zero: ', pos
    key = ord(getch())
    if key == 27: #ESC
        break
    elif key == 13: #Enter
        print('selected')
    elif key == 32: #Space
        print('jump')
    elif key == 224: #Special keys (arrows, f keys, ins, del, etc.)
        key = ord(getch())
        if key == 80: #Down arrow
            print('down')
            fdown
        elif key == 72: #Up arrow
            print('up')
            fup()
        elif key == 75: #Left arrow
            print('left')
            fleft()
        elif key == 77: #Right arrow
            print('right')
            fright()

Solution 5

I was also trying to achieve this. From above codes, what I understood was that you can call getch() function multiple times in order to get both bytes getting from the function. So the ord() function is not necessary if you are just looking to use with byte objects.

while True :
    if m.kbhit() :
        k = m.getch()
        if b'\r' == k :
            break
        elif k == b'\x08'or k == b'\x1b':
            # b'\x08' => BACKSPACE
            # b'\x1b' => ESC
            pass
        elif k == b'\xe0' or k == b'\x00':
            k = m.getch()
            if k in [b'H',b'M',b'K',b'P',b'S',b'\x08']:
                # b'H' => UP ARROW
                # b'M' => RIGHT ARROW
                # b'K' => LEFT ARROW
                # b'P' => DOWN ARROW
                # b'S' => DELETE
                pass
            else:
                print(k.decode(),end='')
        else:
            print(k.decode(),end='')

This code will work print any key until enter key is pressed in CMD or IDE (I was using VS CODE) You can customize inside the if for specific keys if needed

Share:
156,128

Related videos on Youtube

kres0345
Author by

kres0345

I am a programmer and I am 16 years old, have no programming related education, yet.

Updated on July 09, 2022

Comments

  • kres0345
    kres0345 almost 2 years

    I'm new to Python, and I just made a game and a menu in Python. Question is, that using (raw_)input() requires me to press enter after every keypress, I'd like to make it so that pressing down-arrow will instantly select the next menu item, or move down in the game. At the moment, it requires me to like type "down" and then hit enter. I also did quite a lot of research, but I would prefer not to download huge modules (e.g. pygame) just to achieve a single keyDown() method. So are there any easier ways, which I just couldn't find?

    Edit: Just found out that msvcrt.getch() would do the trick. It's not keyDown(), but it works. However, I'm not sure how to use it either, it seems quite weird, any help here? This is what I got at the moment:

    from msvcrt import getch
    while True:
        key = getch()
        print(key)
    

    However, it keeps giving me all these nonsense bytes, for example, down-arrow is this:

    b'\xe0'
    b'P'
    

    And I have no idea how to use them, I've tried to compare with chr() and even use ord() but can't really do any comparisons. What I'm trying to do is basically this:

    from msvcrt import getch
    while True:
        key = getch()
        if key == escape:
            break
        elif key == downarrow:
            movedown()
        elif key == 'a':
            ...
    

    And so on... Any help?

    • futurecat
      futurecat over 11 years
      Not a duplicate of that. This is about keydown events, not single character input.
    • cat
      cat over 8 years
      I can haz cross-platform solution?? msvcrt is not available on mac/linux distributions of Python
  • Admin
    Admin over 11 years
    Well I figured it by now, but can't post the final solution. But this + ord() + char()
  • Anum Sheraz
    Anum Sheraz about 8 years
    I am using the above code, but my code simply blocks at getch(), and nothing happens then. any help ?
  • Moondra
    Moondra almost 7 years
    @AnumSheraz The above method only works when you run the code from command prompt.
  • AJ123
    AJ123 over 6 years
    Please add some explanation to your answer to explain your code.
  • Xitcod13
    Xitcod13 almost 6 years
    if you cast a char to bytes first you can compare directly with keypressed 'keypressed == bytes('q', 'utf-8')' checks if q was pressed. It will work for special keys like enter or esc but you need to know the codes for those (esc is '\x1b' for example)
  • luturol
    luturol over 4 years
    Why you have to do another key = ord(getch()) when you press arrows keys? In the first time, you get a 224, but it gets right away the correct code for that key. How?
  • Apostolos
    Apostolos over 3 years
    Installing a special library ('getkey') is a very ineffective solution when already an built-in module (msvcrt) works just fine!
  • InxaneNinja
    InxaneNinja over 3 years
    @Apostolos as he said in his solution, msvcrt is only available on Windows, getkey is cross platform.
  • Apostolos
    Apostolos over 3 years
    I see what you mean. But think: Since every platform has its own built-in "getkey" module (as 'msvcrt' in Windows), installing an extra "getkey" module will always be useless! :) (Simple logic)
  • Joel G Mathew
    Joel G Mathew almost 3 years
    This is a terrible solution. This is not even using inbuilt functions. You are opening a shell subprocess and running linux commands just for detecting a keypress
  • Ken
    Ken over 2 years
    @Apostolos Try Ctrl + Keys with mscvrt, also look at how much more readable the code is and now think past a one box wonder. The code I posted can be installed and utilized on all platforms and not rely on anything else - completely portable, and one stop maintainability - It just works, try that with code built on Windows msvcrt. If you rely on the platform, you are bound to the platform and your code is platform specific and maintaining unique versions for each platform is not very wise or efficient - though it does make for busy work.
  • Apostolos
    Apostolos over 2 years
    That's fine. The essence is to do well the job you have to do. I personally, have built hundreads of PY files, and I 'mscvrt' always covers my totally. Otherwise, I wouldn't have any problem using some external module, as I often do with other subjects.
  • Robatron
    Robatron over 2 years
    @luturol- because some keys return 2 bytes (arrow keys, function keys, etc). A second getch is required to see WHICH arrow key or function key was pressed.....