Pythonで単一の文字(getchはスタイル)を読むと、UNIXで動作していません
質問
私は http://code.activestate.com/recipes/134892でレシピを使用する
任意の時間/
に私はそれが働くように見えることはできません。それは、常に次のエラーをスローします:Traceback (most recent call last):
...
old_settings = termios.tcgetattr(fd)
termios.error: (22, 'Invalid argument)
私の最高の考えは、私はそうtermios
は、ファイルディスクリプタについてのフィットを投げているEclipseでそれを実行しているので、それがあるということです。
解決
これはUbuntuの8.04.1、Pythonの2.5.2に取り組んでいる、私はそのようなエラーを取得していません。あなたは日食は、独自の標準入力を使用している可能性があり、コマンドラインからそれを試してみてくださいかもしれ、私はウィングIDEから実行した場合、私は正確に同じエラーを取得しますが、コマンドラインから、それは素晴らしい作品。 その理由は、IDE例えばウイングがsys.stdinをとしてそこに自分のクラスnetserver.CDbgInputStreamを使用していることです そうsys.stdin.filenoがゼロである、なぜエラーthatsの。 基本的にはIDEの標準入力がtty(印刷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()
他のヒント
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()
所属していません StackOverflow