Python import modules from a higher level package

前端 未结 2 862
情歌与酒
情歌与酒 2020-11-30 13:00

This is my package hierarchy

app  
|--__init__.py    //Empty file
|--server.py  
|--global_vars.py  
|
|--handlers    
   |--__init__.py    //Empty file
   |         


        
相关标签:
2条回答
  • 2020-11-30 13:40

    If you are running app/server.py as a script, the parent directory of app is not added to sys.path(). The app directory itself is added instead (not as a package but as a import search path).

    You have 4 options:

    1. Move server.py out of the app package (next to it)
    2. Add a new script file next to app that only runs:

      from app import server
      server.main()
      
    3. Use the -m switch option to run a module as the main entry point:

      python -m app.server
      
    4. Add the parent directory of server.py to sys.path:

      import os.path
      import sys
      
      parent = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
      sys.path.insert(0, parent)
      

      This last option can introduce more problems however; now both the app package and the modules contained in the app package are on sys.path. You can import both app.server and server and Python will see these as two separate modules, each with their own entry in sys.modules, with separate copies of their globals.

    0 讨论(0)
  • 2020-11-30 13:46

    need __init__.py file, will regard it as a package

    app
    |--server.py
    |--global_vars.py
    |--handlers

    |--__init__.py ...

    __init__.py can be empty

    0 讨论(0)
提交回复
热议问题