为了账号安全,请及时绑定邮箱和手机立即绑定

在python中轮询键盘(检测按键)

在python中轮询键盘(检测按键)

德玛西亚99 2019-08-08 15:28:17
在python中轮询键盘(检测按键)如何从控制台python应用程序轮询键盘?具体来说,我想在许多其他I / O活动(套接字选择,串行端口访问等)中做类似的事情:   while 1:       # doing amazing pythonic embedded stuff       # ...       # periodically do a non-blocking check to see if       # we are being told to do something else       x = keyboard.read(1000, timeout = 0)       if len(x):           # ok, some key got pressed           # do something在Windows上执行此操作的正确pythonic方法是什么?此外,Linux的可移植性也不错,但并不是必需的。
查看完整描述

3 回答

?
守着星空守着你

TA贡献1799条经验 获得超8个赞

标准方法是使用选择模块。

但是,这在Windows上不起作用。为此,您可以使用msvcrt模块的键盘轮询。

通常,这是通过多个线程完成的 - 每个设备被“监视”一个加上可能需要被设备中断的后台进程。


查看完整回答
反对 回复 2019-08-08
?
慕盖茨4494581

TA贡献1850条经验 获得超11个赞

使用curses模块的解决方案。打印与按下的每个键对应的数值:

import cursesdef main(stdscr):
    # do not wait for input when calling getch
    stdscr.nodelay(1)
    while True:
        # get keyboard input, returns -1 if none available
        c = stdscr.getch()
        if c != -1:
            # print numeric value
            stdscr.addstr(str(c) + ' ')
            stdscr.refresh()
            # return curser to start position
            stdscr.move(0, 0)if __name__ == '__main__':
    curses.wrapper(main)


查看完整回答
反对 回复 2019-08-08
  • 3 回答
  • 0 关注
  • 1619 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号