Robert Motrogeanu
Robert Motrogeanu

Reputation: 47

How to find the file path to an externally used file when the script is compiled as an executable?

I am using pyinstaller to turn a very simple script into an executable using my following arguments in 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"

I would like to find out how to determine the path of the external file once it has been turned into an executable and included alongside the script.

Upvotes: 1

Views: 286

Answers (1)

gelonida
gelonida

Reputation: 5640

This is explained in the documentation. Look for example at https://readthedocs.org/projects/pyinstaller/downloads/pdf/stable/ section 1.7 Run-time Information

You can look also at Where to put large Python lists which asked kind of the same question, though not easy to find due to the phrasing of the question and the fact the the OP didn't know, that SImpleGUI uses pyinstaller beneath.

Following code allows you to determine the base dir (the directory the executable is unpacking all its files) A pyinstaller executable is always extracted to a temp dir before execution of the python code:

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__))

So if for example you called pyinstaller with following command

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

Then you can get a file (e.g. files/file1.mp3) from the directory files with

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

Upvotes: 1

Related Questions