Pyinstaller Unable to Access Data Folder

Pyinstaller Unable to access Data Folder

When pyInstaller (or cx_Freeze, py2exe, etc.) make an executable, all the program files, along with PyGame, Python and a bunch of other stuff is all compressed up.

When it's run, the first thing to happen is that archive of stuff is unpacked. Unpacked somewhere. Then your executable is started, but not from the location of the unpack.

To fix this, your script has to determine the location it is running from - that is the full path to the script. Then use this location to find all the program's extra files.

import sys
import os.path

if getattr(sys, 'frozen', False):
EXE_LOCATION = os.path.dirname( sys.executable ) # cx_Freeze frozen
else:
EXE_LOCATION = os.path.dirname( os.path.realpath( __file__ ) ) # Other packers

Then when loading a file, determine the full path with os.path.join:

my_image_filename = os.path.join( EXE_LOCATION, "images", "xenomorph.png" )
image = pygame.image.load( my_image_filename ).convert_alpha()

my_sound_filename = os.path.join( EXE_LOCATION, "sounds", "meep-meep.ogg" )
meep_sound = pygame.mixer.Sound( my_sound_filename )

It may be possible to use os.chdir( EXE_LOCATION ) to set the directory once, and thus make less changes, but I think being careful about paths is the best approach.

pyinstaller seems not to find a data file

Firstly, it might be wise to do a print config_file / os.path.exists(config_file) before reading it, so you can be sure where the file is and if python can find it.

As to actually accessing it, os.path.split(__file__) looks almost correct, but I'm not sure it works properly under pyinstaller - the proper way of packing files is to add them to the .spec file, pyinstaller will then load them at compile time and unpack them to $_MEIPASS2/ at run time. To get the _MEIPASS2 dir in packed-mode and use the local directory in unpacked (development) mode, I use this:

def resource_path(relative):
return os.path.join(
os.environ.get(
"_MEIPASS2",
os.path.abspath(".")
),
relative
)

# in development
>>> resource_path("logging.conf")
"/home/shish/src/my_app/logging.conf"

# in deployment
>>> resource_path("logging.conf")
"/tmp/_MEI34121/logging.conf"


Related Topics



Leave a reply



Submit