Introduction
Pyinstaller packages pythin applications and its dependencies into a stand-lone executables.
Pyinstaller can be used across platforms. However, the bundled executable can only be used under the environment it be created. i.e. If you want to create .exe file you need to run pyinstaller under Windows environment.
Installation
Pyinstaller can be installed through pip:
pip install pyinstallerRequirements:
-
Python:
- 2.7 or 3.5-3.7
-
Windows:
- Windows XP or newer
-
Mac OS:
- Mac OS X 10.7(Lion) or newer
Getting Started
Go to your program's directory and run:
pyinstaller pythonScriptName.pyBy default, a folder with all dependencies and executables will be created in a subdirectory called dist.
Bundling to a single executable
pyinstaller -F pythonScriptName.pyor
pyinstaller --onefile pythonScriptName.pyStartup time of the single executable is longer than the folder.
Questions
Relative path issue
When file is executed under environment without python or other environments instead of the local machine, the icon is usually not displayed correctly. It is because the file path the executable use has changed.
Solutions:
-
Using absolute file path
-
Freeze file path
import os import sys config_name = 'myapp.cfg' def app_path(): #return the base application path if getattr(sys, 'frozen', False): return os.path.dirname(sys.executable) elif __file__: return os.path.dirname(__file__) config_path = os.path.join(application_path, config_name)app_path() return the execute path of the application.
Size of executable is too large
-
Use
from ... import ...instead ofimportThe whole package will be bundled if using
import. Bundled the APIs that you only need. -
Pipenv
When using Anaconda, as Anaconda has lots of built-in libraries, it will bundle many unnecessary modules. To get rid of them, we can use a clean environment and here I choose pipenv.
Pipenv is a tool to create and manages a virtualenv for the projects.
Install pipenv
pip install pipenvGo to the directory of our project to create a virtual environment.
pipenv installActivate the project's virtualenv
pipenv shellInstall the necessary dependencies
pip install pyinstaller ...Bundle under this virtual environment
pyinstaller pythonScriptName.pyTo delete the virtual environment, go to the project's directory and run
pipenv --rm