Preloader
Others
  • Estimated reading time: 10 Minutes

How to Automate PCB Design Checks with Python

How to Automate PCB Design Checks with Python

You've finished routing a PCB, cleared the design rule checker, and exported the manufacturing files. Everything looks ready until your fabrication partner emails asking for the missing drill data. Or the assembly team discovers that a component marked DNP in the bill of materials still appears in the placement file.

Neither problem requires sophisticated electrical analysis to detect. They're documentation mistakes, and many can be caught automatically.

Python is useful here because PCB manufacturing packages contain a mixture of files that can be checked before an engineer spends time inspecting the actual design.

We can build a small command-line tool that verifies a release package, compares assembly references, and reports errors. It won't replace a PCB CAD application's DRC engine, but it can eliminate an entire category of preventable handoff problems.

What Should the Script Actually Check?

PCB design verification and manufacturing-file verification are related, but they aren't the same task.

A PCB design rule check (DRC) examines constraints inside the design database. It can identify trace spacing violations, clearance problems, and certain connectivity issues.

Once a project has been exported, another question becomes important: Did the correct manufacturing information make it into the release package?

For a typical two-layer board, we'd expect top and bottom copper Gerbers, solder mask files, a board outline, and drill data. Assembly introduces additional documents, particularly the BOM and component placement coordinates.

These files serve different purposes, as explained in this overview of PCB manufacturing files.

Our Python checker will focus on two tasks:

  • Confirm that required manufacturing files exist and aren't empty.
  • Compare BOM population instructions against component placement data.

We'll deliberately avoid attempting to interpret the copper geometry. That requires a proper Gerber parser and knowledge of the intended manufacturing rules.

Start with a Release Manifest

One difficulty with PCB automation is that CAD tools use different naming conventions.

KiCad may export filenames such as controller-F_Cu.gbr, while another tool produces controller.GTL.

Trying to guess every possible naming convention makes the script unnecessarily complicated.

Instead, we'll define the expected files explicitly in a JSON manifest.

Create a directory called pcb-release with this structure:

pcb-release/
├── release.json
├── top.gtl
├── bottom.gbl
├── top_mask.gts
├── bottom_mask.gbs
├── outline.gko
├── plated.drl
├── bom.csv
└── placement.csv

The file names are illustrative. Your actual export can use different names as long as the manifest matches them.

Create release.json:

{
  "required_files": [
    "top.gtl",
    "bottom.gbl",
    "top_mask.gts",
    "bottom_mask.gbs",
    "outline.gko",
    "plated.drl",
    "bom.csv",
    "placement.csv"
  ],
  "assembly": true,
  "bom": "bom.csv",
  "placement": "placement.csv"
}

This arrangement has a useful advantage: the checker doesn't need to know which CAD application generated the files.

For a fabrication-only job, remove the assembly-specific files from required_files and set assembly to false.

For a four-layer design, add the two inner copper Gerbers.

The manifest describes what the project should contain. The Python script verifies whether the exported package matches that description.

Build the Python Checker

We'll use the standard library, so no external Python packages are required.

Create a file named check_pcb.py:

import argparse
import csv
import json
from pathlib import Path


def read_csv(path):
    with path.open(newline='', encoding='utf-8-sig') as stream:
        return list(csv.DictReader(stream))


def main():
    parser = argparse.ArgumentParser(
        description='PCB release package preflight'
    )
    parser.add_argument('folder', type=Path)
    parser.add_argument('--manifest', default='release.json')
    args = parser.parse_args()

    root = args.folder.resolve()

    manifest = json.loads(
        (root / args.manifest).read_text(encoding='utf-8')
    )

    errors = []
    warnings = []

    required = manifest.get('required_files', [])

    # Check expected manufacturing files
    for filename in required:
        candidate = (root / filename).resolve()

        if not candidate.is_relative_to(root):
            errors.append(
                f'Path escapes release folder: {filename}'
            )
        elif not candidate.is_file() or candidate.stat().st_size == 0:
            errors.append(
                f'Missing or empty file: {filename}'
            )

    # Check assembly data when requested
    if manifest.get('assembly'):
        bom_path = (root / manifest['bom']).resolve()
        placement_path = (root / manifest['placement']).resolve()

        if bom_path.is_file() and placement_path.is_file():
            try:
                bom_rows = read_csv(bom_path)
                placement_rows = read_csv(placement_path)

                bom_refs = set()
                fitted_refs = set()

                for row in bom_rows:
                    ref = row['Reference'].strip().upper()

                    if not ref or ref in bom_refs:
                        errors.append(
                            f'Blank or duplicate BOM reference: {ref}'
                        )

                    bom_refs.add(ref)

                    if row['Populate'].strip().lower() in (
                        'yes', 'true', '1'
                    ):
                        fitted_refs.add(ref)

                placed_refs = set()

                for row in placement_rows:
                    ref = row['Reference'].strip().upper()

                    if not ref or ref in placed_refs:
                        errors.append(
                            f'Blank or duplicate placement reference: {ref}'
                        )

                    placed_refs.add(ref)

                    if row['Side'].strip().lower() not in (
                        'top', 'bottom'
                    ):
                        errors.append(f'Invalid board side: {ref}')

                    for field in ('X', 'Y', 'Rotation'):
                        try:
                            float(row[field])
                        except (ValueError, KeyError):
                            errors.append(
                                f'Invalid {field} for {ref}'
                            )

                # Placement file must not include DNP parts
                for ref in sorted(placed_refs - fitted_refs):
                    errors.append(
                        f'Placement not marked fitted in BOM: {ref}'
                    )

                # These may be through-hole or manual parts
                for ref in sorted(fitted_refs - placed_refs):
                    warnings.append(
                        'Fitted BOM part absent from placement '
                        f'(THT/manual?): {ref}'
                    )

            except (KeyError, csv.Error, UnicodeError) as exc:
                errors.append(
                    f'Unable to read assembly CSV: {exc}'
                )

    for item in errors:
        print('ERROR:', item)

    for item in warnings:
        print('WARN:', item)

    print(
        f'{len(errors)} error(s), '
        f'{len(warnings)} warning(s)'
    )

    raise SystemExit(1 if errors else 0)


if __name__ == '__main__':
    main()

This example requires Python 3.9 or later because it uses Path.is_relative_to().

There's no advanced file parsing involved. We simply verify the release structure and check whether assembly data agrees.

That's intentional. A small tool with clearly defined behavior is easier to maintain than one that attempts to make engineering judgments from incomplete data.

Test the Script with Sample Assembly Data

Before running the checker on a real PCB project, create two small CSV files.

For bom.csv:

Reference,Populate
U1,yes
R1,yes
J1,no

And for placement.csv:

Reference,X,Y,Rotation,Side
U1,15.2,20.1,90,Top
R1,11.0,5.2,0,Bottom

Here, J1 is explicitly marked as not populated, so it doesn't appear in the placement file.

Create nonempty placeholder files for the six Gerber and drill filenames listed in release.json. These are sufficient for testing the script's file-presence logic, but they are not valid manufacturing outputs.

Run:

python check_pcb.py ./pcb-release

With the sample files in place, the expected output is:

0 error(s), 0 warning(s)

Now add J1 to placement.csv:

J1,25.0,10.0,0,Top

Run the checker again.

You should see:

ERROR: Placement not marked fitted in BOM: J1
1 error(s), 0 warning(s)

The discrepancy is straightforward: the placement file tells the assembly machine to place a component that the BOM explicitly excludes.

That is exactly the kind of mistake a preflight check should catch.

If a fitted BOM reference is absent from placement data, the script produces a warning instead. This avoids automatically treating every through-hole or manually assembled component as an error.

Understanding the Exit Code

The script finishes with:

raise SystemExit(1 if errors else 0)

This makes it suitable for automated workflows.

An exit code of 0 indicates that no errors were identified. An exit code of 1 indicates that the package failed one or more checks.

Warnings do not cause failure in this implementation.

That behavior can be changed if the project requires stricter assembly documentation.

Why Reference Designators Need Special Attention

Reference Designator

BOM and placement mismatches are common sources of assembly confusion, particularly when designs have multiple revisions.

Suppose an engineer removes a capacitor from a circuit but forgets to regenerate the placement data.

The board may still have the corresponding footprint, and the old placement file may still instruct assembly equipment to populate it.

Our script catches this only if the BOM and placement file disagree.

It cannot determine whether the BOM itself is correct.

That distinction is important because both files could contain the same outdated information.

The correct source of truth remains the approved design revision.

There's another limitation: some BOMs group reference designators into a single cell, such as R1,R2,R3, while our example expects one component reference per row.

Before using the checker with a production export, you'll need to normalize the BOM into the expected format.

Component rotation conventions can also differ between CAD tools and assembly machines. Our script checks whether the rotation value is numeric, not whether the component orientation is electrically or mechanically correct.

Integrating the Checker into a Release Workflow

The real advantage of a command-line validator is repeatability.

Once a project has a defined manufacturing package, the same checks can run every time new output files are generated.

A simple workflow might look like this:

  1. Run ERC and DRC inside the PCB design application.
  2. Export Gerber and drill files from the approved revision.
  3. Generate the BOM and placement data.
  4. Run the Python preflight checker.
  5. Inspect the actual fabrication data with a CAM or Gerber viewer before release.

The fourth step can be automated in a CI pipeline if the project stores manufacturing outputs or generates them during a release job.

For example, a GitHub Actions workflow could invoke the script after the export stage. If the check fails, the release process stops before the manufacturing package is distributed.

For a production system, I'd also recommend creating checksums for the final output files. Recording those checksums alongside the design revision makes it easier to establish exactly which files were issued to a supplier.

What This Script Cannot Tell You

A passing report does not mean the PCB is manufacturable.

It only means the expected files exist and the limited assembly checks passed.

Our code does not inspect Gerber geometry, perform electrical connectivity analysis, or verify the accuracy of drill coordinates.

It also cannot confirm whether trace widths meet a factory's minimum dimensions or whether a particular via structure is compatible with the intended stackup.

Those checks require manufacturing rules and proper interpretation of the design data.

Why Manufacturer Review Still Matters

Consider a design with a 0.15 mm mechanical hole and fine conductor spacing.

A script could verify that the drill file exists, yet still have no understanding of whether the hole size is appropriate for the board thickness or plating requirements.

The selected fabricator must evaluate those details against its actual process limits.

For example, PCBCool, a PCB manufacturer based in China, publishes specifications for its custom board fabrication services. Such specifications provide useful constraints when preparing a release, but individual designs still require appropriate engineering review.

A more advanced automation system could compare extracted design features with a machine-readable capability profile.

That would make the checker more useful without implying that it can replace a manufacturing engineer.

Taking the Checker Further

Once the basic release validation works, the next improvements should address real weaknesses in the workflow.

For instance, checking the layer count against the expected stackup would provide more value than simply counting the number of Gerber files in the folder.

A proper implementation would need to recognize layer functions from reliable metadata or a project manifest.

Another useful extension is parsing BOM variants.

A single PCB design may have several assembly configurations, each with a different set of fitted components. The script could accept a variant name and compare the relevant BOM against its corresponding placement export.

For more advanced file analysis, consider using a dedicated Gerber library rather than writing a parser from scratch.

Gerber files contain structured imaging commands and attributes. Proper interpretation involves considerably more than searching for coordinates in a text file.

The same applies to Excellon drill files, where units, coordinate formats, and tool definitions must be handled correctly.

The safest automation is the kind that knows what it can verify—and refuses to guess about what it cannot.

Final Thoughts

Python makes it straightforward to catch missing manufacturing files and mismatched assembly references before a PCB package leaves the engineering team.

The value isn't in building a complicated tool. It's in making release checks consistent across projects and preventing avoidable documentation mistakes.

Start with a small, reliable validator. Add more detailed checks only when you have the manufacturing data and engineering rules needed to support them.

Related articles
How AI Image Generation Is Changing Everyday Creative Workflows
20 Nov, 2026
  • Estimated reading time: 4 Minutes
How Digital Maps Calculate Distances Between Two Locations
20 Nov, 2026
  • Estimated reading time: 10 Minutes
How AI Is Changing the Way Car Dealerships Prepare Vehicle Photos
20 Nov, 2026
  • Estimated reading time: 4 Minutes
The 5 Best No-Code AI Agent Builders for Customer Service in 2026
20 Nov, 2026
  • Estimated reading time: 6 Minutes
Weekly trending
How AI Image Generation Is Changing Everyday Creative Workflows
20 Nov, 2026
  • Estimated reading time: 4 Minutes
How Digital Maps Calculate Distances Between Two Locations
20 Nov, 2026
  • Estimated reading time: 10 Minutes
How AI Is Changing the Way Car Dealerships Prepare Vehicle Photos
20 Nov, 2026
  • Estimated reading time: 4 Minutes
Our Sponsors

Our blog is proudly supported by industry-leading sponsors.