更新时间:2021-12-13 10:46:26
如果将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个选择:
server.py
移出app
程序包(在其旁边)在仅运行的app
旁边添加一个新的脚本文件:
server.py
out of the app
package (next to it)Add a new script file next to app
that only runs:
from app import server
server.main()
使用 -m
开关选项运行 module 作为主要入口点:
Use the -m
switch option to run a module as the main entry point:
python -m app.server
将server.py
的父目录添加到sys.path
:
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)
这最后一个选项可能会带来更多问题;现在app
软件包和app
软件包中 中包含的模块都在sys.path
上.您可以同时导入app.server
和server
,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.