CentOS7创建Python虚拟环境
为python3创建软连接:
ln -s /usr/local/anaconda3/bin/python /usr/bin/python3 ln -s /usr/local/anaconda3/bin/pip /usr/bin/pip3
查看版本:
[root@centos-base ~]# python3 -V Python 3.7.0 [root@centos-base ~]# pip3 -V pip 10.0.1 from /usr/local/anaconda3/lib/python3.7/site-packages/pip (python 3.7)
二、安装虚拟环境
安装virtualenv和virtualenvwrapper:
pip3 install virtualenv pip3 install virtualenvwrapper
添加环境变量:
编辑bashrc文件:
nano ~/.bashrc export WORKON_HOME=$HOME/.virtualenvs export VIRTUALENVWRAPPER_PYTHON=/usr/local/anaconda3/bin/python source /usr/local/anaconda3/bin/virtualenvwrapper.sh
说明:
# WORKON_HOME: 虚拟环境的目录
# VIRTUALENVWRAPPER_PYTHON python目录
# virtualenvwrapper.sh文件目录
运行:
source ~/.bashrc
三、重新打开终端,创建虚拟环境
使用命令创建虚拟环境:
mkvirtualenv venv_1 # 创建一个名为venv_1的虚拟环境 [root@centos-base .virtualenvs]# mkvirtualenv venv_1 Using base prefix '/usr/local/anaconda3' New python executable in /root/.virtualenvs/venv_1/bin/python Installing setuptools, pip, wheel... done. virtualenvwrapper.user_scripts creating /root/.virtualenvs/venv_1/bin/predeactivate virtualenvwrapper.user_scripts creating /root/.virtualenvs/venv_1/bin/postdeactivate virtualenvwrapper.user_scripts creating /root/.virtualenvs/venv_1/bin/preactivate virtualenvwrapper.user_scripts creating /root/.virtualenvs/venv_1/bin/postactivate virtualenvwrapper.user_scripts creating /root/.virtualenvs/venv_1/bin/get_env_details (venv_1) [root@centos-base .virtualenvs]#
可以看到,创建好虚拟环境后,命令提示符前面多了一个(venv_1),表示我们正处于虚拟环境中。
四、操作虚拟环境
1.退出虚拟环境
(venv_1) [root@centos-base bin]# deactivate
[root@centos-base bin]#
2.进入虚拟环境
[root@centos-base bin]# workon venv_1
(venv_1) [root@centos-base bin]#
或者:
[root@centos-base ~]# cd ~/.virtualenvs/venv_1/bin
[root@centos-base bin]# source activate
3.查看虚拟环境
[root@centos-base bin]# lsvirtualenv
venv_1
======
4.删除虚拟环境
[root@centos-base bin]# rmvirtualenv venv_1
Removing venv_1...
5.避免PIP误装
当我们未处于虚拟环境的时候,使用PIP安装的包会被安装在系统python中。为了避免这种情况的发生,可以进行以下配置:
在~/.bashrc中添加:
export PIP_REQUIRE_VIRTUALENV=true source ~/.bashrc
然后,再在系统环境执行pip的时候:
[root@centos-base bin]# pip3 install redis Could not find an activated virtualenv (required).