사용자로부터 문자 하나를 읽어들이는 파이썬 프로그램
조회수 5288회
사용자의 입력값으로 하나의 문자만을 받을 방법이 있을까요? 예를 들어, 사용자가 터미널에서 키 하나만 누르면 (getch()
같이) 바로 반환되는 식으로요. 윈도우즈 환경에서는 관련한 함수가 있다는 걸 알지만, 저는 모든 플랫폼에서 가능한 방법을 알고 싶습니다.
1 답변
-
해당 사이트에 윈도우즈, 리눅스, OS X 상에서 문자 하나만을 읽어들이는 방법이 나와있습니다 : http://code.activestate.com/recipes/134892/
class _Getch: """Gets a single character from standard input. Does not echo to the screen.""" def __init__(self): try: self.impl = _GetchWindows() except ImportError: self.impl = _GetchUnix() def __call__(self): return self.impl() 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 class _GetchWindows: def __init__(self): import msvcrt def __call__(self): import msvcrt return msvcrt.getch() getch = _Getch()
댓글 입력