我想检测模块是否发生了变化。现在,使用inotify很简单,你只需要知道你想从哪个目录获取通知。
如何在python中检索模块的路径?
我想检测模块是否发生了变化。现在,使用inotify很简单,你只需要知道你想从哪个目录获取通知。
如何在python中检索模块的路径?
当前回答
如果使用__file__的唯一注意事项是当前相对目录为空(即,当脚本从脚本所在的同一目录运行时,作为脚本运行),那么一个简单的解决方案是:
import os.path
mydir = os.path.dirname(__file__) or '.'
full = os.path.abspath(mydir)
print __file__, mydir, full
结果是:
$ python teste.py
teste.py . /home/user/work/teste
诀窍在于“或”。'在dirname()调用之后。它将dir设置为.,这意味着当前目录,并且对于任何与路径相关的函数都是有效的目录。
因此,实际上并不需要使用abspath()。但是如果您无论如何都使用它,那么就不需要这个技巧了:abspath()接受空白路径并将其正确地解释为当前目录。
其他回答
这是微不足道的。
每个模块都有一个__file__变量,它显示了你现在所在位置的相对路径。
因此,为模块获取一个目录来通知它很简单,如下所示:
os.path.dirname(__file__)
如果你使用pip安装它,“pip show”工作得很好(“Location”)
$ PIP show detectron2
Name: detectron2
Version: 0.1
Summary: Detectron2 is FAIR next-generation research platform for object detection and segmentation.
Home-page: https://github.com/facebookresearch/detectron2
Author: FAIR
Author-email: None
License: UNKNOWN
Location: /home/ubuntu/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages
Requires: yacs, tabulate, tqdm, pydot, tensorboard, Pillow, termcolor, future, cloudpickle, matplotlib, fvcore
更新:
$ python -m PIP show mymodule
(author: wisbucky。)
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__)
获取模块的目录。
命令行实用程序
您可以将其调整为命令行实用程序,
python-which <package name>
创建/usr/local/bin/python-which
#!/usr/bin/env python
import importlib
import os
import sys
args = sys.argv[1:]
if len(args) > 0:
module = importlib.import_module(args[0])
print os.path.dirname(module.__file__)
使其可执行
sudo chmod +x /usr/local/bin/python-which
当你导入一个模块时,你可以访问大量的信息。检查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'>