通过 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
|
>> lltotal 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-x 1 polo staff 269B Sep 14 08:40 pip-rwxr-xr-x 1 polo staff 269B Sep 14 08:40 pip3-rwxr-xr-x 1 polo staff 269B Sep 14 08:40 pip3.9lrwxr-xr-x 1 polo staff 9B Sep 14 08:40 python -> python3.9lrwxr-xr-x 1 polo staff 9B Sep 14 08:40 python3 -> python3.9lrwxr-xr-x 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>> lltotal 224drwxr-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.pthdrwxr-xr-x 28 polo staff 896B Sep 14 09:27 fastapidrwxr-xr-x 8 polo staff 256B Sep 14 09:27 fastapi-0.68.1.dist-infodrwxr-xr-x 8 polo staff 256B Sep 14 08:40 pipdrwxr-xr-x 10 polo staff 320B Sep 14 08:40 pip-21.1.1.dist-infodrwxr-xr-x 7 polo staff 224B Sep 14 08:40 pkg_resourcesdrwxr-xr-x 53 polo staff 1.7K Sep 14 09:27 pydanticdrwxr-xr-x 9 polo staff 288B Sep 14 09:27 pydantic-1.8.2.dist-infodrwxr-xr-x 41 polo staff 1.3K Sep 14 08:40 setuptoolsdrwxr-xr-x 11 polo staff 352B Sep 14 08:40 setuptools-56.0.0.dist-infodrwxr-xr-x 27 polo staff 864B Sep 14 09:27 starlettedrwxr-xr-x 8 polo staff 256B Sep 14 09:27 starlette-0.14.2.dist-infodrwxr-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 listPackage Version----------------- --------fastapi 0.68.1pip 21.1.1pydantic 1.8.2setuptools 56.0.0starlette 0.14.2typing-extensions 3.10.0.2 |
pip freeze
在激活虚拟环境下敲
|
1
|
pip freeze > requirement.txt |

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