MCAP Python Library

1.3.1 · active · verified Sat Apr 11

The `mcap` library provides classes for reading and writing the MCAP file format. MCAP is a modular container format primarily intended for robotics applications, supporting pub/sub messages with arbitrary message serialization, including JSON, Protobuf, ROS 1, and ROS 2. It emphasizes high-performance writing, efficient seeking, and data recoverability. The project maintains an active development pace with frequent releases across its core library and various serialization support packages.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to write a simple MCAP file with JSON-encoded messages and then read it back using the `mcap` library's core reader and writer. It registers a schema and channel, adds a message, and iterates over messages to print their content.

import json
import sys
from time import time_ns
from mcap.writer import Writer
from mcap.reader import make_reader

file_path = "example.mcap"

# --- Writing an MCAP file ---
with open(file_path, "wb") as stream:
    writer = Writer(stream)
    writer.start(profile="x-my-profile", library="my-writer-v1")

    schema_id = writer.register_schema(
        name="sample",
        encoding="jsonschema",
        data=json.dumps({
            "type": "object",
            "properties": {
                "sample": {
                    "type": "string"
                }
            }
        }).encode(),
    )
    channel_id = writer.register_channel(
        schema_id=schema_id,
        topic="/sample_topic",
        message_encoding="json",
    )

    writer.add_message(
        channel_id=channel_id,
        log_time=time_ns(),
        data=json.dumps({"sample": "hello world"}).encode("utf-8"),
        publish_time=time_ns(),
    )
    writer.finish()
print(f"Wrote {file_path}")

# --- Reading an MCAP file ---
with open(file_path, "rb") as f:
    reader = make_reader(f)
    for schema, channel, message in reader.iter_messages(topics=["/sample_topic"]):
        print(f"Read: Topic='{channel.topic}' (Schema='{schema.name}'): {message.data.decode('utf-8')}")

view raw JSON →