创建字符串缓冲区和字符串。从python 2到python 3的连接错误
我有一个来自第三方的Python代码,它在ctypes工具上使用Python2.7和创建字符串缓冲区和字符串。从python 2到python 3的连接错误,python,python-3.x,python-2.7,Python,Python 3.x,Python 2.7,我有一个来自第三方的Python代码,它在ctypes工具上使用Python2.7和create\u string\u buffer和string.join。我想将代码转换为Python3.8.3,但在下面的部分我遇到了一个错误。以下是我使用2to3工具将其转换为Python3后的代码: for dev in self.devices: handle = libusb0.usb_open(dev) self.handles.append(handle) # ope
create\u string\u buffer
和string.join。我想将代码转换为Python3.8.3,但在下面的部分我遇到了一个错误。以下是我使用2to3工具将其转换为Python3后的代码:
for dev in self.devices:
handle = libusb0.usb_open(dev)
self.handles.append(handle) # open and store handle
sn_char = create_string_buffer('\000'*16)
libusb0.usb_get_string_simple(handle, offset, sn_char, 16)
ser_num = ''.join(sn_char).split(b'\0',1)[0] # treat first null-byte as stop character
self.sn.append(ser_num)
我得到的错误是:
sn_char = create_string_buffer('\000'*16)
File "C:\Python\Python383\lib\ctypes\__init__.py", line 65, in create_string_buffer
raise TypeError(init)
TypeError:
我也尝试过在create_string_buffer中创建一个init变量到字节(sn_char=create_string_buffer(b'\000'*16)
),但我仍然遇到了如下错误:
ser_num = ''.join(sn_char).split(b'\0',1)[0] # treat first null-byte as stop character
TypeError: sequence item 0: expected str instance, bytes found
希望能在这里得到解决方案,谢谢…当您使用
.split
并提供bytes
类型的参数时,您处理的对象也必须是bytes
类型
您可以通过在文本字符串之前添加b
轻松解决此问题:
ser_num = b''.join(sn_char).split(b'\0',1)[0] # treat first null-byte as stop character
感谢您的快速响应,是的,它可以运行,但是现在我在另一个使用create_string_buffer的代码中得到了新的错误,在这个代码中
def write_data(self, sn, words_in):
num_words = len(words_in)
dev_num = self.sn_to_devnum(sn)
handle = self.handles[dev_num]
buf = create_string_buffer(b'\000'*(num_words*2-1))
for n in range(num_words):
buf[2*n] = chr(words_in[n] % 0x100);
buf[2*n+1] = chr(words_in[n] // 0x100);
ret = libusb0.usb_bulk_write(handle, self.in_ep, buf, num_words*2,
self.usb_write_timeout);
#wr_buf = [ord(buf[n]) for n in range(num_bytes)]
#print "write buffer = ", wr_buf
return ret;
错误是:
buf[2*n] = chr(words_in[n] % 0x100);
TypeError: one character bytes, bytearray or integer expected
抱歉,如果我的问题重复且太简单,因为我是python新手…谢谢