Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.


1 Answers

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 )
like image 78
Bram Avatar answered Dec 08 '25 01:12

Bram



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!