Python getch

有时候我们需要用户的输入,但不需要回车。比如贪吃蛇这类的小游戏,我们不需要每移动一次就回车一次。

源代码来自https://code.activestate.com/recipes/134892-getch-like-unbuffered-character-reading-from-stdin/

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

但是这会有个问题,就是输入 a 会出现 b’a’

虽然这里也有一篇文章讲过这些问题

但我也找到一种方法

在调用的时候使用str(getch())

import getch
a = str(getch())
if a == "b'a'":
    print(a)
    print("成功")
else:
    print("失败")
    print(a)

在这里输入的是 a

这个函数只能在cmd控制台使用

(转载请注明,如有侵权请及时联系ljsdwzljs@163.com避免不必要的纠纷,版权所有©ljs)

知识共享许可协议

Python getchwww.ljsdwz.cn 采用 知识共享 署名-相同方式共享 4.0 国际 许可协议进行许可。

留下评论

您的邮箱地址不会被公开。 必填项已用 * 标注