首页 > 解决方案 > 为什么我的 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.

标签: pygamecondapyinstaller

解决方案


您的 .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"))

在尝试调试可执行文件时,它可以帮助打开命令行并从那里运行可执行文件,如果您已经创建了控制台应用程序,那么您可能仍然会看到发生的回溯。


推荐阅读