NX Journal Text output of child part attributes

2019/12/08 categories:NX Journal| tags:NX Journal|Python|

I created a program that outputs the attributes of child parts as text.

Rewrite “attribute_id”, “attribute_name”, and “attribute_material” according to your environment. The result is saved as comma separated text in the “filename” location.

Python Code

import NXOpen

filename = "D:/tree.txt"
dict_attr = { "attribute_id":"ID", "attribute_name":"Name", "attribute_material":"Material" }
titles = ["Rank", "Suppression", "ID", "Name", "Material"]

def main():
    theSession  = NXOpen.Session.GetSession()
    workPart = theSession.Parts.Work
    theComponent = workPart.ComponentAssembly.RootComponent
    rank1 = 0

    # Get attributes of assembly top
    dicts1 = [ componentToDict( theComponent, rank1 ) ]

    # Recursively get the attributes of child parts
    recursion( theComponent, rank1 + 1, dicts1 )

    # Output title as text
    with open(filename, mode='a') as f:
        f.write( ','.join(titles) )

    # Output the acquisition result as text
    attributes1 = [ dictToText(dict1) for dict1 in dicts1 ]
    with open(filename, mode='a') as f:
        f.write( '\n'.join(attributes1) )

def recursion( component1, rank2, dicts2 ):
    for child1 in component1.GetChildren():
        dicts2.append( componentToDict( child1, rank2 ) )
        recursion( child1, rank2 + 1, dicts2 )

def componentToDict( component2, rank3 ):
    attributes2 = { dict_attr[key] : component2.GetStringAttribute(key) for key in dict_attr }
    attributes2["Rank"] = str(rank3)
    attributes2["Suppression"] = str(component2.IsSuppressed)
    return attributes2

def dictToText( dict2 ):
    return ','.join( [ dict2[key] for key in titles ] )

if __name__ == '__main__':
    main()

Share post

Related Posts

コメント