Reputation: 4449
I'm developing a module right now that requires a configuration file.
The configuration file is optional and can be supplied when the module is launched, or (ideally) loaded from a defaults.json
file located in the same directory as the application. The defaults.json file's purpose is also used to fill in missing keys with setdefault
.
The problem comes from where the module is launched...
...\Application
= python -m application.web.ApplicationServer
...\Application\application
= python -m web.ApplicationServer
...\Application\application\web
= python ApplicationServer.py
....read as, "If if I'm in the folder, I type this to launch the server."
How can I determine where the program was launched from (possibly using os.getcwd()
) to determine what file path to pass to json.load(open(<path>), 'r+b'))
such that it will always succeed?
Thanks.
Note: I strongly prefer to get a best practices answer, as I can "hack" a solution together already -- I just don't think my way is the best way. Thanks!
Upvotes: 0
Views: 985
Reputation: 7304
If you want to get the path to file that has your code relative to from where it was launched, then it is stored in the __file__
of the module, which can be used if you:
setup.py
/distutils
scheme.So a codeDir = os.path.dirname(os.path.abspath(__file__))
should always work.
If you want to make an installer, I would say it is customary to place the code in one place and things like configs somewhere else. And that would depend on your OS. On linux, one common place is in /home/user/.local/share/yourmodule
or just directly under /home/user/.yourmodule
. Windows have similar place for app-data.
For both, os.environ['HOME']
/ os.getenv('HOME')
is a good starting point, and then you should probably detect the OS and place your stuff in the expected location with a nice foldername.
I can't swear that these are best practices, but they seem rather hack-free at least.
Upvotes: 3