我想检测模块是否发生了变化。现在,使用inotify很简单,你只需要知道你想从哪个目录获取通知。
如何在python中检索模块的路径?
我想检测模块是否发生了变化。现在,使用inotify很简单,你只需要知道你想从哪个目录获取通知。
如何在python中检索模块的路径?
当前回答
下面是一个快速bash脚本,以防它对任何人都有用。我只是想设置一个环境变量,这样我就能把它推到代码中。
#!/bin/bash
module=${1:?"I need a module name"}
python << EOI
import $module
import os
print os.path.dirname($module.__file__)
EOI
壳牌的例子:
[root@sri-4625-0004 ~]# export LXML=$(get_python_path.sh lxml)
[root@sri-4625-0004 ~]# echo $LXML
/usr/lib64/python2.7/site-packages/lxml
[root@sri-4625-0004 ~]#
其他回答
如果你想从你的脚本中知道绝对路径,你可以使用path对象:
from pathlib import Path
print(Path().absolute())
print(Path().resolve('.'))
print(Path().cwd())
慢性消耗病()方法
返回一个表示当前目录的新路径对象(由os.getcwd()返回)
解决()方法
使路径为绝对路径,解析任何符号链接。返回一个新的路径对象:
正如其他答案所说,最好的方法是使用__file__(下面再次演示)。然而,有一个重要的警告,即如果你单独运行模块(即作为__main__), __file__是不存在的。
例如,假设你有两个文件(都在你的PYTHONPATH上):
#/path1/foo.py
import bar
print(bar.__file__)
and
#/path2/bar.py
import os
print(os.getcwd())
print(__file__)
运行foo.py会得到如下输出:
/path1 # "import bar" causes the line "print(os.getcwd())" to run
/path2/bar.py # then "print(__file__)" runs
/path2/bar.py # then the import statement finishes and "print(bar.__file__)" runs
然而,如果你试图单独运行bar.py,你会得到:
/path2 # "print(os.getcwd())" still works fine
Traceback (most recent call last): # but __file__ doesn't exist if bar.py is running as main
File "/path2/bar.py", line 3, in <module>
print(__file__)
NameError: name '__file__' is not defined
希望这能有所帮助。在测试其他解决方案时,这个警告花费了我大量的时间和混乱。
命令行实用程序
您可以将其调整为命令行实用程序,
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
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__)
获取模块的目录。
因此,我花了相当多的时间尝试用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__))