Pyinstaller打包的wxPython macOS .app无法打开,路径错误求助
Hey there! Let's fix this file path issue you're having with your wxPython app on macOS. The problem boils down to how os.getcwd() behaves when your app is packaged as a .app bundle—here's a step-by-step solution tailored to your setup:
1. Replace os.getcwd() with a reliable root path finder
When you run the packaged .app, os.getcwd() points to your user's home directory (like /Users/MyAccount) instead of the internal folder where your app's resources live. PyInstaller sets a special variable sys._MEIPASS that points to the temporary directory where it extracts your app's files. We can use this to make a helper function that works both during development and when packaged.
Add this function to either MyApp.py or script.py (whichever you use to access resources first):
import os import sys def get_app_root(): # Check if we're running from a PyInstaller bundle if hasattr(sys, '_MEIPASS'): return sys._MEIPASS # For development: return the directory containing this script # If this is in script.py (inside scripts/), adjust to go up one level: # return os.path.dirname(os.path.dirname(os.path.abspath(__file__))) return os.path.dirname(os.path.abspath(__file__))
Then in script.py, replace any use of os.getcwd() with this function to build your resource paths:
# Get the app's root directory root_path = get_app_root() # Build the full path to your resources folder resources_dir = os.path.join(root_path, 'resources') # Now access your files using this path file1_path = os.path.join(resources_dir, 'file1.json') file2_path = os.path.join(resources_dir, 'file2.txt')
Note: If you put the helper function in script.py (inside the scripts/ folder), uncomment the adjusted return line to jump up one directory to the root.
2. Update your PyInstaller command to include resources
By default, PyInstaller only packages your Python scripts—it doesn't automatically copy the resources folder. Use the --add-data flag to tell it to include those files in the bundle.
For macOS, the --add-data syntax uses a colon (:) to separate the source and destination paths. Run this command from your root folder:
pyinstaller MyApp.py --windowed --add-data "resources:resources"
This copies everything in your resources folder into a matching resources folder inside the packaged app.
3. Verify your script call (if needed)
If MyApp.py imports script.py (like import scripts.script), PyInstaller will automatically include it. But if you're using subprocess to run it as a separate script, adjust that path too with the helper function:
# In MyApp.py, for subprocess calls script_path = os.path.join(get_app_root(), 'scripts', 'script.py') subprocess.run(['python3', script_path])
4. Test the packaged app
Re-package with the updated command, then try opening the .app again. If you still hit issues, run the app directly from the terminal to see detailed error messages:
/Path/To/Your/MyApp.app/Contents/MacOS/MyApp
内容的提问来源于stack exchange,提问作者Adam Zarn

