Search code examples
pythonpyinstallerwin32comautodesk-inventorpythoncom

Using Autodesk Inventor COM object through Python with PyInstaller


Hello everyone and happy fourth to my friends in America.

I am working on a python script which is meant to create an instance of Inventor, and open an assembly file through the COM object. I am aware that using Python with the Inventor API is not the best way to go about it, but it's what I have available to me. This script works fine when I run it normally, but when I make it into a binary with PyInstaller I get the following error during runtime:

Traceback (most recent call last):
  File "<path>\main.py", line 49, in <module>
    commands[vars(options)['command']](vars(options))
  File "actions\createbatch.py", line 20, in run_create_batch_command
  File "actions\createbatch.py", line 31, in create_batch_with_references
  File "inventor.py", line 37, in open_doc_with_thread
  File "win32com\client\__init__.py", line 585, in __getattr__
  File "win32com\client\__init__.py", line 574, in _ApplyTypes_
  File "win32com\client\dynamic.py", line 638, in __getattr__
AttributeError: Inventor.Application.InvokeTypes
[45208] Failed to execute script 'main' due to unhandled exception!

After looking into the error, I have traced it to line 10 in the following code:

try:
    oApp = win32com.client.Dispatch('Inventor.Application')  # get COM object
except pythoncom.com_error:
    raise AppNotFoundError()

mod = gencache.EnsureModule('{D98A091D-3A0F-4C3E-B36E-61F62068D488}', 0, 1, 0)  # Loads python support
oApp = mod.Application(oApp)

try:
    oApp.Documents.Open(path_to_file)
except pythoncom.com_error:
    pass  # throws error when app is closed before document can open

I originally thought it had something to do with gencache.EnsureModule not being able to load the python support because it was bundled, but I'm pretty sure I ruled this out. I've tried using different versions of PyInstaller, different versions of Python, and even building the code on a different machine. Nothing has worked.

What can I do to resolve this error?


Solution

  • After many hours of struggle and self-doubt I have solved the problem- I'm not sure why this works, but by accessing the COM object in another thread via pythoncom.CoMarshalInterThreadInterfaceInStream, and then calling oApp.Documents.Open(path_to_file) in this thread it works.