如何从用户那里读取单个字符?

新手上路,请多包涵

有没有办法从用户输入中读取一个字符?例如,他们在终端按下一个键并返回(有点像 getch() )。我知道 Windows 中有一个功能,但我想要跨平台的功能。

原文由 Evan Fosmark 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 556
2 个回答

下面是 ActiveState Recipes 站点的链接,其中介绍了如何在 Windows、Linux 和 OSX 中读取单个字符:

在 Windows 和 Unix 上从 stdin 读取类似 getch() 的无缓冲字符

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()

原文由 tehvan 发布,翻译遵循 CC BY-SA 4.0 许可协议

sys.stdin.read(1)

基本上会从 STDIN 读取 1 个字节。

如果您必须使用不等待 \n 的方法,您可以按照先前答案中的建议使用此代码:

 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()

取自 http://code.activestate.com/recipes/134892/

原文由 Yuval Adam 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题