pythonpython-2.7python-3.xpython-2.6pyinstaller

exe-file created by pyinstaller, not find self-defined modules while running


I create two python files, and the directory/file relations is as follows:

mytest---
     |---mycommon.py
     |---myMainDir---
                     |----myMain.py

In mycommon.py:

def myFunc(a):
    ...

And in myMain.py:

import sys
sys.path.append(os.path.join(os.path.dirname(os.path.abspath('__file__')), '..'))
import mycommon.py
mycommon.myFunc("abc")

Then I created exe using pyinstaller:

pyinstall.py -F mytest\myMainDir\myMain.py

MyMain.exe is created, but when run, is tells that can not find mycommon module.


Solution

  • PyInstaller's official manual describes this issue:

    Some Python scripts import modules in ways that PyInstaller cannot detect: for example, by using the __import__() function with variable data, or manipulating the sys.path value at run time. If your script requires files that PyInstaller does not know about, you must help it.

    It also suggests what should be done in such a case:

    If Analysis recognizes that a module is needed, but cannot find that module, it is often because the script is manipulating sys.path. The easiest thing to do in this case is to use the --paths= option to list all the other places that the script might be searching for imports:

    pyi-makespec --paths=/path/to/thisdir --paths=/path/to/otherdir myscript.py

    These paths will be added to the current sys.path during analysis.

    Therefore, please specify the --paths argument while building the application. The manual states that specifying the -p argument is equivalent:

    -p dir_list, --paths=dir_list

    Set the search path(s) for imported modules (like using PYTHONPATH). Use this option to help PyInstaller to search in the right places when your code modifies sys.path for imports. Give one or more paths separated by ; (under Windows) or : (all other platforms), or give the option more than once to give multiple paths to search.