Python 虚拟环境venv详解
Python 虚拟环境venv详解

Python 虚拟环境venv详解

通过 venv 操作虚拟环境

Python 3.5 后推荐使用 venv 来创建虚拟环境

创建虚拟环境

1
python3 -m venv fastapi_test

fastapi_test 是虚拟环境名字,可以自定义

激活虚拟环境

1
source <环境名称>/bin/activate

可以看到虚拟环境中的 Package 只有最基础的 pip、setuptools

关闭虚拟环境

1
deactivate

Pycharm 项目关联新创建的虚拟环境

先在项目目录下创建好虚拟环境

Python Interpreter 选中虚拟环境

安装项目所需要的库

Pycharm 创建虚拟环境

  • 选中 Python Interpreter
  • 查看更多 Interpreters
  • 添加一个新的 Interpreters
  • 选择 New environment,默认选项即可,确定

查看虚拟环境的目录

刚刚创建的两个虚拟环境的目录其实是一样的

bin

与虚拟环境交互的文件

1
2
3
4
5
6
7
8
9
10
11
12
>> ll
total 72
-rw-r--r--  1 polo  staff   8.6K Sep 14 09:26 Activate.ps1
-rw-r--r--  1 polo  staff   1.9K Sep 14 09:26 activate
-rw-r--r--  1 polo  staff   882B Sep 14 09:26 activate.csh
-rw-r--r--  1 polo  staff   2.0K Sep 14 09:26 activate.fish
-rwxr-xr-1 polo  staff   269B Sep 14 08:40 pip
-rwxr-xr-1 polo  staff   269B Sep 14 08:40 pip3
-rwxr-xr-1 polo  staff   269B Sep 14 08:40 pip3.9
lrwxr-xr-1 polo  staff     9B Sep 14 08:40 python -> python3.9
lrwxr-xr-1 polo  staff     9B Sep 14 08:40 python3 -> python3.9
lrwxr-xr-1 polo  staff    39B Sep 14 08:40 python3.9 -> /usr/local/opt/python@3.9/bin/python3.9

include

编译 Python 包的 C 头文件

lib

包含Python 版本的副本(python3.9),以及安装每个依赖包的 site-packages 文件夹

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
>> pwd
/Users/polo/Downloads/FastAPI_project/fastapi_test/lib/python3.9/site-packages
>> ll
total 224
drwxr-xr-x   3 polo  staff    96B Sep 14 09:27 __pycache__
drwxr-xr-x   5 polo  staff   160B Sep 14 08:40 _distutils_hack
-rw-r--r--   1 polo  staff   152B Sep 14 08:40 distutils-precedence.pth
drwxr-xr-28 polo  staff   896B Sep 14 09:27 fastapi
drwxr-xr-x   8 polo  staff   256B Sep 14 09:27 fastapi-0.68.1.dist-info
drwxr-xr-x   8 polo  staff   256B Sep 14 08:40 pip
drwxr-xr-10 polo  staff   320B Sep 14 08:40 pip-21.1.1.dist-info
drwxr-xr-x   7 polo  staff   224B Sep 14 08:40 pkg_resources
drwxr-xr-53 polo  staff   1.7K Sep 14 09:27 pydantic
drwxr-xr-x   9 polo  staff   288B Sep 14 09:27 pydantic-1.8.2.dist-info
drwxr-xr-41 polo  staff   1.3K Sep 14 08:40 setuptools
drwxr-xr-11 polo  staff   352B Sep 14 08:40 setuptools-56.0.0.dist-info
drwxr-xr-27 polo  staff   864B Sep 14 09:27 starlette
drwxr-xr-x   8 polo  staff   256B Sep 14 09:27 starlette-0.14.2.dist-info
drwxr-xr-x   8 polo  staff   256B Sep 14 09:27 typing_extensions-3.10.0.2.dist-info
-rw-r--r--   1 polo  staff   107K Sep 14 09:27 typing_extensions.py

从虚拟环境生成 requirement.txt

先看看有哪些包

1
2
3
4
5
6
7
8
9
> pip list
Package           Version
----------------- --------
fastapi           0.68.1
pip               21.1.1
pydantic          1.8.2
setuptools        56.0.0
starlette         0.14.2
typing-extensions 3.10.0.2

pip freeze

在激活虚拟环境下敲

1
pip freeze > requirement.txt 

这样生成的 requirement.txt 文件就只包含虚拟环境中已安装的依赖包了!

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注