Python에서 단일 캐릭터 (Getch Style) 읽기는 Unix에서 작동하지 않습니다.

StackOverflow https://stackoverflow.com/questions/1052107

  •  20-08-2019
  •  | 
  •  

문제

레시피를 사용할 때마다 http://code.activestate.com/recipes/134892/ 작동하지 않는 것 같습니다. 항상 다음 오류를 던집니다.

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

내 최선의 생각은 내가 일식으로 실행하기 때문이라는 것입니다. termios 파일 디스크립터에 대해 적합합니다.

도움이 되었습니까?

해결책

이것은 Ubuntu 8.04.1, Python 2.5.2에서 작동합니다. 그러한 오류는 없습니다. 명령 줄에서 시도해야 할 수도 있습니다. Eclipse가 자체 stdin을 사용하고있을 수 있습니다. Wing IDE에서 실행하면 똑같은 오류가 발생하지만 명령 줄에서 잘 작동합니다. 이유는 Ide Eg Wing이 Sys.stdin sys.stdin.fileno가 0이므로 오류가 발생하기 때문에 Ode Eg Wing이 자신의 클래스 NetServer.cdbginputStream을 사용하고 있기 때문입니다. 기본적으로 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()

다른 팁

터미널을 원시 모드에 넣는 것이 항상 좋은 생각은 아닙니다. 실제로 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()
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top