How to read a single character from the user?

后端 未结 23 2736
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-21 04:28

Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like getch()).

23条回答
  •  既然无缘
    2020-11-21 05:19

    The curses package in python can be used to enter "raw" mode for character input from the terminal with just a few statements. Curses' main use is to take over the screen for output, which may not be what you want. This code snippet uses print() statements instead, which are usable, but you must be aware of how curses changes line endings attached to output.

    #!/usr/bin/python3
    # Demo of single char terminal input in raw mode with the curses package.
    import sys, curses
    
    def run_one_char(dummy):
        'Run until a carriage return is entered'
        char = ' '
        print('Welcome to curses', flush=True)
        while ord(char) != 13:
            char = one_char()
    
    def one_char():
        'Read one character from the keyboard'
        print('\r? ', flush= True, end = '')
    
        ## A blocking single char read in raw mode. 
        char = sys.stdin.read(1)
        print('You entered %s\r' % char)
        return char
    
    ## Must init curses before calling any functions
    curses.initscr()
    ## To make sure the terminal returns to its initial settings,
    ## and to set raw mode and guarantee cleanup on exit. 
    curses.wrapper(run_one_char)
    print('Curses be gone!')
    

提交回复
热议问题