简体   繁体   English

来自相关包的python导入模块

[英]python import module from the relative package

I have a python project looks like this: 我有一个python项目看起来像这样:

src
 |
 +---- __init__.py
 |
 +---- branch2
         |
         +----__init__.py
         +----xx.py
 |
 +---- branch3
         |
         +---- __init__.py
         +---- yy.py

I want to import a python file in yy.py from a sibling package: 我想从同级包中导入yy.py中的python文件:

from branch2 import xx

but I got error: 但我得到了错误:

ImportError: No module named xx

I'm sure that every package has a init .py file ,and my python version is 2.7.10 我确定每个软件包都有一个init .py文件,我的python版本是2.7.10

Have you ensured that your PYTHONPATH is pointed at the scr directory? 您是否已确保PYTHONPATH指向scr目录? Not doing so will generate this error. 不这样做将产生此错误。

Whenever python interpreter encounters an import statement it looks into PYTHONPATH for that module.In your case interpreter is not able to find module in PYTHONPATH. 每当python解释器遇到import语句时,它都会查找该模块的PYTHONPATH。在您的情况下,解释器无法在PYTHONPATH中找到模块。 add the below line of code in the beginning of your python file. 在python文件的开头添加以下代码行。

import sys;
sys.path.insert('../')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM