MS3RecordReader¶
- class pymseed.MS3RecordReader(source, *, start_byte_offset=0, end_byte_offset=0, unpack_data=False, sourceid=None, starttime=None, endtime=None, skip_not_data=False, validate_crc=True, verbose=0)[source]¶
Bases:
objectRead miniSEED records from a file or file descriptor.
Usually created via
MS3Record.from_file()rather than directly.This class provides a Python interface for reading miniSEED records from files or file descriptors.
The reader can be used as an iterator to process records sequentially, or as a context manager for automatic resource cleanup.
Warning
Each
MS3Recordreturned byread()(and therefore by iteration via__next__()) shares a single C struct with the reader. The record is only valid until the next call toread()/next()on this reader, and is fully invalidated when the reader is exhausted or afterclose()is called. If you need to retain a record beyond the current iteration step, copy the fields you need (or load the data withMS3Record.parse(),MS3Record.from_buffer(), orMS3TraceList).- Parameters:
source (str | os.PathLike | int) –
File path (
stror anyos.PathLike, e.g.pathlib.Path) or open file descriptor (int). Any other type raisesTypeError. If an integer, it must be a non-negative, currently-open file descriptor (e.g. obtained fromos.open()). Negative integers are rejected withValueError. The class will not verify that an arbitrary non-negative integer corresponds to a valid open descriptor — passing the wrong number will silently read from whateverfdis currently bound to that slot (commonly0=stdin,1=stdout,2=stderr).Ownership semantics differ by source type:
Path (str): libmseed opens an internal file handle and closes it automatically on
close(), context-manager exit, or garbage collection.File descriptor (int): the caller retains ownership of the descriptor. libmseed reads through an internal
dupof the fd and closes only the duplicate; the original fd is not closed byclose(),__exit__, or__del__, and the caller is responsible for closing it.
start_byte_offset (int) – Start byte offset in the input bytes stream. Defaults to 0.
end_byte_offset (int) – End byte offset in the input bytes stream. Defaults to 0, which means read until the end of the stream. A range ending part way through a record raises
MiniSEEDErrorafter the records that fit within it, as a truncated stream does.unpack_data (bool) – Whether to decode/unpack the data samples from the records. If False, only metadata is parsed and data remains in compressed format. Defaults to False for better performance when only metadata is needed.
sourceid (str) – Source ID glob pattern to select matching records (e.g.
"FDSN:IU_COLA_*"). None matches all source IDs. Defaults to None.starttime (str) – Start of time window as a formatted date-time string (e.g.
"2024-01-01T00:00:00Z"). Only records containing data after this time are returned. None means open start. Defaults to None.endtime (str) – End of time window as a formatted date-time string. Only records containing data before this time are returned. None means open end. Defaults to None.
skip_not_data (bool) – Whether to skip non-data bytes in the input stream until a valid miniSEED record is found. Useful for reading from streams that may contain other data mixed with miniSEED records. Defaults to False.
validate_crc (bool) – If True, validate CRC checksums when present in records. miniSEED v3 records contain CRCs, but v2 records do not. Default is True.
verbose (int) – Verbosity level for libmseed operations. Higher values produce more detailed output. 0 = no output, 1+ = increasing verbosity. Defaults to 0 (silent).
- Raises:
TypeError – If
sourceis missing or is not a supported type.ValueError – If
starttimeorendtimeis not a valid date-time string.MiniSEEDError – If the file or file descriptor cannot be initialized for reading, or if the stream ends part way through a record, or with bytes remaining that are too few for one. The truncated cases carry a status of
MS_ENDOFFILEand are reported as a clean end of stream whenskip_not_datais set.
Examples
Basic usage with a file path as a context manager:
>>> from pymseed import MS3Record
>>> total_samples = 0 >>> for msr in MS3Record.from_file('examples/example_data.mseed', unpack_data=True): ... total_samples += msr.numsamples >>> print(f"Total samples: {total_samples}") Total samples: 12600
Selecting records by source ID and time window. The filtering is applied by libmseed while reading, non-matching records are skipped without leaving the C layer and their data samples are never decoded:
>>> records = 0 >>> for msr in MS3Record.from_file( ... 'examples/example_data.mseed', ... sourceid='FDSN:IU_COLA_00_L_H_Z', ... starttime='2010-02-27T07:00:00Z', ... endtime='2010-02-27T07:30:00Z', ... ): ... records += 1 >>> print(f"Matching records: {records}") Matching records: 15
Using with an open file descriptor (caller closes the fd):
>>> import os >>> flags = os.O_RDONLY | getattr(os, 'O_BINARY', 0) # For Windows portability >>> fd = os.open('examples/example_data.mseed', flags) >>> try: ... total_records = 0 ... for msr in MS3Record.from_file(fd, unpack_data=False): ... total_records += 1 ... finally: ... os.close(fd) >>> print(f"Total records: {total_records}") Total records: 107
Note
This class is not thread-safe. Each thread should use its own reader instance. The underlying libmseed library handles the actual parsing and decompression.
See also
MS3Record.from_file(): use this instead of MS3RecordReader directly
- __enter__()[source]¶
Context manager entry point - returns self for use in ‘with’ statements.
- Return type:
- __exit__(exc_type, exc_value, traceback)[source]¶
Context manager exit point - ensures proper cleanup by calling close().
- read()[source]¶
Read the next miniSEED record from the file or file descriptor.
Returns the next
MS3Record, orNoneat end of stream. RaisesValueErrorif the reader has been closed, andMiniSEEDErrorif the stream ends part way through a record.Warning
The returned
MS3Recordshares a single C struct with this reader. It is only valid until the next call toread()/next()on this reader, and is fully invalidated when the reader is exhausted or afterclose()is called. Copy the fields you need before reading the next record if you need to retain them.- Return type:
MS3Record | None