4

http://code.activestate.com/recipes/134892/でレシピを使用するときはいつでも、それを機能させることができないようです。常に次のエラーがスローされます。

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

私の最善の考えは、Eclipseで実行しているためtermios、ファイル記述子に適合しているためです。

4

2 に答える 2

9

これはUbuntu8.04.1、Python 2.5.2で動作していますが、そのようなエラーは発生しません。コマンドラインから試してみてください。日食は独自のstdinを使用している可能性があります。WingIDEから実行するとまったく同じエラーが発生しますが、コマンドラインからはうまく機能します。理由は、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()
于 2009-06-27T04:34:18.457 に答える
4

端末を raw モードにすることは、必ずしも良い考えではありません。実際には、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()
于 2013-07-30T06:21:12.110 に答える