Hi @isocam .
How about something like this?
import adsk.core, adsk.fusion, traceback
def walkThrough(bom):
def spacePadRight(value, length):
pad = ''
if type(value) is str:
paddingLength = length - len(value) + 1
else:
paddingLength = length - value + 1
while paddingLength > 0:
pad += ' '
paddingLength -= 1
return str(value) + pad
def getInfo(item) -> str:
return ''.join([
spacePadRight(item['instances'], 15),
spacePadRight(item['name'], 25),
spacePadRight(item['description'], 25),
spacePadRight(item['folderName'], 15),
])
infos = [getInfo(item) for item in bom]
return '\n'.join(infos)
def hasTargetFolder(
targetName: str,
doc: adsk.fusion.FusionDocument) -> bool:
df: adsk.core.DataFolder = doc.dataFile.parentFolder
folderNames = []
while True:
if df.isRoot:
break
if not df.parentFolder:
break
folderNames.append(df.name)
df = df.parentFolder
if targetName in folderNames:
return True
return False
def writeFile_Desktop(filename, txt):
import os
desktop_dir = os.path.expanduser('~/Desktop')
import pathlib
path = pathlib.Path(desktop_dir, filename)
with open(path, mode='w') as f:
f.write(txt)
def run(context):
ui = None
targetFolderName = 'PurchasedParts'
try:
app = adsk.core.Application.get()
ui = app.userInterface
product = app.activeProduct
design = adsk.fusion.Design.cast(product)
title = 'Extract BOM'
if not design:
ui.messageBox('No active design', title)
return
root = design.rootComponent
occs = root.allOccurrences
bom = []
for occ in occs:
comp = occ.component
jj = 0
for bomI in bom:
if bomI['component'] == comp:
bomI['instances'] += 1
break
jj += 1
if jj == len(bom):
bodies = comp.bRepBodies
doc = comp.parentDesign.parentDocument
if hasTargetFolder(targetFolderName, doc):
folderName = targetFolderName
else:
folderName = ''
bom.append({
'instances': 1,
'component': comp,
'name': comp.name,
'description': comp.description,
'folderName': folderName,
})
msg = walkThrough(bom)
writeFile_Desktop(f'{root.name}.txt', msg)
ui.messageBox('Done')
except:
if ui:
ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))