pygame - 为什么我的 pyinstaller 可执行文件不能访问数据文件?
问题描述
我一直在阅读数十篇文章,包括 pyinstaller 文档,但无法弄清楚为什么我的 pyinstaller 可执行文件不断返回pygame.error: Couldn't open data/items/switch.png
。
switch.png
是脚本应该加载的许多图像中的第一个。
我pyinstaller --add-data 'data:data' snake.py
从我的应用程序的根目录运行。这个director中唯一的东西是snake.py
包含data
图像data
和音乐文件的子文件夹。
snake.spec
显示datas=[('data', 'data')],
我觉得合适的。
我也用--onefile
修饰符试过这个,但每次仍然得到同样的错误。
更新:
我已验证文件在捆绑包中。我--onedir
用来解决这个问题,目录中的目录结构'Dist'
反映了我的本机结构。已使用--add-data="data:data"
,主 .py 文件旁边有一个“数据”文件夹,其中包含一个数据文件'database.xlsx'
和剩余数据文件的子目录。我收到以下消息,表明系统无法访问第一个数据文件:
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
File "cronga.py", line 559, in <module>
File "pandas/io/excel/_base.py", line 304, in read_excel
File "pandas/io/excel/_base.py", line 824, in __init__
File "pandas/io/excel/_xlrd.py", line 21, in __init__
File "pandas/io/excel/_base.py", line 353, in __init__
File "pandas/io/excel/_xlrd.py", line 36, in load_workbook
File "xlrd/__init__.py", line 111, in open_workbook
FileNotFoundError: [Errno 2] No such file or directory: 'data/database.xlsx'
[11168] Failed to execute script cronga
logout
Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.
解决方案
您的 .spec 文件是什么样的?这是有关添加数据文件的 PyInstaller 文档。
基本上你需要添加类似的东西:
a = Analysis(...
datas=[ ('the.wav', '.') ],
...
)
这会将您的声音文件('the.wav')放入已编译应用程序的根目录(第二个参数,'.')。从您的问题来看,您似乎想要复制整个数据目录。问题在于这些文件的相对路径。
然后在您的应用程序中,您可以检查您是从源代码运行还是作为已编译的可执行文件运行。我使用一个辅助函数:
def my_path(path_name):
"""Return the appropriate path for data files based on execution context"""
if getattr( sys, 'frozen', False ):
# running in a bundle
return(os.path.join(sys._MEIPASS, path_name))
else:
# running live
return path_name
因此,您的应用程序代码将如下所示:
the_sound = pygame.mixer.Sound(my_path("the.wav"))
在尝试调试可执行文件时,它可以帮助打开命令行并从那里运行可执行文件,如果您已经创建了控制台应用程序,那么您可能仍然会看到发生的回溯。
推荐阅读
- ios - 如何让 UICollectionView 连续水平滚动而不是创建第二行?
- google-bigquery - 谷歌大查询与 PowerBI 错误连接
- javascript - 复选框 ng-model 问题
- r - 使用 Nginx 上的 R Shiny 服务器将无扩展名 URL 重写为 .Rmd
- java - 两个表的组合填充距离D算法
- javascript - 如果另一个元素设置为显示,如何选择元素:flex; 用 JS
- date - 如果我想编写一个序言谓词来比较两个时期(日期)并查看两个时期是否重叠......例如:
- java - 需要在循环中执行 SQL 查询的替代方法
- windows - 如何在 Inno Setup 中执行此操作?
- c# - ASP.NET OAuth 微软单租户登录