我想检测模块是否发生了变化。现在,使用inotify很简单,你只需要知道你想从哪个目录获取通知。
如何在python中检索模块的路径?
我想检测模块是否发生了变化。现在,使用inotify很简单,你只需要知道你想从哪个目录获取通知。
如何在python中检索模块的路径?
当前回答
如果你使用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。)
其他回答
从python包的模块中,我必须引用与包位于同一目录中的文件。前女友。
some_dir/
maincli.py
top_package/
__init__.py
level_one_a/
__init__.py
my_lib_a.py
level_two/
__init__.py
hello_world.py
level_one_b/
__init__.py
my_lib_b.py
所以在上面,我必须从my_lib_a.py模块调用maincli.py,知道top_package和maincli.py在同一个目录中。下面是我获取main .py路径的方法:
import sys
import os
import imp
class ConfigurationException(Exception):
pass
# inside of my_lib_a.py
def get_maincli_path():
maincli_path = os.path.abspath(imp.find_module('maincli')[1])
# top_package = __package__.split('.')[0]
# mod = sys.modules.get(top_package)
# modfile = mod.__file__
# pkg_in_dir = os.path.dirname(os.path.dirname(os.path.abspath(modfile)))
# maincli_path = os.path.join(pkg_in_dir, 'maincli.py')
if not os.path.exists(maincli_path):
err_msg = 'This script expects that "maincli.py" be installed to the '\
'same directory: "{0}"'.format(maincli_path)
raise ConfigurationException(err_msg)
return maincli_path
根据PlasmaBinturong的帖子,我修改了代码。
如果你想在一个“程序”中动态地做到这一点,试试下面的代码: 我的观点是,你可能不知道模块的确切名称来“硬编码”它。 它可以从列表中选择,也可以当前未运行以使用__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中模拟 由于这是在程序中,所以可以很容易地将其放入方法或模块中进行重用。
如果你想从包的任何模块中检索包的根路径,下面的工作(在Python 3.6上测试):
from . import __path__ as ROOT_PATH
print(ROOT_PATH)
主__init__.py路径也可以通过使用__file__来引用。
希望这能有所帮助!
这是微不足道的。
每个模块都有一个__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。)