一、准备CentOS7系统
参照:https://www.cnblogs.com/leokale-zz/p/11643822.html
安装Anaconda到/usr/local/anaconda3目录下。
为python3创建软连接:
ln -s /usr/local/anaconda3/bin/python /usr/bin/pyhon3 ln -s /usr/local/anaconda3/bin/pip /usr/bin/pip3
查看版本:
[[email protected] ~]# python3 -V Python 3.7.0
[[email protected] ~]# 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 export WORKON_HOME=$HOME/.virtualenvs export VIRTUALENVWRAPPER_PYTHON=/usr/local/anaconda3/bin/python source /usr/local/anaconda3/bin/virtualenvwrapper.sh
source ~/.bashrc
三、创建虚拟环境
使用命令创建虚拟环境:
mkvirtualenv venv_1 # 创建一个名为venv_1的虚拟环境
[[email protected]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) [[email protected]-base .virtualenvs]#
可以看到,创建好虚拟环境后,命令提示符前面多了一个(venv_1),表示我们正处于虚拟环境中。
四、操作虚拟环境
1.退出虚拟环境
(venv_1) [[email protected]base bin]# deactivate [[email protected]-base bin]#
2.进入虚拟环境
[[email protected]base bin]# workon venv_1 (venv_1) [[email protected]-base bin]# 或者: [[email protected]-base ~]# cd ~/.virtualenvs/venv_1/bin [[email protected]-base bin]# source activate
3.查看虚拟环境
[[email protected]base bin]# lsvirtualenv venv_1 ======
4.删除虚拟环境
[[email protected]base bin]# rmvirtualenv venv_1 Removing venv_1...
5.避免PIP误装
当我们未处于虚拟环境的时候,使用PIP安装的包会被安装在系统python中。为了避免这种情况的发生,可以进行以下配置:
在~/.bashrc中添加:
export PIP_REQUIRE_VIRTUALENV=true
source ~/.bashrc
然后,再在系统环境执行pip的时候:
[[email protected] bin]# pip3 install redis Could not find an activated virtualenv (required).
*(^_ ^)**!
原文地址:https://www.cnblogs.com/leokale-zz/p/12155852.html
时间: 2024-11-03 01:57:45