How to do relative imports in Python?

前端 未结 15 3160
情深已故
情深已故 2020-11-21 04:47

Imagine this directory structure:

app/
   __init__.py
   sub1/
      __init__.py
      mod1.py
   sub2/
      __init__.py
      mod2.py

I\'

15条回答
  •  生来不讨喜
    2020-11-21 05:30

    def import_path(fullpath):
        """ 
        Import a file with full path specification. Allows one to
        import from anywhere, something __import__ does not do. 
        """
        path, filename = os.path.split(fullpath)
        filename, ext = os.path.splitext(filename)
        sys.path.append(path)
        module = __import__(filename)
        reload(module) # Might be out of date
        del sys.path[-1]
        return module
    

    I'm using this snippet to import modules from paths, hope that helps

提交回复
热议问题