当脚本被编译为可执行文件时,如何找到外部使用的文件路径?

2024-05-22 09:36:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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"

我想了解一下,一旦外部文件转换为可执行文件并包含在脚本中,如何确定其路径


Tags: topathpy脚本add可执行文件data参数
1条回答
网友
1楼 · 发布于 2024-05-22 09:36:41

文档中对此进行了解释。 查看https://readthedocs.org/projects/pyinstaller/downloads/pdf/stable/第1.7节运行时信息的示例

您还可以看看Where to put large Python lists,它问了类似的问题,尽管由于问题的措辞和OP不知道的事实,很难找到,SImpleGUI在下面使用pyinstaller

下面的代码允许您确定基本目录(可执行文件解包所有文件的目录) pyinstaller可执行文件总是在执行python代码之前提取到临时目录:

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/file1.mp3)

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

相关问题 更多 >