Open file from PYTHONPATH

In the program and, obviously, influenced by how Java does something, I want to read a static file (log configuration file, actually) from a directory in the PYTHONPATH interpreter. I know I can do something like:

import foo
a = foo.__path__
conf = open(a[0] + "/logging.conf")

but I don’t know if this is the "Putin" way of doing something. How can I distribute the logging configuration file so that my application does not need external configuration to read it?

+3
source share
2 answers

, , , a[0] ( ), os.path.join / - . , , .. os.path.abspath(os.path.dirname(foo.__path__)). , , __path__ zip , ( Python, Java).

zip , pkg_resources, ( API, . packaging).

+1

Here's a Nix-based snippet posted upthread but written in a more functional style:

def search_path(pathname_suffix):
    cands = [os.path.join(d,pathname_suffix) for d in sys.path]
    try:
        return filter(os.path.exists, cands)[0]
    except IndexError:
        return None
0
source

All Articles