How to read a single character from the user?

后端 未结 23 2669
爱一瞬间的悲伤
爱一瞬间的悲伤 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:27

    Also worth trying is the readchar library, which is in part based on the ActiveState recipe mentioned in other answers.

    Installation:

    pip install readchar
    

    Usage:

    import readchar
    print("Reading a char:")
    print(repr(readchar.readchar()))
    print("Reading a key:")
    print(repr(readchar.readkey()))
    

    Tested on Windows and Linux with Python 2.7.

    On Windows, only keys which map to letters or ASCII control codes are supported (Backspace, Enter, Esc, Tab, Ctrl+letter). On GNU/Linux (depending on exact terminal, perhaps?) you also get Insert, Delete, Pg Up, Pg Dn, Home, End and F n keys... but then, there's issues separating these special keys from an Esc.

    Caveat: Like with most (all?) answers in here, signal keys like Ctrl+C, Ctrl+D and Ctrl+Z are caught and returned (as '\x03', '\x04' and '\x1a' respectively); your program can be come difficult to abort.

提交回复
热议问题