当脚本被编译为可执行文件时,如何找到外部使用文件的文件路径?
How to find the file path to an externally used file when the script is compiled as an executable?
我正在使用 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"
我想了解如何在将外部文件转换为可执行文件并包含在脚本中后确定其路径。
这在文档中有解释。
在 https://readthedocs.org/projects/pyinstaller/downloads/pdf/stable/ 第 1.7 节 运行-time Information
中查看示例
您还可以查看 ,它提出了同样的问题,但由于问题的措辞和 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")
我正在使用 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"
我想了解如何在将外部文件转换为可执行文件并包含在脚本中后确定其路径。
这在文档中有解释。 在 https://readthedocs.org/projects/pyinstaller/downloads/pdf/stable/ 第 1.7 节 运行-time Information
中查看示例您还可以查看
以下代码允许您确定基本目录(可执行文件解压缩其所有文件的目录) 在执行 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")