Search code examples
pythonmacosinputkeygetch

How to return a character from standard input on OS X in Python?


For a Python project that I'm working on I need to tell the user to insert a character and return its value in ASCII code without having to press enter to commit the key.

It must also read the input only if my program is the active application, otherwise it must do nothing (like getch() in Windows). The OS is OS X.


Solution

  • Normally, data becomes available at stdin after a newline.

    So you need to put stdin into 'raw mode'. Here is a python program that will read key presses from a raw tty. It stops after 16 presses, because Ctrl-C is not processed either.

    import sys
    import termios
    import tty
    
    attr = termios.tcgetattr( sys.stdin )
    tty.setraw( sys.stdin )
    
    for i in range(16) :
        d = sys.stdin.read(1)
        print ord( d[0] )
        print "\r",
    
    termios.tcsetattr( sys.stdin, termios.TCSADRAIN, attr )