clang-format

22.1.3 · active · verified Fri Apr 10

clang-format is a Python package that distributes the official LLVM-based code formatting utility for C, C++, C#, Java, JavaScript, JSON, Objective-C, and Protobuf. It allows users to easily install and use a specific version of the `clang-format` executable via pip. The project aims to release a new PyPI package for each major and minor release of upstream clang-format, currently at version 22.1.3.

Warnings

Install

Imports

Quickstart

Demonstrates how to use the `clang-format` executable provided by the package to format a C++ code string. This is the most common usage pattern.

import subprocess
import os
import tempfile

# Create a dummy C++ file
cpp_code_unformatted = """
#include <iostream>

int main() {
    std::cout << "Hello, World!" << std::endl;
        return 0;
}
"""

# Use a temporary file to demonstrate formatting a real file
with tempfile.NamedTemporaryFile(mode='w', suffix='.cpp', delete=False) as temp_file:
    temp_file.write(cpp_code_unformatted)
    temp_file_path = temp_file.name

try:
    # Run clang-format on the temporary file
    # The 'clang-format' command is made available in PATH by the pip installation
    result = subprocess.run(
        ["clang-format", "-style=LLVM", temp_file_path],
        capture_output=True,
        text=True, # Decode stdout/stderr as text
        check=True # Raise an exception for non-zero exit codes
    )

    formatted_code = result.stdout
    print("Original code:\n", cpp_code_unformatted)
    print("\nFormatted code:\n", formatted_code)

except FileNotFoundError:
    print("Error: 'clang-format' executable not found. Make sure it's installed and in your system's PATH.")
except subprocess.CalledProcessError as e:
    print(f"Error formatting file: {e.returncode}")
    print(f"Stderr: {e.stderr}")
finally:
    # Clean up the temporary file
    os.remove(temp_file_path)

view raw JSON →