Ubuntu20.04 多Python版本共存与Virtualenvwrapper创建虚拟环境

Python3.6.8下载与安装

原文参考链接
安装各类依赖工具

sudo apt-get install -y gcc make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev xz-utils tk-dev libffi-dev liblzma-dev

下载源码文件压缩包

wget https://www.python.org/ftp/python/3.6.8/Python-3.6.8.tgz

解压与配置

tar -xzf Python-3.6.8.tgz
cd Python-3.6.8
sudo ./configure --enable-optimizations --prefix=/usr/local/bin/python3.6

–prefix=/usr/local/bin/python3.6:编译的时候用来指定程序存放路径

编译与安装

sudo make
sudo make install

设置软链接

sudo ln -s -f /usr/local/bin/python3.6/bin/python3.6 /usr/bin/python3.6
sudo ln -s -f /usr/local/bin/python3.6/bin/pip3.6 /usr/bin/pip3.6

Virtualenvwrpper虚拟环境配置

默认Python3对应的Virtualenvwrapper安装与使用参考链接

实际上,Python3自带了集成的venv.

venv创建虚拟环境:

指定项目路径(~/proj_doc)并创建虚拟环境

python3.6 -m venv ~/proj_doc

该虚拟环境激活:

source ~/proj_doc/bin/activate

退出虚拟环境

deactivate

在该途径下进行包的pip安装,包会被安装至~/proj_doc/lib/python3.6/site-packages

virtualenvwrapper安装与创建虚拟环境

在本文中采用的思路是为Ubuntu20.04默认的Python3(Python3.8)安装virtualenvwrapper, 并在创建虚拟环境时指定Python版本.

下载与安装virtualenvwrapper

pip3 install virtualenv virtualenvwrapper

设置WORKON路径等:

vim ~/.bashrc

在bashrc中加入下面的内容

# Virtualenvwrapper settings:
export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
export WORKON_HOME=$HOME/.virtualenvs
export VIRTUALENVWRAPPER_VIRTUALENV=$HOME/.local/bin/virtualenv
source $HOME/.local/bin/virtualenvwrapper.sh

virtrualenvwrapper默认将所有的虚拟环境放置于~/.virtualenvs
目录下进行管理.

通过source命令或重新打开终端即可使其生效

source ~/.bashrc

创建虚拟环境

mkvirtualenv venv

指定Python版本进行虚拟环境创建

mkvirtualenv venv6 --python=/usr/local/bin/python3.6/bin/python3.6 

报错情况:

RuntimeError: failed to query /usr/local/bin/python3.6/bin/python3.6 with code 1 err: ' File "/usr/local/lib/python3.8/dist-packages/virtualenv/discovery/py_info.py", line 152\n os.path.join(base_dir, exe) for exe in (f"python{major}", f"python{major}.{minor}")\n ^\nSyntaxError: invalid syntax\n

解决方法:
virtualenv在>=20.22.0后放弃了对<=Python3.6的支持,所以降低virtualenv的版本即可。参考链接

pip3 install virtualenv==20.21.1

`

可根据不同的Python解释器所在路径进行参数的修改

查看环境

workon

切换环境

workon venv6

退出环境

deactivate

删除环境

rmvirtualenv venv6

你可能感兴趣的:(python,linux,开发语言)