我想检测模块是否发生了变化。现在,使用inotify很简单,你只需要知道你想从哪个目录获取通知。
如何在python中检索模块的路径?
我想检测模块是否发生了变化。现在,使用inotify很简单,你只需要知道你想从哪个目录获取通知。
如何在python中检索模块的路径?
当前回答
如果你想在一个“程序”中动态地做到这一点,试试下面的代码: 我的观点是,你可能不知道模块的确切名称来“硬编码”它。 它可以从列表中选择,也可以当前未运行以使用__file__。
(我知道,它在python3中不起作用)
global modpath
modname = 'os' #This can be any module name on the fly
#Create a file called "modname.py"
f=open("modname.py","w")
f.write("import "+modname+"\n")
f.write("modpath = "+modname+"\n")
f.close()
#Call the file with execfile()
execfile('modname.py')
print modpath
<module 'os' from 'C:\Python27\lib\os.pyc'>
我试图摆脱“全球”问题,但发现在某些情况下它不起作用 我认为"execfile()"可以在python3中模拟 由于这是在程序中,所以可以很容易地将其放入方法或模块中进行重用。
其他回答
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__)
获取模块的目录。
如果你想在不加载的情况下检索模块路径:
import importlib.util
print(importlib.util.find_spec("requests").origin)
示例输出:
/usr/lib64/python3.9/site-packages/requests/__init__.py
如果你想从你的脚本中知道绝对路径,你可以使用path对象:
from pathlib import Path
print(Path().absolute())
print(Path().resolve('.'))
print(Path().cwd())
慢性消耗病()方法
返回一个表示当前目录的新路径对象(由os.getcwd()返回)
解决()方法
使路径为绝对路径,解析任何符号链接。返回一个新的路径对象:
如果你使用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。)
这是微不足道的。
每个模块都有一个__file__变量,它显示了你现在所在位置的相对路径。
因此,为模块获取一个目录来通知它很简单,如下所示:
os.path.dirname(__file__)