+ -
当前位置:首页 → 问答吧 → 程序运行出错 TypeError: 'str' does not support the buffer interface

程序运行出错 TypeError: 'str' does not support the buffer interface

时间:2011-03-25

来源:互联网

程序功能:测试通过COM1串口对设备收发数据的正确率。

运行时错误提示如下,请帮忙查看是什么原因?多谢!

Traceback (most recent call last):
  File "D:\work\python\serial-modbus.py", line 24, in <module>
    sendbin=binascii.a2b_hex(sends)
TypeError: 'str' does not support the buffer interface

使用Python3.2,源代码:

if __name__ == '__main__':
    import sys
    import time
    import binascii
    import datetime
    from time import gmtime, strftime

    #日志初始化(修改这里)
    LogR=open('D:\\work\\python\\test\\pkgtestR.txt','r+') #所有包
    LogE=open('D:\\work\\python\\test\\pkgtestE.txt','r+') #错误包
    LogN=open('D:\\work\\python\\test\\pkgtestN.txt','r+') #空包
    num=0
    err=0
    nul=0
    #发送数据包(修改这里)
    sends='01 04 13 87 00 01 85 67'
    #验证数据包(修改这里)
    checks='01 04 02 00 91 78 9C '

    #这里将字符串转成HEX数据
    sends=sends.replace(' ','')
    sendbin=binascii.a2b_hex(sends)   
    checks=checks.replace(' ','')
    checkbin=binascii.a2b_hex(checks)
    #打开通讯口
    fserial=open('COM1','rb+')
   
    for i in range(1000):
        try:
            fserial.write(sendbin)
            fserial.flush()
            time.sleep(0.3)
            sebuf=fserial.read(255)
            #将HEX数据转换成字符串
            if len(sebuf)>0:
                strdat=str(binascii.b2a_hex(sebuf))
                strdat=strdat[2:len(strdat)-1]
                index=2
                while index<len(strdat):
                    strdat=strdat[:index]+' '+strdat[index:]
                    index=index+3
            else:
                strdat=''
            #精确保存时间
            mstr=datetime.datetime.now()
            tstr=strftime("%Y-%m-%d %H:%M:%S ", gmtime()) + str(mstr.microsecond) + '('
            if sebuf==checkbin:
                num=num+1
            elif sebuf==b'':
                nul=nul+1
                LogN.write(str(i)+' '+tstr+strdat+')\n')
            else:
                err=err+1
                LogE.write(str(i)+' '+tstr+strdat+')\n')
            
            print(str(i)+' '+tstr+strdat+')')
            LogR.write(str(i)+' '+tstr+strdat+')\n')
        except:
            print('串口读取错误')

    print('测试通讯包间隔时间0.3秒')
    print('成功接收包数='+str(num))
    print('失败接收包数='+str(err))
    print('空包数='+str(nul))
   
    LogR.write('测试通讯包间隔时间0.3秒\n')
    LogR.write('成功接收包数='+str(num)+'\n')
    LogR.write('失败接收包数='+str(err)+'\n')
    LogR.write('空包数='+str(nul)+'\n')
    fserial.close()
    LogR.close()
    LogE.close()
    LogN.close()

作者: zqsq   发布时间: 2011-03-25

Just try

sendbin=binascii.a2b_hex(sends.encode('ascii') )

to see if that may works

作者: iamkey9   发布时间: 2011-03-26