How to retrieve a module's path?

后端 未结 20 1723
无人及你
无人及你 2020-11-22 05:34

I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from.

How do I retrieve

20条回答
  •  清酒与你
    2020-11-22 06:19

    I don't get why no one is talking about this, but to me the simplest solution is using imp.find_module("modulename") (documentation here):

    import imp
    imp.find_module("os")
    

    It gives a tuple with the path in second position:

    (,
    '/usr/lib/python2.7/os.py',
    ('.py', 'U', 1))
    

    The advantage of this method over the "inspect" one is that you don't need to import the module to make it work, and you can use a string in input. Useful when checking modules called in another script for example.

    EDIT:

    In python3, importlib module should do:

    Doc of 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.

提交回复
热议问题