在python开发应用,我们多数是通过pip、easy_install等工具将需要的python安装到自己机子上就可以应用了,但是我们完成开发给用户使用时,程序运行环境就是一个问题。当然,你可以要求客户按照你的方法安装依赖的库,这种方法在部署趋向自动化的今天就显得机械了。
将库直接放在python安装目录下
# 查看python库的安装路径
$ python -c "from distutils.sysconfig import get_python_lib; print (get_python_lib())"
/usr/lib/python2.7/site-packages# 查看库的路径
$ python -c "import hbase; print hbase.__file__"
/usr/lib/python2.7/site-packages/hbase/__init__.pyc# 查看可执行文件路径
$ python -c "import sys; print sys.executable"
/usr/bin/python
以上我虚拟机上的路径,这样,你开发的python程序无需关注python库的路径了。
.pth文件中添加路径
通过easy_install安装的python,都会将库的路径放在site-packages目录下的easy-install.pth文件中
$ pwd
/usr/lib/python2.7/site-packages
[gongsuo@localhost site-packages]$ cat easy-install.pth
import sys; sys.__plen = len(sys.path)
./supervisor-3.1.3-py2.7.egg
./meld3-1.0.2-py2.7.egg
./Sphinx-1.3.1-py2.7.egg
./sphinx_rtd_theme-0.1.8-py2.7.egg
./alabaster-0.7.6-py2.7.egg
./Babel-2.0-py2.7.egg
./snowballstemmer-1.2.0-py2.7.egg
./docutils-0.12-py2.7.egg
./Pygments-2.0.2-py2.7.egg
./Jinja2-2.8-py2.7.egg
./six-1.9.0-py2.7.egg
./pytz-2015.4-py2.7.egg
./MarkupSafe-0.23-py2.7.egg
./shadowsocks-2.8.2-py2.7.egg
./Fabric-1.10.2-py2.7.egg
./paramiko-1.15.2-py2.7.egg
./ecdsa-0.13-py2.7.egg
./pip-7.1.2-py2.7.egg
import sys; new=sys.path[sys.__plen:]; del sys.path[sys.__plen:]; p=getattr(sys,'__egginsert',0); sys.path[p:p]=new; sys.__egginsert = p+len(new)
同样的我们可以在此目录创建自己的.pth文件,然后把自己所依赖的库或自己开发的库的路径添加到此文件中
动态添加库的路径
import sys
sys.path.append('lib_path')
设置PYTHONPATH环境变量
将python库所在的路径添加到PYTHONPATH环境变量中。
https://github.com/torproject/chutney中实例
$ cat chutney
#!/bin/sh
export PYTHONPATH="`dirname $0`/lib:${PYTHONPATH}"
# Use python2, python, python3 in that order
[ -n "$PYTHON" ] || {command -v python2 >/dev/null 2>&1 && PYTHON=python2 || \command -v python >/dev/null 2>&1 && PYTHON=python # || \
# Not yet supported
# command -v python3 >/dev/null 2>&1 && PYTHON=python3
}
# Use python2 if the checks that use "command" fail
${PYTHON:=python2} -m chutney.TorNet "$@"
chutney作为可执行的shell程序,设置PYTHONPATH环境变量,然后运行对应的程序。
请使用python -h
获取python的一下帮助。
参考
- Windows下Python添加库(模块)路径