Determining the location of a Python package before importing

I want to get the package location before importing it. I basically would like to do

import pkg pkg_path = pkg.__file__ 

but without import pkg . Now I am 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 in which this will not work ( target does not contain __init__.py , target is inside a compressed EGG file).

Is there a better way to get target_path ?

Thanks,

Yang

+6
source share
2 answers

Yes, there is imp.find_module() :

 target_path = imp.find_module(target) 
+5
source

You can use [__import__()][1] as follows:

 target_path = __import__('pkg').__file__ 

__import__() used by import , and one of its uses is when the module name is known only at run time.

0
source

Source: https://habr.com/ru/post/887372/


All Articles