Question

I've never had to consider about any kind of software distributing (I'm using python for this project), so now I'm not sure about the 'best' or most common used approach of filename handling. Now I use relative paths for all images, config files, ... from the top-level-directory with the executable program.

So it naturally fails when the program is executed from different location. My question is, if it is Ok to change curent working directory in the beginnig of the program to dirname of __file__ (It's executed in sub-shell so I don't see a problem with this - but I want to run platfrom independent, so I'm not sure how windows handles it), or if it issue I can solve using distutils and installing the whole program (I'd prefer not to). Or if there are any other (better) ways?

So basically I can solve the problem easily, I just want to know what is the usual to do, thank you for your advice.

Was it helpful?

Solution

Best practice is to use absolute paths.

Use the __file__ path not to change directories, instead use it to calculate a base path to use to build absolute paths. In a top-level module, add:

import os.path

BASE = os.path.dirname(os.path.abspath(__file__))

and reuse BASE to build absolute paths:

abspath = os.path.join(BASE, relpath)

Changing the working directory is rarely needed or useful.

OTHER TIPS

Well __file__ is defined for a given module and not all modules has this property. According to the documentation:

__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file. The __file__ attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.

Since you are planning to invoke this in your own module you shouldn't have any problem on linux, windows and even osx. Of course, use os.path module to manipulate the paths.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top