我想检测模块是否发生了变化。现在,使用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__))

其他回答

我不明白为什么没有人谈论这个,但对我来说,最简单的解决方案是使用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.

python中有inspect模块。

官方文档

inspect模块提供了几个有用的函数来帮助获取 有关活动对象的信息,如模块、类、方法、 函数、回溯、帧对象和代码对象。例如, 它可以帮助您检查类的内容,检索源 方法的代码,提取并格式化函数的参数列表, 或者获取显示详细回溯所需的所有信息。

例子:

>>> import os
>>> import inspect
>>> inspect.getfile(os)
'/usr/lib64/python2.7/os.pyc'
>>> inspect.getfile(inspect)
'/usr/lib64/python2.7/inspect.pyc'
>>> os.path.dirname(inspect.getfile(inspect))
'/usr/lib64/python2.7'

从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的帖子,我修改了代码。

如果使用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。

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