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: object

Read 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 MS3Record returned by read() (and therefore by iteration via __next__()) shares a single C struct with the reader. The record is only valid until the next call to read() / next() on this reader, and is fully invalidated when the reader is exhausted or after close() is called. If you need to retain a record beyond the current iteration step, copy the fields you need (or load the data with MS3Record.parse(), MS3Record.from_buffer(), or MS3TraceList).

Parameters:
  • source (str | os.PathLike | int) –

    File path (str or any os.PathLike, e.g. pathlib.Path) or open file descriptor (int). Any other type raises TypeError. If an integer, it must be a non-negative, currently-open file descriptor (e.g. obtained from os.open()). Negative integers are rejected with ValueError. 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 whatever fd is currently bound to that slot (commonly 0=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 dup of the fd and closes only the duplicate; the original fd is not closed by close(), __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 MiniSEEDError after 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 source is missing or is not a supported type.

  • ValueError – If starttime or endtime is 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_ENDOFFILE and are reported as a clean end of stream when skip_not_data is 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:

MS3RecordReader

__exit__(exc_type, exc_value, traceback)[source]

Context manager exit point - ensures proper cleanup by calling close().

Parameters:
  • exc_type (Any)

  • exc_value (Any)

  • traceback (Any)

Return type:

None

__iter__()[source]

Iterator protocol - allows the reader to be used in for loops.

Return type:

MS3RecordReader

read()[source]

Read the next miniSEED record from the file or file descriptor.

Returns the next MS3Record, or None at end of stream. Raises ValueError if the reader has been closed, and MiniSEEDError if the stream ends part way through a record.

Warning

The returned MS3Record shares a single C struct with this reader. It is only valid until the next call to read() / next() on this reader, and is fully invalidated when the reader is exhausted or after close() is called. Copy the fields you need before reading the next record if you need to retain them.

Return type:

MS3Record | None

__next__()[source]

Iterator protocol - returns the next record or raises StopIteration.

See read() for the lifetime contract of the returned record (each yielded MS3Record is invalidated by the next call).

Return type:

MS3Record

__del__()[source]

Ensure cleanup when object is garbage collected

Return type:

None

close()[source]

Close the reader and free any allocated memory.

Idempotent: safe to call multiple times.

Return type:

None