You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 3中bytes对象调用split方法报TypeError的技术咨询

Fixing "TypeError: a bytes-like object is required, not 'str'" with ctypes Buffer

Let's break this down and fix that error quickly—you're already halfway there by identifying the bytes vs str mismatch!

The Root Cause

You're right that split() is a string method, but readBuffer.value is a bytes object (your type() check confirms this). When you try to call split(',') on bytes, Python throws that error because it expects a bytes separator, not a string one.

Two Simple Solutions

Since your goal is to extract the device ID (like 0 from your sample output), here are two straightforward approaches tailored to your use case:

1. Decode Bytes to String First (Most Readable)

Convert the bytes buffer to a regular string first, then handle splitting as you originally intended. This works perfectly because your device output uses ASCII-compatible characters:

readBuffer = ctypes.create_string_buffer(1024)
# Make sure your C function fills readBuffer before this step!

# Decode bytes to a string (use 'ascii' explicitly if you want to be precise)
device_str = readBuffer.value.decode()
# Clean up the trailing '\r;' and split into individual device entries
device_entries = device_str.rstrip('\r;').split(';')

# Extract the first device ID (loop through entries if multiple devices exist)
first_device_id = device_entries[0].split(',')[0]
print(f"Extracted Device ID: {first_device_id}")

2. Split Bytes Directly (No Decoding Needed)

If you prefer working with bytes without converting to a string, just use byte literals for your separators:

readBuffer = ctypes.create_string_buffer(1024)
# Make sure your C function fills readBuffer before this step!

# Strip trailing byte characters and split using byte separators
device_bytes_entries = readBuffer.value.rstrip(b'\r;').split(b';')

# Extract and decode the first device ID
first_device_id = device_bytes_entries[0].split(b',')[0].decode()
print(f"Extracted Device ID: {first_device_id}")

How This Works for Your Sample Output

Your sample readBuffer.value is b'0,NEWPORT 1936-R v1.2.2 04/06/12 SN22955\r;':

  • Both methods first remove the trailing \r; (or b'\r;' for bytes)
  • Split by ; (or b';') to get individual device entries
  • Split each entry by , (or b',') to separate the ID from the description
  • The first part of the first entry is your desired device ID (0)

内容的提问来源于stack exchange,提问作者Physicist

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:13:40