pyinstaller importing/loading 在运行时 python 代码例如config.py

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

我有一个大型项目,其中包含一个大型 'config.py' 文件,并使用 pyinstaller 将其转换为可执行文件。是否可以编译整个项目,但在 运行 时保留/重新加载/导入此文件,如何?

(我可以将部分内容移动到 json 格式,并改变文件的逻辑,然后加载 json 文件,但不想加上,它是一个大文件每个人都有自己的副本...)

'config.py'中的一小部分是:

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

我发现的唯一相关问题是 this one,但它似乎要求更广泛的东西,加上答案 ('You are missing the point. Your script supposes to be an end product.') 绝对不适合我的情况...

ntg;

我发现与 PyInstaller 一起使用的最佳解决方案是 Python 3.4 importlib 模块 class SourceFileLoader 在运行时加载配置信息。这是一个示例。

文件:./conf.py

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

接下来是一个示例脚本,它将在运行时导入 conf 信息。

文件: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)

请注意,conf.py 中的选项已导入到 "conf" 命名空间中。您需要在每个对 conf 项的引用前加上 "conf."。可能还有其他方法。