Python Assistant Prompts: Display Class Names and Property Values


 

Prompt Used:

Can you write a script which reads all ECInstances attached to a selected element 
and prints their class names and property values?

 

 

Python Assistant Generated Code:

from MSPyBentley import *
from MSPyECObjects import *
from MSPyBentleyGeom import *
from MSPyDgnPlatform import *
from MSPyDgnView import *
from MSPyMstnPlatform import *


def print_ecinstances_for_selected_element():
    """
    Reads all ECInstances attached to the first selected element and prints their 
    class names and property values.
    """
    sel_mgr = SelectionSetManager.GetManager()
    n_selected = sel_mgr.NumSelected()
    if n_selected == 0:
        print("No element selected. Please select an element.")
        return

    # Get the first selected element
    eh = ElementHandle()
    sel_mgr.GetElement(0, eh)
    if not eh.IsValid():
        print("Selected element is not valid.")
        return

    # Set up EC query for all ECInstances on the element
    dgnECManager = DgnECManager.GetManager()
    scope_option = FindInstancesScopeOption()
    scope = FindInstancesScope.CreateScope(eh, scope_option)
    query = ECQuery.CreateQuery(ECQueryProcessFlags.eECQUERY_PROCESS_SearchAllIntrinsic)

    # Find ECInstances
    result_tuple = dgnECManager.FindInstances(scope, query)
    if not result_tuple or not result_tuple[0]:
        print("No ECInstances found on the selected element.")
        return

    for instance in result_tuple[0]:
        ec_class = instance.GetClass()
        class_name = ec_class.GetName()
        print(f"ECInstance Class: {class_name}")

        # Print all property values
        properties = ec_class.GetProperties(True)
        for prop in properties:
            prop_name = prop.GetName()
            ec_value = ECValue()
            instance.GetValue(ec_value, str(prop_name))
            print(f"  {prop_name}: {ec_value.ToString()}")
        print("-" * 40)


def main():
    print_ecinstances_for_selected_element()


if __name__ == "__main__":
    main()

 

 

Python: Documentation | API Presentations | FAQs | GitHub | Samples | Wikis | Blogs