Skip to content

Instantly share code, notes, and snippets.

@piratecarrot
Created February 29, 2024 23:30
Show Gist options
  • Save piratecarrot/680c1722d3504d880210f132c8c7814f to your computer and use it in GitHub Desktop.
Save piratecarrot/680c1722d3504d880210f132c8c7814f to your computer and use it in GitHub Desktop.
Replace tags in KiCAD files
#!/usr/bin/env python
import glob, os
import tomllib
data = {}
for file in glob.glob("build/env.d/*.env"):
with open(file, "rb") as f:
for k, v in tomllib.load(f).items():
data[k] = v
import sexpdata
from sexpdata import Symbol
import re
variable_regex = re.compile(r'^\${([a-zA-Z][a-zA-Z0-9]*)}$', flags = re.MULTILINE)
with open('pcbfile.kicad_pcb', 'r', encoding='utf-8') as file_input:
sexp = sexpdata.load(file_input)
for i in [i for i in sexp if Symbol('footprint') in i and 'Tags:Text' in i]:
for j in [j for j in i if type(j) == list and Symbol('fp_text') in j]:
for k in range(len(j)):
if type(j[k]) == str and j[k].startswith('$'):
variable_name = variable_regex.findall(j[k])
if len(variable_name) > 0 and variable_name[0] in data.keys():
j[k] = data[variable_name[0]]
with open('pcbfile_new.kicad_pcb', 'w', encoding='utf-8') as file_output:
sexpdata.dump(sexp, file_output)
file_output.close()
# The easier to read perhaps but not as satisfying way
# for i in sexp:
# if Symbol('footprint') in i and 'Tags:Text' in i:
# for j in i:
# if type(j) == list and Symbol('fp_text') in j:
# for k in range(len(j)):
# if type(j[k]) == str and j[k].startswith('$'):
# j[k] = 'TEST'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment