I'm packaging a python application with "pyinstaller --onefile myapp.py" which creates a single executable file, and the application works great. Now I would like to be able to import a module from the system if it exists, and otherwise use the bundled module from the single executable file. I'm specifically wanting to import PySide2 from the system if it's installed, and ideally with a configurable flag that indicates if the application should load from the system or from the single executable. I'm already using a configuration file that is read by the single executable, so I could put a flag in there to indicate how to load the module. Is there a way to accomplish this?
The pseudo code would be something like this:
read import_external from configuration file
if import_external is true:
try:
import PySide2 from system
except:
import PySide2 from executable
EDIT I'm getting close to the solution. I can import a single Python file dynamically from a pyinstaller onefile executable, as in the below code where I created a dummy "PySide2.py" file with a simple print statement to validate it imported.
import os
print("Import test")
if os.path.isfile('./PySide2.py'):
print('Importing local PySide2')
import importlib
import importlib.util
spec = importlib.util.spec_from_file_location('PySide2', './PySide2.py')
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
else:
print('Importing system PySide2')
import PySide2
print(PySide2.__version__)
print("Import complete")
But PySide2 is not a single file, so now I need to understand how to import from a directory. Any advice is appreciated!
EDIT 2 I found the solution here: Python use importlib to import a module from a package directory