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 theSCRIPTING class defined in /scripting/python_scripting.h:
Thread Safety
When interacting with the Python API from C++, use thePyLOCK class to ensure thread safety:
Core API Functions
The main Python API is exposed throughpcbnew_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
- Always close plot controllers: Call
pctl.ClosePlot()when finished - Use proper units: Always convert to internal units using
FromMM()orFromMils() - Validate board loading: Check if
LoadBoard()returnsNone - Avoid print statements: Print statements can cause issues when running from GUI
- Use RemoveNative(): For proper undo/redo support when removing items
- Lock Python GIL: Use
PyLOCKwhen 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_Cuinstead 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
- Action Plugins - Create interactive plugins
- IPC API - Modern IPC communication protocol
- Custom File Formats - File format specifications