我正在使用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"
我想找出如何确定将外部文件转换为可执行文件并包含在脚本旁边的路径。我正在使用的有问题的函数来自playsound库。 playsound(path)
。
这在文档中进行了解释。例如查看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 / file1.mp3)>
mp3path = os.path.join(BASEDIR, "files", "file1.mp3")