Sphinx Internationalization Utility

2.3.2 · active · verified Thu Apr 16

sphinx-intl is a utility for Sphinx that simplifies the process of translating documentation. It helps manage `.pot` (Portable Object Template) and `.po` (Portable Object) files, making it easier to extract translatable messages, update translations, and build translated versions of Sphinx projects. The current version is 2.3.2, and it typically sees a few releases per year, keeping pace with Python and Sphinx updates.

Common errors

Warnings

Install

Quickstart

This quickstart demonstrates the core workflow of sphinx-intl using a temporary Sphinx project. It covers generating `.pot` files, initializing a locale, updating `.po` files, simulating translation, building `.mo` files, and finally building the translated HTML output.

import os
import shutil
import subprocess
import tempfile

# Create a temporary directory for the Sphinx project
temp_dir = tempfile.mkdtemp()
print(f"Working in temporary directory: {temp_dir}")

try:
    project_dir = os.path.join(temp_dir, "myproject")
    os.makedirs(project_dir)

    # 1. Create a minimal conf.py
    conf_content = '''
import os
import sys
sys.path.insert(0, os.path.abspath('.'))

project = 'My Translated Project'
copyright = '2024, Author'
extensions = []
html_theme = 'alabaster'
'''
    with open(os.path.join(project_dir, "conf.py"), "w") as f:
        f.write(conf_content)

    # 2. Create a minimal index.rst with translatable content
    index_content = '''
.. _index:

Welcome to My Translated Project
================================

.. rst-class:: special

This is a paragraph that needs translation.

Another paragraph.
'''
    with open(os.path.join(project_dir, "index.rst"), "w") as f:
        f.write(index_content)

    # 3. Generate POT files using sphinx-build
    print("\n--- Generating .pot files ---")
    gettext_output_dir = os.path.join(project_dir, "_build", "gettext")
    subprocess.run(["sphinx-build", "-b", "gettext", project_dir, gettext_output_dir], check=True, capture_output=True, text=True)

    # 4. Initialize locale directory for a target language (e.g., French)
    print("\n--- Initializing French locale ---")
    locale_dir = os.path.join(project_dir, "_build", "locale")
    subprocess.run(["sphinx-intl", "init", "-l", "fr", "-d", locale_dir, "-p", gettext_output_dir], check=True, capture_output=True, text=True)

    # 5. Update PO files (no changes yet, but good practice)
    print("\n--- Updating PO files (no changes expected yet) ---")
    subprocess.run(["sphinx-intl", "update", "-l", "fr", "-d", locale_dir, "-p", gettext_output_dir], check=True, capture_output=True, text=True)

    # Simulate manual translation: modify the .po file
    po_file_path = os.path.join(locale_dir, "fr", "LC_MESSAGES", "index.po")
    if os.path.exists(po_file_path):
        with open(po_file_path, "r") as f:
            po_content = f.read()
        po_content = po_content.replace(
            'msgid "This is a paragraph that needs translation."',
            'msgid "This is a paragraph that needs translation."\nmsgstr "Ceci est un paragraphe à traduire."
        )
        po_content = po_content.replace(
            'msgid "Another paragraph."',
            'msgid "Another paragraph."\nmsgstr "Un autre paragraphe."
        )
        with open(po_file_path, "w") as f:
            f.write(po_content)
        print(f"--- Translated {po_file_path} ---")
    else:
        print(f"Error: {po_file_path} not found.")

    # 6. Build MO files from PO files using sphinx-intl build
    print("\n--- Building MO files from PO files ---")
    subprocess.run(["sphinx-intl", "build", "-d", locale_dir], check=True, capture_output=True, text=True)

    # 7. Build HTML output for the translated language
    print("\n--- Building translated HTML documentation ---")
    html_output_dir_fr = os.path.join(project_dir, "_build", "html", "fr")
    subprocess.run(["sphinx-build", "-b", "html", "-D", "language=fr", project_dir, html_output_dir_fr], check=True, capture_output=True, text=True)

    print(f"\nSuccessfully built translated documentation in: {html_output_dir_fr}")
    print("Check the generated HTML files, e.g., _build/html/fr/index.html")

except subprocess.CalledProcessError as e:
    print(f"Error executing command: {e.cmd}")
    print(f"Return code: {e.returncode}")
    print(f"Stdout:\n{e.stdout}")
    if e.stderr:
        print(f"Stderr:\n{e.stderr}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")
finally:
    # Clean up the temporary directory
    print(f"\nCleaning up temporary directory: {temp_dir}")
    shutil.rmtree(temp_dir)

view raw JSON →