views:

80

answers:

1

I'm developing a python application and have a question regarding coding it so that it still works after an user has installed it on his or her machine via setup.py install or similar.

In one of my files, I use the following:

file = "TestParser/View/MainWindow.ui"
cwd = os.getcwd()
argv_path = os.path.dirname(sys.argv[0])
file_path = os.path.join(cwd, argv_path, file)

in order to get the path to MainWindow.ui, when I only know the path relative to the main script's location. This works regardless of from where I call the main script.

The issue is that after an user installs the application on his or her machine, the relative path is different, so this doesn't work. I could use __file__, but according to this, py2exe doesn't have __file__.

Is there a standard way of achieving this? Or a better way?

EDIT:

Should I even worry about py2exe and just use __file__? I have no immediate plans to use py2exe, but I was hoping to learn the proper way of accessing files in this context.

+1  A: 

With setup.py there is never a simple answer that works for all scenarios. Setup.py is a huge PITA to get working with different installation procedures (e.g., "setup.py install", py2exe, py2app).

For example, in my app, I have this code to find files needed by the app:

def getHome():
  if hasattr(sys, "frozen"):
    if sys.platform == "darwin": # OS X
      return os.path.join(os.path.dirname(os.path.dirname(sys.executable)), "Resources")
    return os.path.dirname(sys.executable)
  else:
    return os.path.dirname(__file__)

"frozen" is set for apps created with py2exe and py2app.

So to answer your question, use __file__ and do not worry about py2exe. If you ever need to use py2exe, you will probably need to create a special case anyway.

Jeff