venv 环境管理、pip 环境管理

1、venv 环境管理

venv 虚拟环境

  • 虚拟环境是什么
  • 虚拟环境的用途
  • venv & virtualenv

venv 虚拟环境的优点

  • 独立的 Python 环境,不会产生冲突
  • 有助于包的管理
  • 删除和卸载方便

venv 使用方法

  • 创建虚拟环境
  • 激活虚拟环境
  • 安装 Python 包

venv 创建虚拟环境

  • 执行指令
python3 -m venv test

venv 激活虚拟环境

  • 切换指定文件夹
    • Windows:/Scripts/
    • macOS:/bin/
  • 执行指令:activate
# Windows 系统激活虚拟环境
cd test
cd Scripts
activate

# macOS系统激活虚拟环境
cd test
cd bin
source actiavte
# 或者一步到位
source ./test/bin/activate

venv 安装 Python 包

  • Python 版本选择
    • 进入 python2.7 环境:python2
    • 进入 python3.x 环境: python3
  • pip 安装 Python 包
    • 安装 Python2.x 版本的包
    • 安装 Python3.x 版本的包
# 进入 python2.7 环境
python2

# 进入 python3.x 环境
python3

# 安装 Python2.x 版本的包
pip install xxx

# 安装 Python3.x 版本的包
pip3 install xxx

venv 退出和删除

  • 退出虚拟环境:deactivate
  • 删除虚拟环境:删除环境目录
# Windows和macOS通用的退出指令
deactivate

2、pip 环境管理

pip 环境管理

  • pip 是什么
  • pip 常用指令
  • pip 管理 Python 包
  • pip 使用镜像加速

pip 概述

  • pip 是 Python 包管理工具
    • python2 的 2.7.9 版本开始自带
    • python3 的 3.4 版本开始自带
  • https://pypi.org/ 托管了大量流行的 Python 包

pip 常用命令

功能 指令
查看 pip 版本 pip -V
查看帮助文档 pip help
查看包列表 pip list
导出包列表 pip freeze
安装 pip install 包名
升级 pip install -U 包名
卸载 pip uninstall 包名

pip 安装包

  • 普通安装
  • 指定版本
  • 从文件中安装
# 默认安装最新版本
$ pip install pytest

# 执行版本
$ pip install pytest==6.2.0

# 从文件清单中批量安装
$ pip install -r requirments.txt

# 文件格式
pytest==6.2.0
Faker==9.3.1
selenium==3.14.1

pip 升级包

  • 升级已安装的 Python 包
$ pip install -U pytest

pip 卸载包

  • 卸载 Python 包
# 卸载包

$ pip uninstall pytest

pip 使用镜像加速

  • pip install -i 镜像源
  • 国内常用源
    • 阿里源:https://mirrors.aliyun.com/pypi/simple/
    • 清华源:https://pypi.tuna.tsinghua.edu.cn/simple/
    • 豆瓣源:http://pypi.douban.com/simple/
# 使用镜像

pip install pytest -i https://pypi.douban.com/simple