【问题标题】:How to find the file path to an externally used file when the script is compiled as an executable?将脚本编译为可执行文件时,如何找到外部使用文件的文件路径?
【发布时间】:2020-06-13 23:43:11
【问题描述】:

我正在使用 pyinstaller 使用 pyinstaller 中的以下参数将一个非常简单的脚本转换为可执行文件:

pyinstaller -F --add-data "C:\path\to\my_external_file.mp3;." --onefile "C:\path\to\my_script.py" --distpath "C:\path\to\dist\directory"

我想了解如何确定外部文件在转换为可执行文件并包含在脚本旁边后的路径。

【问题讨论】:

    标签: python windows pyinstaller executable


    【解决方案1】:

    这在文档中有解释。 例如查看https://readthedocs.org/projects/pyinstaller/downloads/pdf/stable/ 1.7 节运行时信息

    您也可以查看Where to put large Python lists,它提出了同样的问题,但由于问题的措辞和 OP 不知道 SIMpleGUI 在下面使用 pyinstaller 的事实,这并不容易找到。

    以下代码允许您确定基本目录(可执行文件解压缩其所有文件的目录) 在执行 python 代码之前,一个 pyinstaller 可执行文件总是被提取到一个临时目录:

    import os
    import sys
    
    if getattr(sys, "frozen", False):
        # for executable mode
        BASEDIR = sys._MEIPASS  
    else:
        # for development mode
        BASEDIR = os.path.dirname(os.path.realpath(__file__))
    

    因此,例如,如果您使用以下命令调用 pyinstaller

    pyinstaller -wF yourscript.py --add-data files:files
    

    然后你可以从目录files中获取一个文件(例如files/file1.mp3)

    mp3path = os.path.join(BASEDIR, "files", "file1.mp3")
    

    【讨论】:

      猜你喜欢
      • 2011-07-10
      • 1970-01-01
      • 2012-08-18
      • 1970-01-01
      • 1970-01-01
      • 2011-05-26
      • 1970-01-01
      • 2012-09-02
      相关资源
      最近更新 更多