开发者

python import problem

although there are many posts on the internet as well as some posts on stack overflow, I still want to ask开发者_运维技巧 about this nasty python "import" problem.

OK. so, the open source code organization is usually like this:

project/src/model.py;

project/test/testmodel.py

if I put the famous __init__.py in project directory and also in src/ and test/ subdirectories, and then put "from project.src import model" for the testmodel.py. it does not work! keep telling me that the Module named "project.src" is not found!

how can I solve the problem without changing the code structure?


You shoud not add the project directory to your pythonpath but it's parent, e.g. imagine the setup

/home/user/develop/project/src/model

You'd add /home/user/develop to PYTHONPATH

If that still doesn't work, make sure you don't have a 'project.py' insite project/src/model.


Make sure you have the parent directory of project/ on your pythonpath, rather than the project directory. If you add the project path itself, imports like import project.src will look for project/project/src.


The directory where project is located is probably not in your python path.


You can use a relative import (assuming Python 2.5+) from testmodel.py, like:

from ..src import model

However, this does not work if you're running testmodel.py as the main module.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜