Search code examples
pythonimportpyinstallerpython-import

How to import the package being frozen in the PyInstaller spec file?


I have this directory structure:

mypackage/
|___ installer.spec
|___ package/
    |___ __init__.py

and package.__init__.py contains some variables I'd like to use in my installer.spec file. So this file contains a import package line. However, running pyinstaller installer.spec in mypackage/ fails with a ModuleNotFoundError.

How can I retrieve variables from the package I want to freeze while freezing it with PyInstaller?


Solution

  • In the spec file, change

    import package
    
    foobar = package.foobar
    

    to

    import importlib.util
    
    spec = importlib.util.spec_from_file_location(
        "package", "/full/path/to/package/__init__.py"
    )
    package = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(package)
    foobar = package.foobar
    

    Reference: How to import a module given the full path?