8

这是我的包层次结构

app  
|--__init__.py    //Empty file
|--server.py  
|--global_vars.py  
|
|--handlers    
   |--__init__.py    //Empty file
   |
   |--url1
   |  |--__init__.py    //Empty file
   |  |--app1.py
   |  |--app2.py
   |
   |--url2
      |--__init__.py    //Empty file
      |--app3.py

现在我想在global_vars.py里面导入app1.py。所以我给了 import app.global_vars.pyapp1.py里面。

但我收到以下错误:

    import app.global_vars
ImportError: No module named app.global_vars

我还应该提到我正在从 server.py 导入 app1.py。server.py是我实际运行的文件。当 server.py 导入 app1.py 时,app1.py尝试导入global_vars.py并出现上述错误

我在这里做错了什么?

4

2 回答 2

14

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.

于 2013-05-28T08:09:47.400 回答
0

需要__init__.py文件,将其视为一个包

应用程序
|--server.py
|--global_vars.py
|--handlers

|-- __init__.py ...

__init__.py可以为空

于 2013-05-28T07:48:12.357 回答