Pyinstaller .app 包无法在 Mac 打开

Pyinstaller .app bundle won't open on Mac

我创建了一个 wxPython GUI 应用程序,我想将其分发到 运行 macOS 上。

首先,这是我的文件夹结构:

root/
├── MyApp.py
|
├── scripts/
|   ├── script.py
|
├── resources/
|   ├── file1.json
|   ├── file2.txt

MyApp.py 文件 运行s script.pyscript.py 引用 resources 文件夹中的文件。

为了创建 .app 包,我使用了 Pyinstaller,如下所示:

cd /path/to/root/folder
pyinstaller MyApp.py --windowed

这会创建一个 .app 文件,但当我尝试打开它时它会立即关闭。

为了调查这个问题,我去了这里:

MyApp.app > Contents > MacOS > MyApp (A Unix executable)

这是来自终端的 运行 应用程序,但我收到此错误:

FileNotFoundError: [Errno 2] No such file or directory: '/Users/MyAccount/resources'

script.py 中,我使用 os.getcwd() 获得了对 root 目录的引用,但是 运行 应用程序在尝试时似乎没有使用此相对路径访问 resources 文件夹。我对此很陌生,所以我不确定我可能哪里出错了,任何帮助将不胜感激!

您可以使用 runtime information 获取代码所在文件夹的路径:

import sys
import os

if getattr(sys, 'frozen', False):
    # this is a Pyinstaller bundle
    root_path = sys._MEIPASS
else:
    # normal python process
    root_path = os.getcwd()

然后,例如,您的 file1.json 冷访问使用:

path_to_file1 = os.path.join(root_path, 'resources', 'file1.json')

但是,如果不在 Pyinstaller 命令行(或 .spec 文件中)指定它们,您的 resources 文件夹中的两个文件可能不会包含在您的应用程序文件夹中:

pyinstaller --windowed --add-data "resources/file1.json:resources" --add-data "resources/file2.txt:resources" MyApp.py

您可以只在 --add-data 选项中指定文件夹,如下所示:

pyinstaller --windowed --add-data "resources:resources" MyApp.py

但我从来没有真正尝试过。