问题描述
我正在编写基于python和Django的基于Web的应用程序.我有一个包含 LIBS 目录的源代码文件夹,该目录具有一个名为 utils.py 的文件.当我要安装我的应用程序时,会将新行添加到〜/.profile文件中,例如 export PYTHONPATH = $ PYTHONPATH:/home/test/src/LIBS (根据安装路径添加路径))当我在解释器中运行以下代码时,路径就可以了:
I am writing a web based app based on python and django. I have a source code folder containing LIBS directory that has a file named utils.py. When I want to install my app a new line is added to ~/.profile file like export PYTHONPATH=$PYTHONPATH:/home/test/src/LIBS (The path is added based on the installation path)When I run the below code in the interpreter the path is OK:
import sys
sys.path
不幸的是,当我想加载应用程序的主页时,导入 utils 的行引发了异常
Unfortunately, when i want to load the home page of my app the line that imports utils raises an exception
我做错了什么?谢谢你.
What i do wrong? Thanks in advanced.
推荐答案
您的〜/.profile仅将目录添加到当前Shell环境中的PYTHONPATH中.它不是全球可用的.django加载后,将使用wsgi.py和另一个项目路径.
Your ~/.profile only adds the dir to the PYTHONPATH in the current shell environment. It's not globally available. When django loads, it uses the wsgi.py and another project path.
添加全局可用路径的最简单方法是添加.pth文件.它应该在您的python dist-packages目录中(取决于操作系统):
The easiest way to add a globally available path is to add a .pth file. It should be in your python dist-packages directory (depends on the OS):
$ sudo nano /usr/lib/python2.7/dist-packages/
/home/test/src/LIBS
并保存文件.
现在该应用将可用于您计算机上的所有python实例.
Now the app will be available for all python instances on your machine.
如果您只想将此路径添加到特定的django项目,请在wsgi.py中添加:
If you want to add this path only to a specific django project, in the wsgi.py add:
import sys
sys.path.append("/home/test/src/LIBS")
这篇关于PYTHONPATH中的路径不在Django路径中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!