Python importing a module from a parallel directory

假装没事ソ 提交于 2019-11-27 15:04:54

问题


How would I organize my python imports so that I can have a directory like this.

project
|      \
|      __init__.py
|     
src
|   \
|    __init__.py
|    classes.py
|
test
    \
     __init__.py
     tests.py

And then inside /project/test/tests.py be able to import classes.py

I've got code looking like this in tests.py

from .. src.classes import(
    scheduler
    db
)

And am getting errors of

SystemError: Parent module '' not loaded, cannot perform relative import

Anyone know what to do?


回答1:


Python adds the folder containing the script you launch to the PYTHONPATH, so if you run

python test/tests.py

Only the folder test is added to the path (not the base dir that you're executing the command in).

Instead run your tests like so:

python -m test.tests

This will add the base dir to the python path, and then classes will be accessible via a non-relative import:

from src.classes import etc

If you really want to use the relative import style, then your 3 dirs need to be added to a package directory

package
* __init__.py
* project
* src
* test

And you execute it from above the package dir with

python -m package.test.tests

See also:

  • https://docs.python.org/2/using/cmdline.html
  • http://www.stereoplex.com/blog/understanding-imports-and-pythonpath


来源:https://stackoverflow.com/questions/24622041/python-importing-a-module-from-a-parallel-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!