systemd-python

235 · active · verified Thu Apr 16

systemd-python provides a Python interface for libsystemd, allowing Python applications to interact with systemd components like the journal, daemon management, and unit control. The current version is 235. Releases are infrequent and typically tied to major systemd project releases.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to send a log message to the systemd journal using the `Journal` class. It includes custom fields for better discoverability and provides an error message if systemd-journald is not available, which is common when running on non-systemd systems or without proper access.

import os
from systemd.journal import Journal

# Get an environment variable, useful for identifying the service in the journal
service_identifier = os.environ.get('SYSTEMD_UNIT', 'my_python_script.service')

try:
    # Initialize the Journal object
    j = Journal()

    # Send a message to the systemd journal
    j.send(
        f'Hello from systemd-python! Test message from {service_identifier}.',
        PRIORITY='INFO',
        PYTHON_PROCESS=os.getpid(), # Example custom field
        SERVICE_NAME=service_identifier # Another custom field
    )
    print(f"Message successfully sent to systemd journal from {service_identifier}.")
except Exception as e:
    print(f"Failed to send message to systemd journal: {e}")
    print("Note: This script must be run on a Linux system with systemd-journald active and accessible.")
    print("You can view journal entries using: journalctl -f -t python-script")

view raw JSON →