Python从并行目录导入模块 [英] Python importing a module from a parallel directory

查看:140
本文介绍了Python从并行目录导入模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何组织我的python导入,以便我可以拥有这样的目录。

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

然后在/project/test/tests.py中可以导入classes.py

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

我在tests.py中有类似的代码/ p>

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

from .. src.classes import(
    scheduler
    db
)

我收到错误

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

任何人都知道该怎么做吗?

Anyone know what to do?

推荐答案

Python将包含您启动的脚本的文件夹添加到PYTHONPATH,因此如果您运行

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

python test/tests.py

只有文件夹 test 被添加到路径中(而不是你执行命令的基础目录)。

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

这会将基础目录添加到python路径,然后可以通过非相对导入访问类:

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

如果你真的想要要使用相对导入样式,那么需要将3个目录添加到包目录中

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

和你从包dir上面执行它

And you execute it from above the package dir with

python -m package.test.tests

参见:

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

这篇关于Python从并行目录导入模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆