方法一:函数添加
1 import sys
2 查看sys.path
3 添加sys.path.append("c:\\")
方法二:修改环境变量
w用户可以修改系统环境变量PYTHONPATH
方法三:增加.pth文件,推荐!
在site-packages添加一个路径文件,如mypkpath.pth,必须以.pth为后缀,写上你要加入的模块文件所在的目录名称就是了。
1 windows
c:\python27\site-packages
# 我们的学员把pth文件直接放在c:\python27
# (或其他python安装目录)目录下测试也是有效的
# 2015.9.23
2 linux(ubuntu)
/usr/local/lib/python2.7/dist-packages (note by shanql, 我是放在这个目录下有效的,所添加的目录一定要存在,不存在则会不成功)
2 linux(redhat)
/usr/lib/python2.7/site-packages
学习python不久,碰到个问题,怎么样把自己写的模块加入到python默认就有的搜索路径中呢?不要每次非得import sys; sys.path.append(‘/home/fightlikekobe/python’)才可。
上网找了很多久未果,都来我自己糊里糊涂找到了解决方法,那就是在dist-packages(即/usr/local/lib/python2.7/dist-packages)添加一个路径文件,如mypkpath.pth,必须以.pth为后缀,写上你要加入的文件名称就是了,如我的:
/home/fightlikekobe/python
保存退出,OK!结果自己验证,重启terminal,再次打开python,
>>> import sys
>>> sys.path
['/home/fightlikekobe', '/usr/bin', '/usr/local/lib/python2.7/dist-packages/pymysql_sa-1.0-py2.7.egg', '/usr/local/lib/python2.7/dist-packages/PyMySQL-0.5-py2.7.egg', '/usr/local/lib/python2.7/dist-packages/hiredis-0.1.0-py2.7-linux-i686.egg', '/usr/local/lib/python2.7/dist-packages/SQLAlchemy-0.7.3-py2.7-linux-i686.egg', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/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/local/lib/python2.7/dist-packages', '/home/fightlikekobe/python', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PIL', '/usr/lib/python2.7/dist-packages/gst-0.10', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.7', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client', '/usr/lib/python2.7/dist-packages/ubuntuone-client', '/usr/lib/python2.7/dist-packages/ubuntuone-control-panel', '/usr/lib/python2.7/dist-packages/ubuntuone-couch', '/usr/lib/python2.7/dist-packages/ubuntuone-installer', '/usr/lib/python2.7/dist-packages/ubuntuone-storage-protocol', '/usr/lib/python2.7/dist-packages/wx-2.8-gtk2-unicode']