Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining Python package location prior to import

I want to get the location of a package before importing it. Basically I'd like to do

import pkg
pkg_path = pkg.__file__

but without having to import pkg. Right now I'm doing:

target = "pkg"
target_path = None
for p in sys.path:
    search_path = "%s/%s" % (p, target)
    if os.path.exists(search_path):
        target_path = search_path

but there are several scenarios where this won't work (target doesn't contain __init__.py, target is inside a compressed EGG file).

Is there any better way to get target_path?

Thanks,

Ian

like image 268
IanSR Avatar asked May 05 '11 14:05

IanSR


1 Answers

Yes, there is imp.find_module():

target_path = imp.find_module(target)
like image 139
Sven Marnach Avatar answered Sep 21 '22 04:09

Sven Marnach