Bundling External Files with PyInstaller through --onefile
When attempting to create a single-file executable (.exe) using PyInstaller's --onefile option, users may encounter difficulties incorporating external files, such as images or icons. While this option produces a convenient, portable application, it often fails to locate additional files that contribute to the application's functionality.
To resolve this issue, previous versions of PyInstaller relied on setting an environment variable to specify the location of additional files. However, recent updates to PyInstaller have changed this approach. The current method for accessing external files in --onefile mode is through the sys._MEIPASS variable.
The following code demonstrates how to access external files using the updated approach:
import sys def resource_path(relative_path): """ Get absolute path to resource, works for dev and for PyInstaller """ try: # PyInstaller creates a temp folder and stores path in _MEIPASS base_path = sys._MEIPASS except Exception: base_path = os.path.abspath(".") return os.path.join(base_path, relative_path)
By invoking this function with the relative path to the external file, you can obtain its absolute path, regardless of whether you are running the application from a development environment or a PyInstaller-generated executable.
The above is the detailed content of How Can I Access External Files in a PyInstaller --onefile Executable?. For more information, please follow other related articles on the PHP Chinese website!