bom_csv_by_ref_v2.py 1.59 KB
Newer Older
1 2 3 4 5 6
#
# Example python script to generate a BOM from a KiCad generic netlist
#
# Example: Ungrouped (One component per row) CSV output
#

7 8
from __future__ import print_function

9
# Import the KiCad python helper module
10
import kicad_netlist_reader
11 12
import csv
import sys
13

14 15
# Generate an instance of a generic netlist, and load the netlist tree from
# the command line option. If the file doesn't exist, execution will stop
16
net = kicad_netlist_reader.netlist(sys.argv[1])
17 18

# Open a file to write to, if the file cannot be opened output to stdout
19
# instead
20 21 22
try:
    f = open(sys.argv[2], 'w')
except IOError:
23
    print(__file__, ":", e, file=sys.stderr)
24 25 26
    f = stdout

# Create a new csv writer object to use as the output formatter
27
out = csv.writer(f, lineterminator='\n', delimiter=',', quotechar="\"", quoting=csv.QUOTE_ALL)
28

29 30 31 32 33 34 35
# override csv.writer's writerow() to support utf8 encoding:
def writerow( acsvwriter, columns ):
    utf8row = []
    for col in columns:
        utf8row.append( str(col).encode('utf8') )
    acsvwriter.writerow( utf8row )

36 37
components = net.getInterestingComponents()

38
# Output a field delimited header line
39 40 41
writerow( out, ['Source:', net.getSource()] )
writerow( out, ['Date:', net.getDate()] )
writerow( out, ['Tool:', net.getTool()] )
42
writerow( out, ['Component Count:', len(components)] )
43
writerow( out, ['Ref', 'Value', 'Footprint', 'Datasheet', 'Manufacturer', 'Vendor'] )
44 45

# Output all of the component information (One component per row)
46
for c in components:
47
    writerow( out, [c.getRef(), c.getValue(), c.getFootprint(), c.getDatasheet(),
48 49
        c.getField("Manufacturer"), c.getField("Vendor")])