在Python中读取单个字符(getch样式)在Unix中不起作用

Eva*_*ark 4 python getch

任何时候我在http://code.activestate.com/recipes/134892/上使用该配方我似乎无法使其正常工作.它总是抛出以下错误:

Traceback (most recent call last):
    ...
    old_settings = termios.tcgetattr(fd)
termios.error: (22, 'Invalid argument)
Run Code Online (Sandbox Code Playgroud)

我最好的想法是,因为我在Eclipse中运行它所以termios正在抛出关于文件描述符的东西.

Anu*_*yal 9

这是在Ubuntu 8.04.1,Python 2.5.2上工作,我没有这样的错误.也许你应该从命令行尝试它,eclipse可能正在使用它自己的stdin,如果我从Wing IDE运行它,我得到完全相同的错误,但是从命令行它运行得很好.原因是IDE例如Wing正在使用自己的类netserver.CDbgInputStream作为sys.stdin,因此sys.stdin.fileno为零,这就是错误的原因.基本上IDE stdin不是tty(print sys.stdin.isatty()为False)

class _GetchUnix:
    def __init__(self):
        import tty, sys

    def __call__(self):
        import sys, tty, termios
        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


getch = _GetchUnix()

print getch()
Run Code Online (Sandbox Code Playgroud)


小智 5

将终端置于原始模式并不总是一个好主意。实际上清除 ICANON 位就足够了。这是具有超时支持的 getch() 的另一个版本:

import tty, sys, termios
import select

def setup_term(fd, when=termios.TCSAFLUSH):
    mode = termios.tcgetattr(fd)
    mode[tty.LFLAG] = mode[tty.LFLAG] & ~(termios.ECHO | termios.ICANON)
    termios.tcsetattr(fd, when, mode)

def getch(timeout=None):
    fd = sys.stdin.fileno()
    old_settings = termios.tcgetattr(fd)
    try:
        setup_term(fd)
        try:
            rw, wl, xl = select.select([fd], [], [], timeout)
        except select.error:
            return
        if rw:
            return sys.stdin.read(1)
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)

if __name__ == "__main__":
    print getch()
Run Code Online (Sandbox Code Playgroud)