문제

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.

도움이 되었습니까?

해결책

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 )
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top