Making relative path to file to work
In the previous article I’ve described my way to configure logging. One of the pitfalls was that if I want to use relative path to logging configuration file, I should run my application/script from the same folder.
Note: Logging configuration files are not special. The problem occur when you use relative path to any file.
I’ve written small utility function that overcomes this limitation. You can run your application/script from any working directory, this function will fix cwd to the expected one in such a way, that relative paths will work. See more details below.
You can install AlexBerUtils from PyPi:
python3 -m pip install -U alex-ber-utils
See here for more details explanation on how to install.
This is usage example:
Now, I recommend you to put this code snippet after you did your basic logging configuration (because, this function use logger; otherwise, you will lose these messages), but before you use any of relative path. It can be relative path to the logging configuration file or, for example, to
You code should look like something like this:
Basically, it looks for
__file__ attribute in the
__main__ module, takes directory from there and set cwd to it (by calling to
If this function is called in REPL or IPython notebook it does nothing.
This function wasn’t tested from frozen python script (frozen using py2exe), but it should work (by doing nothing).
importermodule or How to write easily customizable code?
mainsmodule or Making relative path to file to work.
mainsmodule or Make path to file on Windows works on Linux.
- parser module or Description of one the oldest AlexBerUtils project
- ymlparsers module or Description of low-level API module for another modules
- init_app_conf module, or My major init_app_con module
- deploys module, or My deploys module
- emails module,or My emails module
- processinvokes module, or My processinvokes module