PYTHONPATH中的路径不在Django路径中 [英] Path in the PYTHONPATH not in django path

查看:62
本文介绍了PYTHONPATH中的路径不在Django路径中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写基于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 

['','/usr/lib/python2.7','/home/test/src/LIBS','/usr/lib/python2.7/plat-x86_64-linux-gnu','/usr/lib/python2.7/lib-tk','/usr/lib/python2.7/lib-old','/usr/lib/python2.7/lib-dynload','/usr/local/lib/python2.7/dist-packages','/usr/lib/python2.7/dist-packages','/usr/lib/pymodules/python2.7']

['', '/usr/lib/python2.7', '/home/test/src/LIBS', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/pymodules/python2.7']

不幸的是,当我想加载应用程序的主页时,导入 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路径中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆