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
Error Message: 'Chromedriver' Executable Needs to Be Path
Color Coding Cells in a Table Based on the Cell Value Using Jinja Templates
How to Set the R_Home Environment Variable to the R Home Directory
Restrictons of Python Compared to Ruby: Lambda'S
Is There a Function That Checks If a Character in a String Is a Letter in the Alphabet? (Swift)
Python MySQL Connector Database Query with %S Fails
Where Is a Complete Example of Logging.Config.Dictconfig
How to Copy a 2D Array into a 3Rd Dimension, N Times
How to Edit Header Row in Pandas - Styling
R's Which() and Which.Min() Equivalent in Python
Convert Uiimage from Bgr to Rgb
Matplotlib: Annotating a 3D Scatter Plot