python获取键盘上哪个键按下

当在Windows系统中,termios模块并不可用,因为termios是Unix系统(包括Linux和macOS)上的一个用于终端输入输出信息的接口,而Windows没有这样的系统调用。

如果你需要在Windows上使用类似termios的功能,你可以考虑以下替代方案:

  1. 使用Windows特有的库,如msvcrt(Microsoft Visual C Runtime),它提供了一些终端操作的功能。

    import os
    import sys
    import tty
    import termios

    def getkey():
    old_settings = termios.tcgetattr(sys.stdin)
    tty.setcbreak(sys.stdin.fileno())
    try:
    while True:
    b = os.read(sys.stdin.fileno(), 3).decode()
    if len(b) == 3:
    k = ord(b[2])
    else:
    k = ord(b)
    key_mapping = {
    127: 'backspace',
    10: 'return',
    32: 'space',
    9: 'tab',
    27: 'esc',
    65: 'up',
    66: 'down',
    67: 'right',
    68: 'left'
    }
    return key_mapping.get(k, chr(k))

    复制代码
     except TypeError:
         pass
     finally:
         termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)

    if name == 'main':
    try:
    while True:
    key = getkey()
    if key == 'esc':
    break
    else:
    print("key= ",key);
    except (KeyboardInterrupt, SystemExit):
    os.system('stty sane')
    print('stopping.')

运行程序按下键盘上的按键,会在终端打印对应的按键名

相关推荐
彦为君1 分钟前
JavaSE-07-异常机制
java·开发语言·后端·python·spring
Kurisu57516 分钟前
雾锁王国修改器下载2026最新
前端·修改器代码
OxyTheCrack18 分钟前
【Golang】简述make与new内置函数以及两者的区别
开发语言·golang
适应规律21 分钟前
【无标题】
人工智能·python·算法
Rain50928 分钟前
mini-cc 的 MCP 协议:给 AI 装个 USB-C 接口
c语言·开发语言·前端·人工智能·架构·node.js·ai编程
XLYcmy28 分钟前
全链路验证测试系统:一个针对智能代理(Agent)系统全链路能力的自动化验证脚本
分布式·python·http·网络安全·ai·llm·agent
有味道的男人39 分钟前
电商效率翻倍:京东全量商品信息抓取
python
华科大胡子1 小时前
AI开发者的网络卡点:Anthropic连接超时
开发语言·php
原来是猿1 小时前
博客系统自动化测试实战总结
python
磊 子1 小时前
STL无序关联容器—unorded_set+unorded_map
开发语言·c++