如何利用pyenv 和virtualenv 在单机上搭建多版本python 虚拟开发环境

时间:2023-03-09 22:23:31
如何利用pyenv 和virtualenv 在单机上搭建多版本python 虚拟开发环境

pyenv 和virtualenv分别是干什么的?

pyenv帮助你在一台机上建立多个版本的python环境, 并提供方便的切换方法。

virtualenv则就是将一个目录建立为一个虚拟的python环境, 这样的话, 用户可以建立多个虚拟环境, 每个环境里面的python版本可以是不同的, 也可以是相同的, 而且环境之间相互独立。

pyenv安装: https://github.com/yyuu/pyenv#choosing-the-python-version

pyenv命令: https://github.com/yyuu/pyenv/blob/master/COMMANDS.md

pyenv virtualenv插件安装: https://github.com/yyuu/pyenv-virtualenv

pyenv commands

Lists all available pyenv commands.

不同python版本间的切换使用

  • pyenv local version or --unset 在一个文件夹下创建.python-version隐藏文件,下次再进入该文件夹将直接使用其中写的python版本。
  • pyenv global version or --unset
  • pyenv shell version,version or --unset

pyenv version

Displays the currently active Python version, along with information on how it was set.

pyenv versions

Lists all Python versions known to pyenv, and shows an asterisk next to the currently active version.以*开头的表示当前使用的版本。

pyenv which

Displays the full path to the executable that pyenv will invoke when you run the given command. 必须是先切换(pyenv local 2.7.8)到该版本下才能查看。

$ pyenv which python2.7(我是用pyenv安装的2.7.8版本)
/home/zxpo/.pyenv/versions/3.3.3/bin/python2.7

pyenv rehash

Installs shims for all Python binaries known to pyenv (i.e., ~/.pyenv/versions/*/bin/*). Run this command after you install a new version of Python, or install a package that provides binaries.

$ pyenv rehash 

1、查看可以安装的版本

pyenv install -l

2、安装python2.7.8

pyenv install 2.7.8

pyenv uninstall 2.7.8

如果失败参考: https://github.com/yyuu/pyenv/wiki/Common-build-problems

3、创建一个使用指定版本python虚拟环境(注意:python-version必须是pyenv安装的版本)

pyenv virtualenv python-version virtual-env-name (如pyenv virtualenv 2.7.8 winingcpi)

4、创建一个使用当前python版本的虚拟环境

pyenv virtualenv virtual-env-name

5、激活虚拟环境(注意这个虚拟环境必须是pyenv创建的)

pyenv activate virtual-env-name (如显示 pyenv activate winingcpi)

在虚拟环境中安装pip,可直接运行easy_install pip

6、退出虚拟环境

pyenv deactivate

7 、显示已存在的虚拟环境

pyenv virtualenvs (如显示 winingcpi)

Delete existing virtualenv

Removing the directories in ~/.pyenv/versions and ~/.pyenv/versions/{version}/envs will delete the virtualenv, or you can run:

pyenv uninstall my-virtual-env