python venv虚拟环境基础

Last updated on 5 months ago

什么是虚拟环境

相当于给解释器复制了几个副本,在项目中使用这个副本进行包的安装和管理,在项目打包时,可以更方便的导出。对于多个项目也可以使用虚拟环境对环境进行区分,而不需要去更改全局环境。

python使用虚拟环境有多种方法,这里用venv(针对py3),如果有切换py版本的需求,还可以使用pyenv

venv安装

一般不需要安装,在安装python的时候会自带

查看venv help列表

终端输入

1
python -m venv -h

返回结果如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
usage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear] [--upgrade] [--without-pip]
[--prompt PROMPT] [--upgrade-deps]
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.

options:
-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.
--upgrade-deps Upgrade core dependencies: pip setuptools to the latest version in PyPI

Once an environment has been created, you may wish to activate it, e.g. by sourcing an activate script in its bin
directory.

让GPT翻译翻译

  1. –system-site-packages
    • 这个选项允许虚拟环境访问系统的 site-packages 目录,即当前系统 Python 安装的库。默认情况下,虚拟环境是隔离的,不会访问系统安装的包。
  2. –symlinks
    • 当平台默认不是符号链接时,尝试使用符号链接而不是拷贝文件。符号链接可以节省空间并且更改后会同步更新,但不适用于所有平台。
  3. –copies
    • 即使平台默认使用符号链接,也尝试使用拷贝而不是符号链接。这个选项可以确保在所有平台上都使用拷贝,避免符号链接可能带来的兼容性问题。
  4. –clear
    • 如果指定了这个选项,并且目标环境目录已经存在,将会删除目录中的内容,然后重新创建环境。
  5. –upgrade
    • 这个选项用于升级已存在的虚拟环境目录,以适应当前使用的 Python 版本。这在你的系统 Python 升级后,想要更新虚拟环境时非常有用。
  6. –without-pip
    • 如果指定了这个选项,创建虚拟环境时将跳过安装或升级 pip。通常情况下,pip 是默认引导安装的。
  7. –prompt PROMPT
    • 这个选项允许你为虚拟环境提供一个自定义的提示符前缀,用于在激活虚拟环境后显示在命令行界面中。
  8. –upgrade-deps
    • 这个选项用于升级虚拟环境中的核心依赖项,如 pip 和 setuptools,到最新的 PyPI 版本。

创建环境

1
python -m venv <环境名>

创建完成后,当前路径下会出现一个与环境名同名的目录,该目录目录结构如下:

1
2
3
4
<DIR>          Include
<DIR> Lib
pyvenv.cfg
<DIR> Scripts

激活环境

进入到同名目录的Scripts目录下,该目录有一个activate文件,在终端中运行它即可激活环境

1
activate

之后终端的前面有带有一个括号,括号里是环境名,如:

(test) D:\code>

在这个基础上输出pip list查看该环境下的包,可以发现,虚拟环境中并没有我们在真实环境过的包。说明成功了

激活的本质就是修改临时修改环境变量

如果不想激活也可以直接运行Scripts下的python也是可以的,或者是在IDE中指定解释器

复制和保存虚拟环境

在pip中有一个pip list指令,可以查看当前环境安装的包,在通过>可以将结果输出到文件中

1
pip list > requirements.txt

这样就安装的包名与版本输出到文本文件中了

如果想要导入这个文件中的包,可以通过pip install -r <文件名>批量导入

1
pip install -r requirements.txt