且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python 从更高级别的包中导入模块

更新时间:2022-05-01 23:00:23

如果你将app/server.py作为脚本运行,app的父目录为未添加到 sys.path().而是添加了 app 目录本身(不是作为包,而是作为导入搜索路径).

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).

您有 4 个选项:

  1. app 包的 server.py out 移出(旁边)
  2. app 旁边添加一个仅运行的新脚本文件:

  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()

  • 使用 -m切换选项来运行一个模块作为主入口点:

  • Use the -m switch option to run a module as the main entry point:

    python -m app.server
    

  • server.py的父目录添加到sys.path:

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

    然而,这最后一个选项可能会带来更多问题;现在 app 包和 in app 包中包含的模块都在 sys.path 上.您可以同时导入 app.serverserver,Python 会将它们视为两个独立的模块,每个模块在 sys.modules 中都有自己的条目,具有其全局变量的单独副本.

    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.