How to do relative imports in Python?

前端 未结 15 2804
情深已故
情深已故 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:24

    I found it's more easy to set "PYTHONPATH" enviroment variable to the top folder:

    bash$ export PYTHONPATH=/PATH/TO/APP
    

    then:

    import sub1.func1
    #...more import
    

    of course, PYTHONPATH is "global", but it didn't raise trouble for me yet.

    0 讨论(0)
  • 2020-11-21 05:25

    As @EvgeniSergeev says in the comments to the OP, you can import code from a .py file at an arbitrary location with:

    import imp
    
    foo = imp.load_source('module.name', '/path/to/file.py')
    foo.MyClass()
    

    This is taken from this SO answer.

    0 讨论(0)
  • 2020-11-21 05:27

    You have to append the module’s path to PYTHONPATH:

    export PYTHONPATH="${PYTHONPATH}:/path/to/your/module/"
    
    0 讨论(0)
  • 2020-11-21 05:28

    "Guido views running scripts within a package as an anti-pattern" (rejected PEP-3122)

    I have spent so much time trying to find a solution, reading related posts here on Stack Overflow and saying to myself "there must be a better way!". Looks like there is not.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-21 05:32

    This is solved 100%:

    • app/
      • main.py
    • settings/
      • local_setings.py

    Import settings/local_setting.py in app/main.py:

    main.py:

    import sys
    sys.path.insert(0, "../settings")
    
    
    try:
        from local_settings import *
    except ImportError:
        print('No Import')
    
    0 讨论(0)
提交回复
热议问题