How do I get the file location of libraries imported by Python
Considering this line of Python code:
import foo
how do I then find the locati开发者_Go百科on on disk of the file that contains the source code to be executed in foo?
(And I'm on Win7)
You can find the information in
foo.__file__
Note that not all modules come from files, though. Some modules are also compiled directly into the interpreter, and those modules won't have a __file__
attribute.
A list of the modules included in the interpreter can be found in sys.builtin_module_names
.
I'm not sure about the value of __file__
when the module does not have a one-to-one mapping to a file in the file-system. Specifically, if it is loading a module found within a ZIP file, I'm not sure what __file__
will look like. (When I've needed such mappings, I've used tuples with ("path/to/file.zip", "path/within/zip/module.pyc") but that was a result of walking sys.path manually.) It wouldn't surprise me if it just set __file__
to None
.
When it is an issue as to which module of the same name will be loaded, it is always the first one found on the sys.path
.
It is possible to sys.path.insert(0, some_dir)
before you do your first import of the package to tweak things manually. (In the environment, this is set with PYTHONPATH.)
Ideally, you can find out which is being used simply by checking PYTHONPATH
and/or sys.path
. If the wrong one is being loaded, the only way to fix it is with PYTHONPATH
or sys.path
.
精彩评论