开发者

Python - How to PYTHONPATH with a complex directory structure?

开发者 https://www.devze.com 2023-01-07 08:48 出处:网络
Consider the following file\\directory structure: project\\ |django_project\\ __init__.py django_app1\\

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 impor开发者_JAVA技巧t look like?


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


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.

0

精彩评论

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

关注公众号