问题
I'm working on a plugin architecture and need to convert a package name like "foo.bar" to the absolute path where the code resides. imp.find_module seems to do what I want, except when the code in question is installed via an egg-link (installed via 'pip install develop').
If there are two modules foo.bar and foo.bar2 which are installed via egg-links (and which live at completely separate file system locations like /home/bob/foo/bar and /home/alice/foo/bar2), find_modules doesn't work because I look up the package "foo" and get the location to foo/bar, but not foo/bar2.
Anyone have suggestions for an alternative function? find_modules doesn't accept hierarchical names, so I can't just pass "foo.bar2" into it.
回答1:
The easiest way would be to just import the module and inspect its __file__ attribute:
import os
import foo.bar
print(os.path.abspath(foo.bar.__file__))
For dynamic imports:
import os
import sys
module_name = 'foo.bar'
__import__(module_name)
print(os.path.abspath(sys.modules[module_name].__file__))
来源:https://stackoverflow.com/questions/8395868/how-to-find-the-location-of-a-python-package-installed-via-egg-link