Skip to main content
The Python (SWIG) API is being deprecated in favor of the modern IPC API. For new integrations, we strongly recommend using the IPC Protocol which provides better performance, language-agnostic access, improved stability, and future-proof compatibility. The Python API is maintained for backward compatibility but may not receive new features.
KiCad provides a comprehensive Python API for automating PCB design tasks, creating action plugins, and generating footprint wizards. The API is accessible through the pcbnew module.

Getting Started

Import the pcbnew module to access the Python API:
import pcbnew

Core Functions

Board Management

LoadBoard(filename, format=None)

Loads a board from file. Parameters:
  • filename (str): Path to the board file
  • format (PCB_IO_MGR.PCB_FILE_T, optional): File format specifier
Returns: BOARD object or None if loading fails
board = pcbnew.LoadBoard("path/to/board.kicad_pcb")

GetBoard()

Returns the currently active board in the PCB editor. Returns: BOARD object or None
board = pcbnew.GetBoard()

CreateEmptyBoard()

Constructs a default BOARD with a temporary project. Returns: New BOARD object
board = pcbnew.CreateEmptyBoard()

NewBoard(filename)

Creates a new board and project with the given filename (will overwrite existing files). Parameters:
  • filename (str): Full path for the new board file
Returns: BOARD object or None

SaveBoard(filename, board, skipSettings=False)

Saves a board to file in KiCad native format. Parameters:
  • filename (str): Target file path
  • board (BOARD): Board object to save
  • skipSettings (bool): If True, only save the board file (loses project settings)
Returns: True if successful, False otherwise
pcbnew.SaveBoard("output.kicad_pcb", board)

Drawing and Plotting

PLOT_CONTROLLER(board)

Creates a plot controller for generating output files. Parameters:
  • board (BOARD): Board to plot
board = pcbnew.LoadBoard("design.kicad_pcb")
pctl = pcbnew.PLOT_CONTROLLER(board)
popt = pctl.GetPlotOptions()

# Configure plot options
popt.SetOutputDirectory("plot/")
popt.SetPlotFrameRef(False)
popt.SetUseGerberAttributes(True)

# Plot a layer
pctl.SetLayer(pcbnew.F_Cu)
pctl.OpenPlotfile("top_copper", pcbnew.PLOT_FORMAT_GERBER, "Top layer")
pctl.PlotLayer()
pctl.ClosePlot()

Plot Options Methods

  • SetOutputDirectory(dir) - Set output directory for plot files
  • SetPlotFrameRef(bool) - Enable/disable frame reference plotting
  • SetSketchPadLineWidth(width) - Set pad line width for sketch mode
  • SetAutoScale(bool) - Enable/disable auto-scaling
  • SetScale(scale) - Set plot scale (typically 1)
  • SetMirror(bool) - Enable/disable mirroring
  • SetUseGerberAttributes(bool) - Include Gerber X2 attributes
  • SetIncludeGerberNetlistInfo(bool) - Include netlist information
  • SetCreateGerberJobFile(bool) - Generate .gbrjob file
  • SetUseAuxOrigin(bool) - Use auxiliary origin
  • SetPlotReference(bool) - Plot component references
  • SetPlotValue(bool) - Plot component values
  • SetSubtractMaskFromSilk(bool) - Remove soldermask from silkscreen
  • SetDrillMarksType(type) - Set drill mark style

Drill File Generation

EXCELLON_WRITER(board)

Creates a drill file writer.
board = pcbnew.LoadBoard("design.kicad_pcb")
drlwriter = pcbnew.EXCELLON_WRITER(board)

# Configure drill file options
drlwriter.SetMapFileFormat(pcbnew.PLOT_FORMAT_PDF)
drlwriter.SetFormat(metricFmt=True)

mirror = False
minimalHeader = False
offset = pcbnew.VECTOR2I(0, 0)
mergeNPTH = False
drlwriter.SetOptions(mirror, minimalHeader, offset, mergeNPTH)

# Generate files
genDrl = True
genMap = True
drlwriter.CreateDrillandMapFilesSet(output_dir, genDrl, genMap)

# Generate report
drlwriter.GenDrillReportFile("drill_report.rpt")

Library Management

GetFootprintLibraries()

Returns all configured footprint library nicknames. Returns: wxArrayString of library nicknames
libraries = pcbnew.GetFootprintLibraries()

GetFootprints(nickname)

Returns all footprint names in a library. Parameters:
  • nickname (str): Library nickname
Returns: wxArrayString of footprint names
footprints = pcbnew.GetFootprints("Resistor_SMD")

Utility Functions

Unit Conversion

# Convert millimeters to internal units (nanometers)
pcbnew.FromMM(value)

# Convert mils to internal units
pcbnew.FromMils(value)

# Convert internal units to millimeters
pcbnew.ToMM(value)

# Convert internal units to mils
pcbnew.ToMils(value)

Refresh()

Updates the board display after modifications.
pcbnew.Refresh()

UpdateUserInterface()

Updates layer manager and widgets from board setup.
pcbnew.UpdateUserInterface()

GetUserUnits()

Returns the current user unit setting. Returns: 0 for inches, 1 for mm, -1 if frame not set

GetCurrentSelection()

Returns currently selected board items. Returns: deque of BOARD_ITEM objects

FocusOnItem(item, layer=UNDEFINED_LAYER)

Focuses the view on a specific board item. Parameters:
  • item (BOARD_ITEM): Target item
  • layer (PCB_LAYER_ID): Layer ID (optional)

DRC and Validation

WriteDRCReport(board, filename, units, reportAllTrackErrors)

Runs DRC check and writes results to a report file. Parameters:
  • board (BOARD): Board to check
  • filename (str): Output report path
  • units (EDA_UNITS): Units for report
  • reportAllTrackErrors (bool): Report all errors or just first per track
Returns: True if successful

BOARD Class

The BOARD class represents a PCB design.

Common Methods

board = pcbnew.GetBoard()

# Get board properties
board.GetFileName()
board.GetCopperLayerCount()

# Access board items
board.GetDrawings()  # Get all drawing items
board.GetFootprints()  # Get all footprints
board.GetTracks()  # Get all tracks

# Iterate through drawings
for drawing in board.GetDrawings():
    if drawing.GetClass() == 'PTEXT':
        print(drawing.GetText())

Layer Constants

Common layer identifiers:
pcbnew.F_Cu        # Front copper
pcbnew.B_Cu        # Back copper
pcbnew.F_SilkS     # Front silkscreen
pcbnew.B_SilkS     # Back silkscreen
pcbnew.F_Mask      # Front soldermask
pcbnew.B_Mask      # Back soldermask
pcbnew.F_Paste     # Front paste
pcbnew.B_Paste     # Back paste
pcbnew.Edge_Cuts   # Board outline
pcbnew.Dwgs_User   # User drawings
pcbnew.Cmts_User   # User comments
pcbnew.In1_Cu      # Inner layer 1
# ... additional inner layers

Plot Format Constants

pcbnew.PLOT_FORMAT_GERBER
pcbnew.PLOT_FORMAT_PDF
pcbnew.PLOT_FORMAT_SVG
pcbnew.PLOT_FORMAT_DXF
pcbnew.PLOT_FORMAT_HPGL
pcbnew.PLOT_FORMAT_POST

Complete Example: Board Export

import pcbnew
import sys

# Load board
board = pcbnew.LoadBoard(sys.argv[1])

# Set up plot controller
pctl = pcbnew.PLOT_CONTROLLER(board)
popt = pctl.GetPlotOptions()

popt.SetOutputDirectory("output/")
popt.SetPlotFrameRef(False)
popt.SetAutoScale(False)
popt.SetScale(1)
popt.SetMirror(False)
popt.SetUseGerberAttributes(True)
popt.SetUseAuxOrigin(True)

# Define layers to plot
layers = [
    ("F_Cu", pcbnew.F_Cu, "Top copper"),
    ("B_Cu", pcbnew.B_Cu, "Bottom copper"),
    ("F_Mask", pcbnew.F_Mask, "Top soldermask"),
    ("B_Mask", pcbnew.B_Mask, "Bottom soldermask"),
    ("Edge_Cuts", pcbnew.Edge_Cuts, "Board outline"),
]

# Plot each layer
for layer_name, layer_id, description in layers:
    pctl.SetLayer(layer_id)
    pctl.OpenPlotfile(layer_name, pcbnew.PLOT_FORMAT_GERBER, description)
    pctl.PlotLayer()

pctl.ClosePlot()

# Generate drill files
drlwriter = pcbnew.EXCELLON_WRITER(board)
drlwriter.SetMapFileFormat(pcbnew.PLOT_FORMAT_PDF)
drlwriter.SetFormat(True)  # Metric format

drlwriter.SetOptions(False, False, pcbnew.VECTOR2I(0, 0), False)
drlwriter.CreateDrillandMapFilesSet(popt.GetOutputDirectory(), True, True)

print("Export complete!")

See Also

Build docs developers (and LLMs) love