代码之家  ›  专栏  ›  技术社区  ›  Antas Sharma

Python可执行文件:FileNotFoundError

  •  1
  • Antas Sharma  · 技术社区  · 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 命令,但我不知道是文件的位置有问题,还是在将其转换为可执行文件时丢失了什么。

    编辑 -好吧,我忘了把图片放在代码中给出的目录中。我的朋友做了这个脚本,他束手无策,因为他无法将脚本编译成exe,所以我试图帮助他。

    但是,我想我本可以很容易地从错误中找出答案。

    无论如何,这些答案似乎对调试非常有用,所以我考虑不删除它(也是因为我认为我实际上无法删除它)

    我很抱歉浪费了人们的时间。

    1 回复  |  直到 1 年前
        1
  •  3
  •   Raphael    1 年前

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

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

    执行时,exe存档中的所有文件都会解压缩到临时文件夹中。 sys._MEIPASS 指向该目录。

    另请参见此处: Bundling data files with 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