将python2.7项目转为Python3问题记录
将一个Python2.7开发的测试工具项目转化为Python3。
工具:Python自带的2to3.py
将所有.py文件进行转化,生成的python3文件为原文件名,python2文件在后面加.bak
1. 代码如:b = str(a).strip("\0").decode('gbk') + ','
运行报错,显示“AttributeError: 'str' object has no attribute 'decode'”。
参考:https://blog.csdn.net/zz00008888/article/details/123383157
修改为:b = a.decode('gbk').strip("\0") + ','
2. 代码如:struct.pack_into('16s', self.buffer_, self.offset_, bufferdict['name'])
报错:python3 struct.pack方法报错argument for 's' must be a bytes object
参考:https://blog.csdn.net/weixin_38383877/article/details/81100192
修改为:
if 's' in self.format_:
struct.pack_into(self.format_, self.buffer_, self.offset_, bufferdict['name'].encode('utf-8'))
else:
struct.pack_into(self.format_, self.buffer_, self.offset_, bufferdict['name'])
3. 代码如:resultlist.append(int(inputBuffer[i].encode('hex'), 16))
报错:python出错:AttributeError: 'int' object has no attribute 'encode'
修改为:resultlist.append(int(hex(inputBuffer[i]), 16))
4. 代码如:resultText = str(struct.unpack_from('1s', self.buffer_, offset)[0])
解析出的数据是b'2'
修改为:resultText = str(struct.unpack_from('1s', self.buffer_, offset)[0].decode('utf-8'))
解析出数据:2
5. try..except,代码如:
try:
print("right")
except IOError, err:
print ("IOError: ", err)
修改为:
try:
print("right")
except IOError as err: # as 加参数名称
print ("IOError: ", err)
6. print,如
print 1,2
修改为:
print(1,2)
7. binascii.b2a_hex,
如
print("Data is: " , binascii.b2a_hex(byte_str))
修改为:
print("Data is: " , binascii.b2a_hex(byte_str).encode('utf-8'))
参考:https://www.cnblogs.com/0yst3r-2046/p/14552149.html