How to retrieve a module's path?

后端 未结 20 2089
无人及你
无人及你 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:05

    From within modules of a python package I had to refer to a file that resided in the same directory as package. Ex.

    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
    

    So in above I had to call maincli.py from my_lib_a.py module knowing that top_package and maincli.py are in the same directory. Here's how I get the path to maincli.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
    

    Based on posting by PlasmaBinturong I modified the code.

提交回复
热议问题