如何通过PySerial跳过特定字节,避免读取无用的27、28字节?
Great question! Let's break down how this works with PySerial and serial communication in general.
First, a key reality: Serial communication operates as a byte stream—your serial hardware (and PySerial by extension) can't "skip" bytes before they're received. The port will capture all incoming bytes, and PySerial just exposes that stream to your code. So you can't tell the hardware to ignore bytes 27 and 28 entirely, but you can optimize your reading logic to avoid storing or processing those unwanted bytes, which achieves your goal of not dealing with them unnecessarily.
Here's a clean, intentional approach tailored to your 33-byte frame:
- Read the first 26 bytes (the ones you need: positions 1-26)
- Read the next 2 bytes (positions 27-28) but discard them immediately (no need to assign them to a variable you'll use)
- Read the final 5 bytes (positions 29-33) which you need
Here's the code example:
import serial # Initialize your serial port (adjust port, baud rate, timeout to match your setup) ser = serial.Serial('COM3', 9600, timeout=2) try: # Grab the first 26 useful bytes useful_part1 = ser.read(26) # Skip the 2 unwanted bytes by reading them without storing ser.read(2) # Grab the remaining 5 useful bytes useful_part2 = ser.read(5) # Combine the parts you care about final_data = useful_part1 + useful_part2 # Use your data here (example: print as hex) print(f"Received useful data: {final_data.hex()}") finally: # Always close the port when done ser.close()
Quick notes to keep in mind:
- This works reliably only if your data is sent as fixed-length 33-byte frames. If there's any risk of frame misalignment (e.g., dropped bytes, line noise), add a frame sync step first—like looking for a unique header byte/sequence at the start of each frame. This ensures you're starting to read at position 1, not somewhere in the middle.
- While you technically still "read" the 2 unwanted bytes, this approach is more intentional than reading all 33 bytes and slicing later. It makes your code's purpose clear, and avoids holding unnecessary data in memory longer than needed.
内容的提问来源于stack exchange,提问作者Harsh Sulakhe

