pyinstalleramplpy

Compiling AMPL with Pyinstaller


I am wondering if it is possible, or if anyone has any experience with, compiling the amplpy optimization package with pyinstaller into an exe. The amplpy package github page is here

As a test case, I simply have a python file called main.py, containing the following code

from amplpy import AMPL, modules
modules.activate("my-licence-code")

I tested it on a window 10 computer and can be run successfully.

However, after compiling the file with Pyinstaller, the .exe file can be generated, but it cannot be run successfully. After running the exe file, the terminal outputs

Traceback (most recent call last):
  File "playground.py", line 44, in <module>
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "PyInstaller\loader\pyimod02_importers.py", line 391, in exec_module
  File "amplpy\__init__.py", line 6, in <module>
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "PyInstaller\loader\pyimod02_importers.py", line 391, in exec_module
  File "amplpy\outputhandler.py", line 2, in <module>
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "PyInstaller\loader\pyimod02_importers.py", line 391, in exec_module
  File "amplpy\amplpython\__init__.py", line 22, in <module>
  File "amplpy\amplpython\__init__.py", line 18, in <module>
IndexError: list index out of range

I know this error stems from the program cannot find the corresponding .dll file, but even I manually change the .dll file location to where the .exe located, there are more error coming up, and the situation got more complex. Which means there may be some better way to solve the compiling promblem with pyinstaller and amplpy.

Any suggestions with this problem would be much appreciated. Thank you.


Solution

  • Since amplpy v0.13.1 (you can upgrade with python -m pip install amplpy>=0.13.1 --upgrade), there is now a bundle command available that uses pyinstaller to generated distributable bundles (see, e.g., https://dev.ampl.com/ampl/python/pyinstaller.html).

    You can generate a distributable bundle for that script with:

    python -m amplpy.bundle script_name.py
    

    Note: on Windows the latest version of pyinstaller does not seem to be working correctly at the moment. Using v5.1 it is working without issues (you can install that version with python -m pip install pyinstaller==5.1 --upgrade)