Reading Autodesk Inventor dialogs with Python

88 Views Asked by At

I am working on a project with a lot of .iam (Inventor Assembly) files. Sometimes these files are missing, causing the following dialog to show up when I try to open files that use this assembly:

Resolve link dialog

I am trying to create a python program that will create a COM object with Autodesk Inventor, open the file in question, and check that all the assemblies it uses are present. I want to do this by detecting if Inventor throws an error after trying to open the file.

Here is my code so far:

import win32com.client
from win32com.client import gencache
import time
import threading
import pythoncom
from tqdm import tqdm

WAITTIME = 5


def check_file(id, result, verbose, done):
    pythoncom.CoInitialize()
    oApp = win32com.client.Dispatch(
        pythoncom.CoGetInterfaceAndReleaseStream(id, pythoncom.IID_IDispatch)
    )

    manager = oApp.ErrorManager

    if verbose:
        with tqdm(total=WAITTIME, desc="Waiting") as pbar:
            for i in range(WAITTIME):
                if done[0]:
                    result[0] = False
                    oApp.Quit()
                    return
                pbar.update(1)
                time.sleep(1)
    else:
        for i in range(WAITTIME):
            if done[0]:
                result[0] = False
                oApp.Quit()
                return
            time.sleep(1)

    try:
        result[0] = manager.IsMessageSectionActive
        oApp.Quit()
    except:
        pass


def file_is_broken(link, verbose=False):
    oApp = win32com.client.Dispatch('Inventor.Application')  # get COM object
    oApp_id = pythoncom.CoMarshalInterThreadInterfaceInStream(pythoncom.IID_IDispatch, oApp)
    mod = gencache.EnsureModule('{D98A091D-3A0F-4C3E-B36E-61F62068D488}', 0, 1, 0)  # Loads python support
    oApp = mod.Application(oApp)

    result = [None]
    done = [False]
    thread = threading.Thread(target=check_file, args=(oApp_id, result, verbose, done,))
    thread.start()

    try:
        oApp.Documents.Open(link)
        done[0] = True
        thread.join()
    except:
        pass

    return result[0]


if __name__ == "__main__":
    print(file_is_broken("<FILE PATH>", True))

What I am doing is creating the COM object, opening the file from its path, waiting a couple seconds, and then checking to see if there is an error present in another thread while the document is opening. This works, however it is not exact because there can be different errors and I only want to check if the "Resolve Link" error is present so I can determine that the file has broken links.

Is there a way for me to read the contents of the dialog through the Inventor API COM object, so I can get more information about the error that is present?

0

There are 0 best solutions below