Python import modules from a higher level package
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:
- Move
server.py
out of theapp
package (next to it) Add a new script file next to
app
that only runs:from app import server server.main()
Use the
-m
switch option to run a module as the main entry point:python -m app.server
Add the parent directory of
server.py
tosys.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 theapp
package are onsys.path
. You can import bothapp.server
andserver
and Python will see these as two separate modules, each with their own entry insys.modules
, with separate copies of their globals.