【问题标题】:Python - How to PYTHONPATH with a complex directory structure?Python - 如何使用复杂的目录结构使用 PYTHONPATH?
【发布时间】:2011-03-16 00:12:18
【问题描述】:

考虑以下文件\目录结构:

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
|  |  ...

我应该如何在 foo.py 中使用 sys.path.append 以便我可以使用 bar1.pybar2 .py?
导入会是什么样子?

【问题讨论】:

    标签: python pythonpath python-import


    【解决方案1】:

    出于可移植性的原因,使用相对路径会更加理想。

    foo.py 脚本的顶部添加以下内容:

    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')
      

      尽管您需要评估是否要在您的路径中同时拥有这两者——以防两者中存在相互竞争的模块名称。在您的路径中最多只包含django_project 可能是有意义的,并在需要时调用django_app1/bar1.py 并在需要时调用import django_app2.bar2.whatever

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-07
        • 2022-01-13
        • 1970-01-01
        • 1970-01-01
        • 2012-10-02
        • 1970-01-01
        • 2017-01-07
        • 1970-01-01
        相关资源
        最近更新 更多