【问题标题】:PyInstaller does not identify relative pathPyInstaller 不识别相对路径
【发布时间】:2021-05-24 04:32:29
【问题描述】:

我正在尝试为我的 python 应用程序生成一个 .exe。在代码中,我导入了一些嵌入文件,如下所示:

f = open('source/store/data_dictionary.json')

尝试从生成的 .exe 运行应用程序,我收到如下错误:

FileNotFoundError: [Errno 2] No such file or directory: 'source/store/data_dictionary.json'

full output error from the console

为了生成 .exe,我运行了:

pyinstaller --onefile app.py

我不知道是否有更好的方法可以在 python 脚本中导入文件以生成可执行文件,或者我是否必须编写一些设置。

你可以在这里查看我的源代码:https://github.com/GraphFilter/GraphFilter

【问题讨论】:

  • 删除 dist 文件夹并运行你剪切你的 exe 并将其粘贴到应该代码所在的位置
  • 它可以工作,但问题是我不想共享这个文件夹。我打算部署它,我希望用户拥有的只是 .exe(和捆绑的文件)。还有一些我在相对路径中调用的图像。有没有办法告诉 PyInstaller 不要捆绑这个图像和信息文件并重做相对路径?
  • 然后,如果您希望它在 dist 文件夹中工作,则必须更改脚本的路径 f = open('source/store/data_dictionary.json') 您必须提供 C:/ 目录中的路径才能使其工作
  • 所以你想在你的onefile exe中嵌入一些数据文件?您必须将数据文件添加到 exe 中的特定路径中,并修改您的代码,以便当它从 onefile exe 运行时,它使用不同的方式来查找文件 - 阅读文档pyinstaller.readthedocs.io/en/stable/…
  • 在此处查看 Jonathon Reiner 的答案以获得有用的功能 resource_path(),这将允许您访问文件,无论是从 ee 还是从源运行 stackoverflow.com/questions/7674790/… -注意使用 @987654330 通常是个坏主意@ 而这个函数避免了这种情况。

标签: python pyinstaller executable relative-path


【解决方案1】:

查看源代码后,我注意到路径是相对于文件app.py 的位置。因此,只要创建可执行文件后该相对路径相同。 IE。如果你把它做成一个包,其中 exe 与app.py 在同一个地方。那么无论该捆绑包在哪里,以下内容都应该有效

为此,您可以使用以下代码在运行时获取 exe 文件的目录,并使用它来获取您的相关文件

import os

cur_dir = os.path.dirname(__file__) # print this to see what it looks like
             # something like: 'c:/path/to/file'

# then using an f-string to get the absolute path of the required files
f = open(f'{cur_dir}/source/store/data_dictionary.json') # essentially 'c:/path/to/file/source/store....'

编辑:(未测试,但您也可以更改工作目录并使用与以前相同的代码)

import os

cur_dir = os.path.dirname(__file__)
os.chdir(cur_dir) # change working directory

# print os.cwd() to see the current working directory, it should be the path to the file

#then proceed as before
f = open('source/store/data_dictionary.json')
.
.
.

【讨论】:

  • 问题是我只想分发可执行文件。但是根据您的回答,我认为我还必须分发图像和此 json 文件等资源。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-04
  • 2016-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多