Python 可执行文件:FileNotFoundError

问题描述 投票:0回答:1

我有一个运行完美的Python脚本。

我尝试使用 pyinstaller 将其转换为 EXE 可执行文件,但它给了我错误 -

FileNotFoundError: [Errno 2] No such file or directory: './image/Some_Name_logos_transparent.png'

这是使用此文件的示例 -

logo_image = Image.open(r'./image/Some_Name_logos_transparent.png')

我不明白 python 脚本如何工作得很好,但 exe 却无法工作。

我知道

os.path.join
命令,但我不知道问题是否出在文件位置,或者在将其转换为可执行文件时是否丢失了某些内容。

python pyinstaller executable
1个回答
2
投票

如果您正在构建单个 EXE 文件并且您要访问的文件包含在其中,您可以尝试以下操作:

import sys, os
actual_path = os.path.join(sys._MEIPASS, original_relative_path)

执行时,exe 存档中的所有文件都会解压缩到临时文件夹中。

sys._MEIPASS
指向该目录。

另请参阅此处:使用 PyInstaller 捆绑数据文件(--onefile)

如果是不同的文件,请尝试使用完整路径。

编辑:

这里是一个在正常执行和exe文件中运行的代码片段:

def translate_path(file):
    """ Get absolute path to resource, works for dev and for PyInstaller """
    if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
        # PyInstaller creates a temp folder and stores path in _MEIPASS
        file_path = os.path.join(sys._MEIPASS, file)
    else:
        file_path = os.path.abspath(file)

    return file_path

PyInstaller 文档还提供了有关该主题的更多信息:https://pyinstaller.org/en/stable/runtime-information.html

© www.soinside.com 2019 - 2024. All rights reserved.