[Addition] tty version
If you use input () or sys.stdin.read () normally,
Enter characters
Press enter
Two steps are required.
I want you to do something the moment you press the key, without having to press enter. I tried to find it, but I couldn't find it, so I made a note.
You can check the operation on mac and ubuntu. It doesn't work on windows, but it seems easy to do the same with the msvcrt module.
import sys
import termios
#Get standard input file descriptor
fd = sys.stdin.fileno()
#Get the terminal attributes of fd
#The same thing is entered in old and new.
#Make changes to new and adapt
#old is to be restored later
old = termios.tcgetattr(fd)
new = termios.tcgetattr(fd)
#new[3]Is lflags
#ICANON(Canonical mode flag)Remove
new[3] &= ~termios.ICANON
#ECHO(Flag to display the entered characters)Remove
new[3] &= ~termios.ECHO
try:
#Adapt the rewritten new to fd
termios.tcsetattr(fd, termios.TCSANOW, new)
#Receive input from the keyboard.
#Since lfalgs has been rewritten, you can proceed to the next without pressing enter. Do not echo
ch = sys.stdin.read(1)
finally:
#Restore the attributes of fd
#Specifically, ICANON and ECHO are restored
termios.tcsetattr(fd, termios.TCSANOW, old)
print(ch)
In the first place, input / output is managed using an identifier called a file descriptor. http://qiita.com/toshihirock/items/78286fccf07dbe6df38f
By exchanging file descriptors between the OS and each program, it is possible to determine whether it is standard input / output, error output, or input / output from a file.
termios Termios is the point of contact for actually exchanging data with the OS using file descriptors. termios has information on how to exchange data between the program and the OS. https://linuxjm.osdn.jp/html/LDP_man-pages/man3/termios.3.html
Among the information, there is also a flag (canonical mode, ICANON) that decides whether to wait for input until the enter is pressed or to input as soon as the key is pressed. It is a dimension that you can detect key input by playing with it.
By the way, in the above example, the flag (ECHO) that decides whether to display the entered characters is also tampered with.
About termios. I also know about canonical mode. https://linuxjm.osdn.jp/html/LDP_man-pages/man3/termios.3.html
termios in python http://docs.python.jp/2/library/termios.html#module-termios
You can do something similar at a higher level than termios called tty. Or rather, this one is easier. Only available on Unix. http://docs.python.jp/2/library/tty.html#module-tty
I'm using tty to make a nice module http://code.activestate.com/recipes/134892/
Recommended Posts