检索python模块路径

我想检测模块是否已经改变。 现在,使用inotify很简单,你只需要知道你想从中获取通知的目录。

如何在python中检索模块的路径?


import a_module
print a_module.__file__

实际上会给你加载的.pyc文件的路径,至少在Mac OS X上。所以我想你可以做

import os
path = os.path.dirname(amodule.__file__)

你也可以试试

path = os.path.abspath(amodule.__file__)

获取目录以查找更改。


python中有inspect模块。

官方文件

检查模块提供了几个有用的功能来帮助获取有关活动对象的信息,例如模块,类,方法,函数,回溯,框架对象和代码对象。 例如,它可以帮助您检查类的内容,检索方法的源代码,提取并格式化函数的参数列表,或者获取显示详细回溯所需的所有信息。

例:

>>> 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'

正如其他答案所说,最好的办法是用__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 

希望这可以帮助。 这个告诫在测试其他解决方案时花费了我大量的时间和精力。

链接地址: http://www.djcxy.com/p/54723.html

上一篇: Retrieving python module path

下一篇: cv2.imread fails in script, not on command line