【问题标题】:importlib cannot find module after compling using Pyinstaller使用 Pyinstaller 编译后 importlib 找不到模块
【发布时间】:2016-03-04 20:14:42
【问题描述】:

我有一个使用 importlib 从另一个脚本 (sub_script.py) 导入模块的主脚本。我还将参数传递给另一个脚本:

import importlib
parser = argparse.ArgumentParser(add_help=False)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-option1', action = "store_true")

args = parser.parse_known_args()   

if args[0].option1:
    function = importlib.import_module('sub_script')
    function.main(namespace = args[1])

虽然此代码本身运行良好(使用 Python main_script.py),但在我使用 Pyinstaller 编译后它返回以下错误消息:

Traceback (most recent call last):
  File "<string>", line 33, in <module>
ImportError: No module named sub_script
main_script returned -1

我尝试过:

1) 在我的文件夹下添加__init__.py

或 2) 将 sub_script.py 移动到带有__init__.py 的子文件夹 但要么工作。

我也尝试在 Ubuntu 下编译它,但得到了相同的消息。

但是,如果我只使用 import,它就可以正常运行:

import sub_script

有什么想法吗?谢谢!

【问题讨论】:

    标签: python pyinstaller python-importlib


    【解决方案1】:

    pyinstaller 无法自动打包动态导入的模块。如果你真的需要使用importlib来导入模块,那么你需要告诉pyinstaller。您可以为此使用 --hidden-import 选项:

    --hidden-import MODULENAME, --hiddenimport MODULENAME
        Name an import not visible in the code of the script(s). This option can be used multiple times.
    

    详情请见PyInstaller Docs

    【讨论】:

      最近更新 更多