Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open a file from PYTHONPATH

Tags:

python

In a program, and obviously being influenced by the way Java does things, I want to read a static file (a log configuration file, actually) from a directory within the interpreter's PYTHONPATH. I know I could do something like:

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

but I don't know if this is the "Pythonic" way of doing things. How could I distribute the logging configuration file in a way that my application does not need to be externally configured to read it?

like image 707
Georgios Gousios Avatar asked Feb 07 '26 20:02

Georgios Gousios


2 Answers

In general, that's fine, though I'm not sure you want a[0] above (that will just give you the first character of the path), and you should use os.path.join instead of just appending / to be cross-platform compatible. You might consider making the path canonical, i.e. os.path.abspath(os.path.dirname(foo.__path__)). Note that it won't work if __path__ is in a zip file or other import trickery is in use, but I wouldn't worry about that (it's not normal to do so for the main program in Python, unlike Java).

If you do want to support zipped files, there's pkg_resources, but that's somewhat deprecated at this point (there's no corresponding API I could see in the new packaging module).

like image 110
Nicholas Riley Avatar answered Feb 09 '26 10:02

Nicholas Riley


Here's a snippet based on the link Nix 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
like image 45
Joe Futrelle Avatar answered Feb 09 '26 10:02

Joe Futrelle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!