如何检索模块的路径?

2024-04-19 23:00:37 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

正如其他答案所说,最好的方法是使用__file__(在下面再次演示)。但是,有一个重要的警告,那就是如果您独自运行模块(即作为__main__),那么__file__不存在。

例如,假设您有两个文件(都在PYTHONPATH上):

#/path1/foo.py
import bar
print(bar.__file__)

以及

#/path2/bar.py
import os
print(os.getcwd())
print(__file__)

运行foo.py将给出输出:

/path1        # "import bar" causes the line "print(os.getcwd())" to run
/path2/bar.py # then "print(__file__)" runs
/path2/bar.py # then the import statement finishes and "print(bar.__file__)" runs

但是,如果您尝试单独运行bar.py,您将得到:

/path2                              # "print(os.getcwd())" still works fine
Traceback (most recent call last):  # but __file__ doesn't exist if bar.py is running as main
  File "/path2/bar.py", line 3, in <module>
    print(__file__)
NameError: name '__file__' is not defined 

希望这有帮助。在测试所提供的其他解决方案时,这个警告花费了我大量的时间和混乱。

import a_module
print(a_module.__file__)

实际上会给你加载的.pyc文件的路径,至少在MacOSX上是这样。所以我想你可以:

import os
path = os.path.abspath(a_module.__file__)

您还可以尝试:

path = os.path.dirname(a_module.__file__)

获取模块的目录。

python中有inspect模块。

Official documentation

The inspect module provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects. For example, it can help you examine the contents of a class, retrieve the source code of a method, extract and format the argument list for a function, or get all the information you need to display a detailed traceback.

示例:

>>> import os
>>> import inspect
>>> inspect.getfile(os)
'/usr/lib64/python2.7/os.pyc'
>>> inspect.getfile(inspect)
'/usr/lib64/python2.7/inspect.pyc'
>>> os.path.dirname(inspect.getfile(inspect))
'/usr/lib64/python2.7'

相关问题 更多 >