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

树莓派USB条形码扫描器Python脚本报TypeError错误如何修复

问题修复方案

报错根因

  • 该脚本原本为Python2编写,树莓派当前默认运行Python3,二者对二进制文件读取的返回值处理存在差异:
    • Python2中rb模式读取文件返回字符串,迭代得到的每个元素是单字符,需要用ord()转为对应整数
    • Python3中rb模式读取文件返回bytes对象,迭代得到的每个元素本身就是0~255的整数,直接调用ord()处理整数就会触发该报错

修复方法

将代码中所有ord(c)的写法直接替换为c,同时删除冗余的int()包裹逻辑即可。

修复后完整代码

#!/usr/bin/python3
import sys
def barcode_reader():
    hid = {4: 'a', 5: 'b', 6: 'c', 7: 'd', 8: 'e', 9: 'f', 10: 'g', 11: 'h', 12: 'i', 13: 'j', 14: 'k', 15: 'l', 16: 'm',
           17: 'n', 18: 'o', 19: 'p', 20: 'q', 21: 'r', 22: 's', 23: 't', 24: 'u', 25: 'v', 26: 'w', 27: 'x', 28: 'y',
           29: 'z', 30: '1', 31: '2', 32: '3', 33: '4', 34: '5', 35: '6', 36: '7', 37: '8', 38: '9', 39: '0', 44: ' ',
           45: '-', 46: '=', 47: '[', 48: ']', 49: '\\', 51: ';', 52: '\'', 53: '~', 54: ',', 55: '.', 56: '/'}
    hid2 = {4: 'A', 5: 'B', 6: 'C', 7: 'D', 8: 'E', 9: 'F', 10: 'G', 11: 'H', 12: 'I', 13: 'J', 14: 'K', 15: 'L', 16: 'M',
            17: 'N', 18: 'O', 19: 'P', 20: 'Q', 21: 'R', 22: 'S', 23: 'T', 24: 'U', 25: 'V', 26: 'W', 27: 'X', 28: 'Y',
            29: 'Z', 30: '!', 31: '@', 32: '#', 33: '$', 34: '%', 35: '^', 36: '&', 37: '*', 38: '(', 39: ')', 44: ' ',
            45: '_', 46: '+', 47: '{', 48: '}', 49: '|', 51: ':', 52: '"', 53: '~', 54: '<', 55: '>', 56: '?'}
    fp = open('/dev/hidraw0', 'rb')
    ss = ""
    shift = False
    done = False
    while not done:
        buffer = fp.read(8)
        for c in buffer:
            if c > 0:
                if c == 40:
                    done = True
                    break
                if shift:
                    if c == 2:
                        shift = True
                    else:
                        ss += hid2[c]
                        shift = False
                else:
                    if c == 2:
                        shift = True
                    else:
                        ss += hid[c]
    return ss
if __name__ == '__main__':
    try:
        while True:
            print(barcode_reader()) # 可选添加,方便直接看到扫描结果
    except KeyboardInterrupt:
        pass

内容的提问来源于stack exchange,提问作者John Roberts

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 12:48:05