小编典典

Python从用户读取单个字符

python

有没有一种方法可以从用户输入中读取一个字符?例如,他们在终端上按一个键,然后将其返回(类似getch())。我知道Windows中有一个功能,但是我想要一些跨平台的功能。


阅读 962

收藏
2020-02-06

共1个答案

小编典典

以下是指向网站的链接,该网站说明了如何在Windows,Linux和OSX中读取单个字符: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()
2020-02-06