【问题标题】:create_string_buffer and string.join error from python 2 to python 3从 python 2 到 python 3 的 create_string_buffer 和 string.join 错误
【发布时间】:2020-07-16 04:39:22
【问题描述】:

我有一个来自第三方的 Python 代码,它在 ctypes 工具上使用 Python 2.7 和 create_string_buffer 和 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 变量设置为字节(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

希望能在这里得到解决,谢谢...

【问题讨论】:

    标签: python python-3.x python-2.7


    【解决方案1】:

    当您使用.split 并提供bytes 类型的参数时,您处理的对象也必须是bytes 类型。

    您可以通过在文字字符串前添加b 轻松解决此问题:

    ser_num = b''.join(sn_char).split(b'\0',1)[0] # treat first null-byte as stop character
    

    【讨论】:

      【解决方案2】:

      感谢您的快速响应,是的,它可以运行,但现在我在使用 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 新手...谢谢

      【讨论】:

        猜你喜欢
        • 2012-01-29
        • 1970-01-01
        • 2019-09-06
        • 1970-01-01
        • 1970-01-01
        • 2020-01-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多