您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python跨平台监听按键?

Python跨平台监听按键?

我不知道任何跨平台的轻量级模块可以监听按键。但是,如果您想实现一些简单的操作,这里有个建议:

在Python常见问题解答中查看有关一次获得一次按键的问题。您可以尝试屏蔽来自sys.stdin和的读取threading。但这仅适用于Unix。在Windows上,您可以使用msvcrt.kbhit

结合Python FAQ和msvcrt模块中的按键配方,结果kbhit函数将如下所示:

try:
    from msvcrt import kbhit
except ImportError:
    import termios, fcntl, sys, os
    def kbhit():
        fd = sys.stdin.fileno()
        oldterm = termios.tcgetattr(fd)
        newattr = termios.tcgetattr(fd)
        newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
        termios.tcsetattr(fd, termios.TCSANow, newattr)
        oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
        fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
        try:
            while True:
                try:
                    c = sys.stdin.read(1)
                    return True
                except IOError:
                    return False
        finally:
            termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
            fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
python 2022/1/1 18:47:53 有525人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶