I am currently working on a project that involves reading a single character from the command-line without waiting for newlines. I found a helpful answer here, and followed it to its source here. I modified the code slightly, and now I have the following:
import sys,tty,termios
class _Getch:
def __call__(self):
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
def main():
inkey = _Getch()
while(1):
k=inkey()
if k!='':break
print 'you pressed', k
The part that is interesting to me here is the inkey()
. I have tried modifying it to k=inkey
or k=_Getch
, etc. but then it doesn't work as it is meant to. As far as I can tell, no inkey()
method had been defined previously, so it seems like the variable inkey=_Getch()
is somehow being used as a function.
I don't understand what's going on here. How is this possible? What is the underlying mechanic that is being used? I'd be glad if someone could shed some light on this.