Michael Heidweiller Michael Heidweiller - 1 year ago 67
Python Question

Python Mac OS X not loading in external XML file when it is an app

I have a Python3 script that loads the file parameters/parameters.xml. The script is built into an app with PyInstaller. Started up the following ways, the script and app work fine:

- Windows command line

- Windows double click in explorer

- Mac OS X command line

When starting the app from OS X Finder it is not able to find XML file.

Code snipped that calls the file:

self.paramTree = ET.parse("../parameters/parameters.xml")
self.paramTree = ET.parse("parameters/parameters.xml")
self.paramRoot = self.paramTree.getroot()

How could I make it so that the file is always loaded from the location of the app?

Answer Source

You access a file through a relative path. It looks like the current working directory is not set in the same way in your last case (OS X Finder): this would cause the file to not be found.

You can therefore set the working directory based on the location of your program:

import os

# __file__ is a relative path to the program file (relative to the current
# working directory of the Python interpreter).
# Therefore, dirname() can yield an empty string,
# hence the need for os.path.abspath before os.chdir() is used:
prog_dir = os.path.abspath(os.path.dirname(__file__))
os.chdir(prog_dir)  # Sets the current directory

You might set the current working directory to something a bit different from this, depending on what the script expects (maybe the parent directory of the script: os.path.join(prog_dir, os.pardir)).

This should even remove the need for doing try: since the script uses paths relative to the current working directory, the current directory should instead be set first.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download