为Python添加默认模块搜索路径

来源:互联网 发布:数据决策分析系统 编辑:程序博客网 时间:2024/06/10 03:34

PYTHON 路径添加 

近期python 学习的一些总结:添加路径到sys.path

如何将路径“永久"添加到sys.path?

sys.path是python的搜索模块的路径集,是一个list

可以在python 环境下使用sys.path.append(path)添加相关的路径,但在退出python环境后自己添加的路径就会自动消失了!

可以使用以下命令输入当前python 的搜索路径:

python -c"import sys;print '当前的python是:'+sys.prefix;print '\n'.join(sys.path)"

练习使用sys.path.append方法添加路径,显示退出python会消失!

python -c"import sys;print '当前的python是:'+sys.prefix;sys.path.append(r'E:\DjangoWord');print '\n'.join(sys.path)"

再次运行,会发现 自己添加路径E:\DjangoWord()不存在了!

python -c"import sys;print '当前的python是:'+sys.prefix;print '\n'.join(sys.path)"

为解决这个问题,可以有以下方法:

PYTHON 路径添加  转载 - lacus_kira - 懵懵懂懂走一生
将自己做的py文件放到 site_packages 目录下:

下面命令显示了 site-packages 目录:

python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()"

 但是这样做会导致一个问题,即各类模块都放到此文件夹的话,会导致乱的问题,这一点是显而易见的。

 注意,也不创建子文件夹,再将自己的模块放到子文件夹解决问题,这会导致使用import 语句时错误。

PYTHON 路径添加  转载 - lacus_kira - 懵懵懂懂走一生
使用pth文件,在 site-packages 文件中创建 .pth文件,将模块的路径写进去,一行一个路径,以下是一个示例,pth文件也可以使用注释:

# .pth file for the  my project(这行是注释)
E:\DjangoWord
E:\DjangoWord\mysite
E:\DjangoWord\mysite\polls

这个不失为一个好的方法,但存在管理上的问题,而且不能在不同的python版本中共享。

PYTHON 路径添加  转载 - lacus_kira - 懵懵懂懂走一生
使用PYTHONPATH环境变量,在这个环境变量中输入相关的路径,不同的路径之间用逗号(英文的!)分开,如果PYTHONPATH 变量还不存在,可以创建它!如下图所示:

PYTHON 路径添加  转载 - lacus_kira - 懵懵懂懂走一生

这里的路径会自动加入到sys.path中,而且可以在不同的python版本中共享,应该是一样较为方便的方法。

关于与python相关的环境变量有那些,请参考:

http://docs.python.org/using/cmdline.html  在页面上找到PYTHONPATH

PYTHON 路径添加  转载 - lacus_kira - 懵懵懂懂走一生
以下是该环境变量的描述:

PYTHONPATH?

Augment the default search path for module files. The format is the same as the shell’s PATH: one or more directory pathnames separated by os.pathsep (e.g. colons on Unix or semicolons on Windows). Non-existent directories are silently ignored.

In addition to normal directories, individual PYTHONPATHentries may refer to zipfiles containing pure Python modules (in either source or compiled form). Extension modules cannot be imported from zipfiles.

The default search path is installation dependent, but generally begins with prefix/lib/pythonversion (see PYTHONHOME above). It is always appended to PYTHONPATH.

An additional directory will be inserted in the search path in front of PYTHONPATH as described above under Interface options. The search path can be manipulated from within a Python program as the variable sys.path.

0 0