사용자로부터 문자 하나를 읽어들이는 파이썬 프로그램

조회수 5288회

사용자의 입력값으로 하나의 문자만을 받을 방법이 있을까요? 예를 들어, 사용자가 터미널에서 키 하나만 누르면 (getch() 같이) 바로 반환되는 식으로요. 윈도우즈 환경에서는 관련한 함수가 있다는 걸 알지만, 저는 모든 플랫폼에서 가능한 방법을 알고 싶습니다.

1 답변

  • 좋아요

    0

    싫어요
    채택 취소하기

    해당 사이트에 윈도우즈, 리눅스, 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()
    

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)