Python import modules, folder structures

99封情书 提交于 2019-12-04 03:24:30

The structure you're using is not one I would recommend, but I'm a comparaitive newb to how Python projects are usually structured. I believe this will do what you're after:

1) Place an __init__.py file inside /project, /project/src, and /project/test to make sure they're treated as packages.

2) Place from __future__ import absolute_import at the top of each Python file.

3) Then use relative imports:

test.py:

from ..src import models

main.py:

from .src import models

4) You'll need to start your application differently. Ensure your current directory is the parent of /project (which appears to be the file system root) and run your project this way:

python -m project.main

For my own project, I would definitely put main.py inside src if it's the start point of your application. I might put tests.py in src, too, but if not, I would add /project/src to the test runner's Python path on the command line instead of in code.

I would still use absolute_import regardless. In my experience, it's a very clean solution to module organization, and it's also how things work by default in Python 3.

first put your main.py in the src directory..

in your tests you can do , sys.path.append('the src directory')

if you like to force the execution to be in specific directory regardless from where you are executing the app i suggest you adding

import os
os.chdir('relative path to the src dir') 

thisway your program will run in the directory you specified so it will respect the relative paths you have in your code

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