ntg
ntg

Reputation: 14085

pyinstaller importing/loading at runtime python code e.g. config.py

I have a large project that has a large 'config.py' file and is turned into an executable with pyinstaller. Is it possible to compile the whole project, but leave / re-load / import this file at run time, and how?

(I could move part of the contents to a json format, and alter the file's logic, then load the json file, but do not want to plus, its a big file that everyone has his own copy already...)

a small part of what is in 'config.py' is:

import getpass
username = getpass.getuser()
data_files_dir = '/tmp/data'
bindings = 'UC'
if username.lower()=='nick':
   data_files_dir = '/tmp/data'
   ....
....

The only relevant question I found is this one, but it seems to be asking for something much more extensive, plus the answer ('You are missing the point. Your script supposes to be an end product.') definitely does not fit my case...

Upvotes: 3

Views: 1198

Answers (1)

Marsh
Marsh

Reputation: 76

ntg;

The best solution I've found to use with PyInstaller is the Python 3.4 importlib module class SourceFileLoader to load configuration information at runtime. Here's a sample.

File: ./conf.py

"""
Configuration options
"""
OPT1='1'
OPT2='Option #2'
OPT3='The Lumberjack is ok'
OPT4='White over White. Have a nice flight'

Next here's a sample script that will import the conf information at runtime.

File: myapp.py

#!/usr/bin/python3
"""
The Application.
"""
import sys
from importlib.machinery import SourceFileLoader
# load your config file here
conf = SourceFileLoader( 'conf', './conf.py' ).load_module()

print("Option 1:", conf.OPT1)
print("Option 2:", conf.OPT2)
print("Option 3:", conf.OPT3)
print("Option 4:", conf.OPT4)

Note that the options from conf.py are imported into the "conf" namespace. You will need to prefix each reference to a conf item with "conf.". There may be other methods.

Upvotes: 6

Related Questions