我想检测模块是否发生了变化。现在,使用inotify很简单,你只需要知道你想从哪个目录获取通知。
如何在python中检索模块的路径?
我想检测模块是否发生了变化。现在,使用inotify很简单,你只需要知道你想从哪个目录获取通知。
如何在python中检索模块的路径?
当前回答
您可以导入您的模块 然后点击它的名字,你会得到它的完整路径
>>> import os
>>> os
<module 'os' from 'C:\\Users\\Hassan Ashraf\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\os.py'>
>>>
其他回答
命令行实用程序
您可以将其调整为命令行实用程序,
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
因此,我花了相当多的时间尝试用py2exe来实现这一点 问题是获取脚本的基本文件夹,无论它是作为python脚本还是作为py2exe可执行文件运行。此外,无论它是从当前文件夹、另一个文件夹还是(这是最难的)系统路径运行,它都能正常工作。
最终我使用了这种方法,使用sys.frozen作为py2exe中运行的指示符:
import os,sys
if hasattr(sys,'frozen'): # only when running in py2exe this exists
base = sys.prefix
else: # otherwise this is a regular python script
base = os.path.dirname(os.path.realpath(__file__))
如果你想在不加载的情况下检索模块路径:
import importlib.util
print(importlib.util.find_spec("requests").origin)
示例输出:
/usr/lib64/python3.9/site-packages/requests/__init__.py
如果使用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。
如果你使用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。)