[PYTHON] Dynamically import modules at runtime with .exe hardened with pyinstaller --onefile

Although it is not recommended by Python official, when passing the artifact to a person, put the following * config.py * in the same hierarchy as * main.py *, import it with * mian.py * and use it as it is I had something to do.

config.py


width = 10
height = 10
count = 100
threshold = 50

main.py


from config import *

I wanted to dynamically import external parameters from the .exe that was hardened with pyinstaller this time, but I was addicted to it, so make a note of the TIPS.

First of all, this article was very helpful. (Reference) https://ja.coder.work/so/python/1422895

Normally, .exe is dynamically imported by using importlib, but if you fix it with * --onefile *, it seems that config.py is also taken in and hard-coded. This problem was dealt with by deleting * config.py * when converting it to .exe (although it is a muddy method). (Probably the correct procedure is to edit the .spec file using * --hidden-import * or something like ...)

The rest is in * main.py *

main.py


import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '.'))

config = importlib.import_module('config')

width = config.width
height = config.height
count = config.count
threshold = config.threshold

If you add the current directory to the path and then import it, it's OK.

Recommended Posts

Dynamically import modules at runtime with .exe hardened with pyinstaller --onefile
Make Scrapy an exe with Pyinstaller
Automatic update method with python Pyinstaller exe
EXE the application created with PyQt5 with PyInstaller