在Linux操作系统中,程序运行离不开环境变量的设置。
添加环境变量通常使用export指令,使用export指令时要注意不要覆盖原有指令。
使用export指令之前可以先查看下环境变量中已经存在的条目
比如查看环境变量:
echo ${PATH}
usr/local/cuda-7.5/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/usr/local/cuda-7.5/bin
查看Python环境变量:
echo ${PYTHONPATH}
/home/jhm/mxnet/python:
查看动态链接库路径:
echo ${LD_LIBRARY_PATH}
/usr/local/cuda-7.5/lib64:/usr/local/cuda-7.5/lib64
之后我们打算向系统路径中添加自己的程序路径,该怎么做呢?
比如我们配置了caffe框架,准备使用caffe的Python接口,这时该怎么做呢?
想要不受当前路径的约束,随意使用Python接口,就得把caffe的Python目录添加到PYTHONPATH这条变量下,又知Linux操作系统进入桌面后,打开shell之后会自动加载~/.bashrc 文件,因此我们要把添加环境变量的操作放到~/.bashrc文件中。
向文件中添加内容有两种方法,第一种是
# 使用gedit编辑器打开~/.bashrc文件
sudo gedit ~/.bashrc
# 在文件末尾添加命令
export PYTHONPATH=$PYTHONPATH:/home/jhm/caffe/python
# 保存退出
source ~/.bashrc
当然我更推荐单独写一条变量保存Caffe路径,修改后的命令如下:
# 使用gedit编辑器打开~/.bashrc文件
gedit ~/.bashrc
# 在文件末尾添加命令
export CAFFE_ROOT=/home/jhm/caffe
export PYTHONPATH=${CAFFE_ROOT}/python:$PYTHONPATH
# 保存退出
source ~/.bashrc
我们也可以不打开文件,直接使用文件描述符追加写入:
# 追加写入
echo "export CAFFE_ROOT=/home/jhm/caffe" >> ~/.bashrc
echo "export PYTHONPATH=${CAFFE_ROOT}/python:$PYTHONPATH" >> ~/.bashrc
# source一下,立即生效
source ~/.bashrc
之后我们查看Python路径,看到已经有了/home/jhm/caffe/python条目
echo ${PYTHONPATH}
/home/jhm/caffe/python:/home/jhm/mxnet/python:
试着运行Caffe,载入成功
jhm@jhm-W580I:~$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import caffe
/home/jhm/caffe/python/caffe/pycaffe.py:13: RuntimeWarning: to-Python converter for boost::shared_ptr<caffe::Net<float> > already registered; second conversion method ignored.
from ._caffe import Net, SGDSolver, NesterovSolver, AdaGradSolver,
/home/jhm/caffe/python/caffe/pycaffe.py:13: RuntimeWarning: to-Python converter for boost::shared_ptr<caffe::Blob<float> > already registered; second conversion method ignored.
from ._caffe import Net, SGDSolver, NesterovSolver, AdaGradSolver,
/home/jhm/caffe/python/caffe/pycaffe.py:13: RuntimeWarning: to-Python converter for boost::shared_ptr<caffe::Solver<float> > already registered; second conversion method ignored.
from ._caffe import Net, SGDSolver, NesterovSolver, AdaGradSolver,
>>>