Skip to main content

Overview

KiCad provides a powerful Python scripting interface that allows you to automate board design tasks, create custom workflows, and extend functionality. The Python API is built using SWIG (Simplified Wrapper and Interface Generator) and exposes core KiCad classes and functions.

Python Environment

Initialization

The Python scripting environment is initialized when KiCad starts. The system uses the SCRIPTING class defined in /scripting/python_scripting.h:

Thread Safety

When interacting with the Python API from C++, use the PyLOCK class to ensure thread safety:

Core API Functions

The main Python API is exposed through pcbnew_scripting_helpers.h. Here are the essential functions:

Board Management

Accessing Board Elements

Unit Conversion

KiCad internally uses nanometers. Use these functions for conversion:

Modifying Board Elements

Plot Generation

Generate various output files programmatically:

Footprint Libraries

DRC (Design Rule Check)

Export Formats

Interactive Features

When running in the PCBNew GUI:

Advanced Examples

Creating Custom Footprints

Batch Processing

Error Handling

Best Practices

  1. Always close plot controllers: Call pctl.ClosePlot() when finished
  2. Use proper units: Always convert to internal units using FromMM() or FromMils()
  3. Validate board loading: Check if LoadBoard() returns None
  4. Avoid print statements: Print statements can cause issues when running from GUI
  5. Use RemoveNative(): For proper undo/redo support when removing items
  6. Lock Python GIL: Use PyLOCK when calling from C++

Common Pitfalls

  • Unicode handling: Always encode/decode strings properly for cross-platform compatibility
  • Layer IDs: Use layer constants like F_Cu, B_Cu instead of numeric values
  • Coordinate system: KiCad uses internal units (nanometers), not millimeters
  • Memory management: Some objects are owned by the board, others must be explicitly added

See Also