我想检测模块是否发生了变化。现在,使用inotify很简单,你只需要知道你想从哪个目录获取通知。
如何在python中检索模块的路径?
我想检测模块是否发生了变化。现在,使用inotify很简单,你只需要知道你想从哪个目录获取通知。
如何在python中检索模块的路径?
当前回答
当你导入一个模块时,你可以访问大量的信息。检查dir(a_module)。至于路径,有一个dunder: a_module.__path__。也可以只打印模块本身。
>>> import a_module
>>> print(dir(a_module))
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__']
>>> print(a_module.__path__)
['/.../.../a_module']
>>> print(a_module)
<module 'a_module' from '/.../.../a_module/__init__.py'>
其他回答
我不明白为什么没有人谈论这个,但对我来说,最简单的解决方案是使用imp.find_module("modulename")(文档在这里):
import imp
imp.find_module("os")
它给出了一个位于第二位置的元组:
(<open file '/usr/lib/python2.7/os.py', mode 'U' at 0x7f44528d7540>,
'/usr/lib/python2.7/os.py',
('.py', 'U', 1))
与“inspect”方法相比,此方法的优点是您不需要导入模块来使其工作,并且可以在输入中使用字符串。例如,在检查另一个脚本中调用的模块时非常有用。
编辑:
在python3中,importlib模块应该这样做:
importlib.util.find_spec的文档:
Return the spec for the specified module. First, sys.modules is checked to see if the module was already imported. If so, then sys.modules[name].spec is returned. If that happens to be set to None, then ValueError is raised. If the module is not in sys.modules, then sys.meta_path is searched for a suitable spec with the value of 'path' given to the finders. None is returned if no spec could be found. If the name is for submodule (contains a dot), the parent module is automatically imported. The name and package arguments work the same as importlib.import_module(). In other words, relative module names (with leading dots) work.
如果你想从你的脚本中知道绝对路径,你可以使用path对象:
from pathlib import Path
print(Path().absolute())
print(Path().resolve('.'))
print(Path().cwd())
慢性消耗病()方法
返回一个表示当前目录的新路径对象(由os.getcwd()返回)
解决()方法
使路径为绝对路径,解析任何符号链接。返回一个新的路径对象:
您可以导入您的模块 然后点击它的名字,你会得到它的完整路径
>>> import os
>>> os
<module 'os' from 'C:\\Users\\Hassan Ashraf\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\os.py'>
>>>
import a_module
print(a_module.__file__)
会给你已经加载的。pyc文件的路径,至少在Mac OS x上是这样的
import os
path = os.path.abspath(a_module.__file__)
你也可以试试:
path = os.path.dirname(a_module.__file__)
获取模块的目录。
如果使用pip,则可以调用pip show,但必须使用正在使用的特定python版本调用它。例如,这些都可能给出不同的结果:
$ python -m pip show numpy
$ python2.7 -m pip show numpy
$ python3 -m pip show numpy
Location: /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python
不要简单地运行$ pip show numpy,因为不能保证不同的python版本调用的是同一个pip。