我想检测模块是否发生了变化。现在,使用inotify很简单,你只需要知道你想从哪个目录获取通知。

如何在python中检索模块的路径?


当前回答

因此,我花了相当多的时间尝试用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__))

其他回答

这是微不足道的。

每个模块都有一个__file__变量,它显示了你现在所在位置的相对路径。

因此,为模块获取一个目录来通知它很简单,如下所示:

os.path.dirname(__file__)

如果你想在一个“程序”中动态地做到这一点,试试下面的代码: 我的观点是,你可能不知道模块的确切名称来“硬编码”它。 它可以从列表中选择,也可以当前未运行以使用__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中模拟 由于这是在程序中,所以可以很容易地将其放入方法或模块中进行重用。

我不明白为什么没有人谈论这个,但对我来说,最简单的解决方案是使用imp.find_module("modulename")(文档在这里):

import imp
imp.find_module("os")

它给出了一个位于第二位置的元组:

(<open file '/usr/lib/python2.7/os.py', mode 'U' at 0x7f44528d7540>,
'/usr/lib/python2.7/os.py',
('.py', 'U', 1))

与“inspect”方法相比,此方法的优点是您不需要导入模块来使其工作,并且可以在输入中使用字符串。例如,在检查另一个脚本中调用的模块时非常有用。

编辑:

在python3中,importlib模块应该这样做:

importlib.util.find_spec的文档:

Return the spec for the specified module. First, sys.modules is checked to see if the module was already imported. If so, then sys.modules[name].spec is returned. If that happens to be set to None, then ValueError is raised. If the module is not in sys.modules, then sys.meta_path is searched for a suitable spec with the value of 'path' given to the finders. None is returned if no spec could be found. If the name is for submodule (contains a dot), the parent module is automatically imported. The name and package arguments work the same as importlib.import_module(). In other words, relative module names (with leading dots) work.

下面是一个快速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 ~]#
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__)

获取模块的目录。