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

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


当前回答

如果你导入的是一个site-package(例如pandas),我建议这样获取它的目录(如果import是一个模块,例如pathlib):

from importlib import resources  # part of core Python
import pandas as pd

package_dir = resources.path(package=pd, resource="").__enter__()

在一般情况下。当任务是关于访问站点包的路径/资源时,可以考虑资源。

其他回答

这是微不足道的。

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

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

os.path.dirname(__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包的模块中,我必须引用与包位于同一目录中的文件。前女友。

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

如果你想从包的任何模块中检索包的根路径,下面的工作(在Python 3.6上测试):

from . import __path__ as ROOT_PATH
print(ROOT_PATH)

主__init__.py路径也可以通过使用__file__来引用。

希望这能有所帮助!

我想提供一个常见的场景(在Python 3中),并探索一些实现它的方法。

内置函数open()接受相对路径或绝对路径作为其第一个参数。相对路径被视为相对于当前工作目录,因此建议将绝对路径传递给文件。

简单地说,如果你用下面的代码运行一个脚本文件,并不保证example.txt文件会被创建在脚本文件所在的同一目录下:

with open('example.txt', 'w'):
    pass

要修复这段代码,我们需要获取脚本的路径,并使其成为绝对路径。为了确保路径是绝对的,我们只需使用os.path.realpath()函数。为了获得脚本的路径,有几个常见的函数返回不同的路径结果:

os.getcwd() os.path.realpath('example.txt') sys.argv[0] __文件__

os.getcwd()和os.path.realpath()函数都会返回基于当前工作目录的路径结果。通常不是我们想要的。系统的第一个元素。Argv list是根脚本(您运行的脚本)的路径,而不管您是在根脚本本身中还是在其任何模块中调用该列表。在某些情况下可能会派上用场。__file__变量包含调用它的模块的路径。


下面的代码正确地在脚本所在的目录中创建了一个文件example.txt:

filedir = os.path.dirname(os.path.realpath(__file__))
filepath = os.path.join(filedir, 'example.txt')

with open(filepath, 'w'):
    pass