简体   繁体   English

在settings.py中更改sys.path

[英]changing sys.path in settings.py

In a django test project's settings.py I recently tried putting this in: 在Django测试项目的settings.py我最近尝试将其放入:

try:
    import mymodule
except:
    import sys
    TESTPROJ_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
    PROJ_PARENT = os.path.abspath(os.path.join(TESTPROJ_ROOT, '..'))
    sys.path.append(PROJ_PARENT)

The purpose was to add a local project path if mymodule wasn't installed in the environment. 目的是在环境中未安装mymodule下添加本地项目路径。 To aid understanding, the directory structure is as follows: 为了帮助理解,目录结构如下:

base/mymodule
base/test_project/manage.py
base/test_project/test_project/settings.py

This worked so long as mymodule wasn't in the environment. 只要mymodule不在环境中, mymodule工作。 As soon as import mymodule was executed (anywhere in settings.py ) I got the error: 只要执行import mymodule (在settings.py任何地方),我都会收到错误消息:

django.core.exceptions.ImproperlyConfigured: ImportError django.contrib.admin: cannot import name signals

I have two questions... 我有两个问题

a) is there any way to stop this error from happening? a)有什么方法可以阻止此错误的发生?

b) is there another 'smart' way to allow settings.py to change the path to allow a module to be locally included if it's not in the environment? b)是否还有另一种“智能”方式允许settings.py更改路径,以允许模块不在环境中(本地)?

Thanks in advance. 提前致谢。

You can create a file my-site.pth in a directory that is a part of sys.path , and include in that file the full path to the directory you want to add. 您可以在sys.path的一部分目录中创建文件my-site.pth ,并在该文件中包含要添加目录的完整路径。

my-site.pth

base/mymodule

http://docs.python.org/2/library/site.html http://docs.python.org/2/library/site.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM