You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows系统下Python的termios模块缺失问题及节拍器代码适配方案咨询

Windows系统运行Tap Tempo节拍测速脚本解决方案
  • 原脚本报错的核心原因是依赖仅Linux/macOS等类Unix系统提供的termios、tty终端控制模块,Windows原生Python没有集成这两个模块
  • 仅需对键盘输入读取逻辑做跨系统适配,即可实现Windows下正常运行,无需安装任何额外第三方依赖

适配后完整代码

#!/usr/bin/env python
from __future__ import print_function
import os
from time import time

# 跨平台输入适配
if os.name == 'nt':
    import msvcrt
    def getchar():
        return msvcrt.getch().decode('utf-8', errors='ignore')
else:
    import tty
    import termios
    from sys import stdin
    def getchar():
        fd = stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(stdin.fileno())
            ch = stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch


def addtime(times):
    if type(times) != list:
        raise(TypeError)
    t = time()
    if len(times) == 0:
        tdiff = 0  # initial seed
    else:
        tdiff = t - times[-1][0]
    return (t, tdiff)


def averagetimes(times):
    averagetime = sum([row[1] for row in times])/float(len(times))
    bpm = (1.0/(averagetime/60.0))
    return (averagetime, bpm)


def main():
    print('Tap a key on each beat. Press q to quit.', end='\r')

    times = []
    while True:
        char = getchar()
        if char in ('q', 'Q', '\x1b', '\x03'):  # q, Q, ESC, Control+C
            print()
            quit()

        times.append(addtime(times))
        if len(times) > 1:
            # remove first element if it's either the initial seed
            # or when the list reaches max length
            if times[0][1] == 0 or len(times) > 16:
                del times[0]
            (averagetime, bpm) = averagetimes(times)

            print("\rDetected BPM: %0.3f (Avg time between each: %0.3fs)"
                  % (bpm, averagetime), end='')


if __name__ == '__main__':
    main()

使用方法

  • 将代码保存为taptempo.py文件
  • 打开终端进入对应目录,执行python taptempo.py
  • 操作逻辑和原工具完全一致:跟随节拍敲击任意按键即可实时显示BPM数值,按q键、ESC键或Ctrl+C即可退出程序

内容的提问来源于stack exchange,提问作者egghead jr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 03:27:02