简体   繁体   中英

Python read modifier keys (CTRL, ALT, SHIFT)

this seems to be a hard one in Python..

I'm trying to read keystrokes and combinations with the modifier keys CTRL, ALT and SHIFT.

I'm on Python 2.7. It only has to work on Linux , but without X .

Currently, I can only read keystrokes using sys.stdin.read(), but the stdin.read() works like a file and doesn't give back the modifiers..

def getch():
    """getch() -> key character

    Read a single keypress from stdin and return the resulting character. 
    Nothing is echoed to the console. This call will block if a keypress 
    is not already available, but will not wait for Enter to be pressed. 

    If the pressed key was a modifier key, nothing will be detected; if
    it were a special function key, it may return the first character of
    of an escape sequence, leaving additional characters in the buffer.
    """
    fd = sys.stdin.fileno()
    old_settings = termios.tcgetattr(fd)
    try:
        tty.setraw(fd)
        ch = sys.stdin.read(1)
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
    return ch

I'm flexible in the way the function returns the keystroke combination. First thing that comes to mind is to return maybe a list or a dict with the combination in it.. But main question is, how to detect it?!

Stdin, by definition is a stream of bytes representing control codes and characters. It is not a stream of key events. To get keys, you need to use an OS specific function. On Linux, the curses window objects have a getch methods. (There is something for Windows in another module.)

Tk, and Python's tkinter wrapper thereof, uses OS-specific methods to let one bind to both key press and release events, which include the modifiers you mention, in code that is mostly not OS specific.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM