Python3-venv虚拟环境

原来使用conda 管理虚拟环境,但其过于臃肿,并且同时使用conda 和pip 安装过包之后更新总会出点问题,so上也找不到完美解决方案,所以就舍弃了anaconda,使用原生python了。

本文是我在家里windows系统下的设置,平时工作的linux系统中因为不怎么需要更新,所以仍保留anaconda. 两个系统下的配置除了环境变量激活方式外没有太大的区别。

配置

确定本地虚拟环境安装的地址(下文中以"/path/to/virtual/environment"表示)。

然后输入

python3 -m venv /path/to/virtual/environment

此命令会创建指定的目录,包括任何不存在的上次目录。除此之外会在指定目录中创建pyvenv.cfg文件,其中包括一个home字段,其指向运行这个命令的Python的安装目录。此命令还会创建一个Scripts子目录(在Linux中是bin),其中包含了根据创建虚拟环境时设定的参数而配置的二进制文件的拷贝或链接。此命令还会创建一个初始为空的Lib\site-packages子目录(在Linux中是lib/pythonX.Y/site-packages),如果创建时指定了一个已存在的目录,则会将其复用。

配置参数

PS C:\Users\no> python -m venv -h
usage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear] [--upgrade] [--without-pip] [--prompt PROMPT] ENV_DIR [ENV_DIR ...]

Creates virtual Python environments in one or more target directories.

positional arguments:
  ENV_DIR               A directory to create the environment in.

optional arguments:
  -h, --help            show this help message and exit
  --system-site-packages
                        Give the virtual environment access to the system site-packages dir.
  --symlinks            Try to use symlinks rather than copies, when symlinks are not the default for the platform.
  --copies              Try to use copies rather than symlinks, even when symlinks are the default for the platform.
  --clear               Delete the contents of the environment directory if it already exists, before environment creation.
  --upgrade             Upgrade the environment directory to use this version of Python, assuming Python has been upgraded in-place.
  --without-pip         Skips installing or upgrading pip in the virtual environment (pip is bootstrapped by default)
  --prompt PROMPT       Provides an alternative prompt prefix for this environment.

激活虚拟环境

完成虚拟环境的创建后,输入以下命令激活虚拟环境

\path\to\virtual\environment\Scripts\activate.bat

or

\path\to\virtual\environment\Scripts\Activate.ps1

可在官方文档中查阅不同平台不同shell的激活方法。

多版本设置

venvanaconda相比,提供的是相同python版本的不同运行环境,而不是不同版本的环境。因此如果需要不同版本的切换,可先安装指定版本的python,再在创建虚拟环境时指定对应的版本即可。

end

还有一些详细设置,可参照上文中的配置参数。

posted @ 2020-08-03 02:21  Tajangbay  阅读(753)  评论(0编辑  收藏  举报