python - 从 python 2 到 python 3 的 create_string_buffer 和 string.join 错误

标签 python python-3.x python-2.7

我有一个来自第三方的 Python 代码,它使用 Python 2.7 和 create_string_buffer 以及 ctypes 工具上的 string.join。我想将代码转换为 Python 3.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 变量设为 byte (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

关于python - 从 python 2 到 python 3 的 create_string_buffer 和 string.join 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62927560/

相关文章:

Python MemoryError 试图分割大字符串

Python实时编码/调试

python - 如何在 Python 中退出交互模式

python-3.x - Python - 如何使用 += 返回 for 循环

python - 如何使用图像每个像素的值绘制 3d 图形?

django - (fields.E300) 字段定义与模型的关系,该模型要么未安装,要么是抽象的

python - 如何使用不同版本的 Python 运行 Jupyter Notebook?

python - 对列表进行设置操作

python - 无法读取先前读取的 Excel 文件?

python - aws - "Unable to import module ' 进程' :/var/task/numpy/core/multiarray. 所以:ELF header 无效”