Python - How to PYTHONPATH with a complex directory structure?

谁说我不能喝 提交于 2019-12-24 06:12:58

问题


Consider the following file\directory structure:

project\
|  django_project\
|  |  __init__.py
|  |  django_app1\
|  |  |  __init__.py
|  |  |  utils\
|  |  |  |  __init__.py
|  |  |  |  bar1.py
|  |  |  |  ...
|  |  |  ...
|  |  django_app2\
|  |  |  __init__.py
|  |  |  bar2.py
|  |  |  ...
|  |  ...
|  scripts\
|  |  __init__.py
|  |  foo.py
|  |  ...

How should I use sys.path.append in foo.py so that I could use bar1.py and bar2.py?
How would the import look like?


回答1:


Using relative paths would be much more desirable for portability reasons.

At the top of your foo.py script add the following:

import os, sys
PROJECT_ROOT = os.path.join(os.path.realpath(os.path.dirname(__file__)), os.pardir)
sys.path.append(PROJECT_ROOT)

# Now you can import from the django_project package
from django_project.django_app1.utils import bar1
from django_project.django_app2 import bar2



回答2:


import sys
sys.path.append('/absolute/whatever/project/django_project/django_app1')
sys.path.append('/absolute/whatever/project/django_project/django_app2')

Though you need to evaluate whether you want to have both in your path -- in case there are competing module names in both. It might make sense to only have up to django_project in your path, and call django_app1/bar1.py when you need it and import django_app2.bar2.whatever when you need it.



来源:https://stackoverflow.com/questions/3249006/python-how-to-pythonpath-with-a-complex-directory-structure

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