Steven D'Aprano <steve+comp.lang.pyt...@pearwood.info> writes: > On Thu, 30 Jan 2014 18:13:54 +1300, Gregory Ewing wrote: > >> Steven D'Aprano wrote: >>> On Mon, 27 Jan 2014 12:22:22 -0800, Rick Johnson wrote: >>> >>>>Why do we even need an "input" function anyway if all it is going to do >>>>is read from stdin? >>> >>> That's not all it does. >>> >>> For example, it handles backspacing, so that typing H E L O O BACKSPACE >>> BACKSPACE L O gives "HELLO" rather than "HELOO\x7f\x7fO". >> >> No, it doesn't -- that's handled at a lower level. Any other method of >> reading from stdin, as long as it hasn't been redirected away from the >> console, has the same behaviour. >> >> I typed some backspaces in the input to each of the following >> experiments, and they didn't end up in the data: >> >> >>> import sys >> >>> x = sys.stdin.readline() >> HELLO >> >>> x >> 'HELLO\n' >> >>> import os >> >>> f = os.fdopen(0) >> >>> y = f.readline() >> adsxx >> >>> y >> 'adsxx\n' > > > Very interesting. I admit I don't actually understand the way stdin > works. Can you explain what's going on here then? > > import sys, os > import tty, termios, fcntl > > def getch(): > """Get a single character from standard input. > > Does not echo to the screen. This will block waiting for a keypress. > """ > fd = sys.stdin.fileno() > old_settings = termios.tcgetattr(fd) > try: > tty.setraw(fd) > ch = sys.stdin.read(1) > finally: > termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) > return ch > > > And in use: > >>>> [getch() for i in range(14)] > ['H', 'e', 'l', 'l', 'l', '\x7f', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!'] > > > where I type "Helll BACKSPACE o SPACE World!" > > > At what point do the arrow keys and other readline or readline-like > features get handled? >
They can be handled by the in-kernel tty driver, when you're using a tty set in "cooked" mode. This driver can be configured by the termios functions, which invoke various ioctls on the terminal devices. Or you can set the tty to "raw" mode, and the keystrokes are passed on to the application, which can do all sorts of interpretation (for example if you're using the readline library, or a curses app). W. Richard Stevens covers this in much detail in APUE, but you can preserve your sanity by being ignorant of the details of tty handling. -- regards, kushal
pgp_vFN2YRuSu.pgp
Description: PGP signature
-- https://mail.python.org/mailman/listinfo/python-list