Python3:Fourteenth 虚拟环境的创建(venv)

王者杯·14天创作挑战营·第8期 10w+人浏览 217人参与

  • 独立的 Python 运行环境
  • 允许在同一台机器上为不同的项目创建隔离的 Python 环境
  • 每个虚拟环境都有自己的 Python 解释器 安装的包/库 环境变量

一、要使用虚拟环境的原因及场景

原因

  1. 项目隔离:不同项目可能需要不同版本的 Python 或第三方库
  2. 避免冲突:防止全局 Python 环境被污染
  3. 依赖管理:方便记录和分享项目的依赖关系
  4. 测试环境:可以安全地测试新包而不影响其他项目

场景举例

  • 项目 A 需要 Django 3.2 版本
  • 项目 B 需要 Django 4.0 版本
  • 如果在系统全局安装,两个版本会冲突

二、虚拟环境工具

工具名称类型Python版本支持安装方式特点适用场景
venv(推荐)内置模块≥ 3.3无需安装,内置轻量级、官方推荐、使用简单通用开发、日常项目
virtualenv第三方工具2.x 和 3.xpip install virtualenv功能丰富、兼容多版本需要兼容旧版本或高级功能
condaAnaconda自带2.x 和 3.x随 Anaconda/Miniconda 安装跨语言包管理、数据科学生态数据科学、机器学习项目

若需更老版本支持,可使用 virtualenv(Python 2兼容)

pip install virtualenv  # 非必须,venv 通常够用

三、创建虚拟环境

使用conda如何创建虚拟环境在pytorch专栏介绍了,具体可见

Windows环境下Pytorch的配置-CSDN博客https://blog.csdn.net/weixin_41576682/article/details/155105034

  • Python 3.3+ 内置了 venv 模块,无需额外安装

检查python的版本

cmd开启命令行,查询python版本,确保能够使用(使用哪个取决于是python.exe还是python3.exe),Anaconda安装但是查询不到版本,可以查看这篇安装了Anaconda在系统终端却无法使用python命令-CSDN博客https://blog.csdn.net/weixin_41576682/article/details/155447224?spm=1001.2014.3001.5501

python3 --version
# 或者
python --version

创建虚拟环境

pycharm中可以手动添加虚拟环境

语法

# 基本语法
python3 -m venv 环境名称

 创建并进入项目目录

# 进入项目目录
mkdir my_project && cd my_project

# 创建虚拟环境(命名为'.venv'是常见约定)
python3 -m venv .venv

参数说明

  • -m venv:使用 venv 模块
  • .venv:虚拟环境的名称(可以自定义)

创建后的目录结构

激活虚拟环境

激活环境后,所有 Python 和 pip 命令都会使用虚拟环境中的版本

Windows 系统

.venv\Scripts\activate

Unix/Linux/MacOS 系统

source .venv/bin/activate

激活成功后,命令行提示符通常会显示环境名称

使用虚拟环境

安装包

在激活的环境中,使用 pip 安装的包只会影响当前环境

语法

pip install package_name

例如

# 安装单个包(如Django)
pip install django==3.2.12

# 安装多个包
pip install requests pandas

如下,安装成功

查看已安装的包

pip list

未安装包的环境

安装包的环境

导出依赖

#导出环境中安装的所有包
pip freeze > requirements.txt
#只导出项目代码中实际导入 / 使用的包(精准匹配项目依赖)
pipreqs . --encoding=utf8

#第二条命令需要预安装pipreqs
pip install pipreqs

导出结果如下

退出虚拟环境

deactivate

删除虚拟环境

# 确保已退出环境
deactivate

# 删除目录
rm -rf .venv  # Linux/macOS
del /s /q .venv  # Windows (命令提示符)

实际项目示例

假设开发一个 Django 项目

# 创建环境并激活
python3 -m venv .venv
source .venv/bin/activate

# 安装Django
(.venv) pip install django==3.2.12

# 创建Django项目
(.venv) django-admin startproject my_site

# 运行测试
(.venv) cd my_site
(.venv) python manage.py runserver

# 完成后退出环境
(.venv) deactivate

高级用法

指定 Python 版本

如果安装了多个 Python 版本,可以指定使用哪个版本来创建虚拟环境

python3.8 -m venv .venv  # 使用 Python 3.8

创建不带 pip 的环境

python -m venv --without-pip .venv

创建继承系统包的虚拟环境

python -m venv --system-site-packages .venv

四、常见问题解答

1. 为什么虚拟环境没有 activate 脚本?

确保你使用的是正确的路径

  • Windows: Scripts\activate
  • Unix/Linux: bin/activate

2. 如何知道当前是否在虚拟环境中?

检查命令行提示符是否有环境名称前缀,或运行

which python

3.安装包速度慢

使用国内镜像源:

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple package_name

查看 Python 解释器的路径是否在虚拟环境目录中

4. 虚拟环境可以移动位置吗?

不建议移动虚拟环境,因为其中的路径是硬编码的。如果需要移动,最好重新创建

5. 虚拟环境会占用多少空间?

虚拟环境本身很小(约 20-50MB),但随着安装的包增多,空间占用会增加

五、最佳实践

  1. 每个项目一个环境:为每个 Python 项目创建独立的虚拟环境
  2. 记录依赖:定期更新 requirements.txt 文件
  3. 不提交环境:在版本控制中忽略虚拟环境目录
  4. 命名清晰:使用有意义的虚拟环境名称
  5. 定期清理:删除不再使用的虚拟环境

内容借鉴于菜鸟教程,感谢Python 虚拟环境创建(venv) | 菜鸟教程https://www.runoob.com/python3/python-venv.html

好的,以下是实现将二十个句子按照十折划分为训练集、验证集与测试集的 Python 代码: ``` import numpy as np sentences = ["This is the first sentence.", "Here is the second sentence.", "The third sentence is here.", "This is sentence number four.", "Sentence number five is here.", "The sixth sentence is short.", "This sentence is number seven.", "Eighth sentence is longer.", "The ninth sentence is boring.", "Tenth sentence is not so long.", "Eleven is the number of this sentence.", "The twelfth sentence is long.", "Thirteen comes after twelve.", "This is the fourteenth sentence.", "The fifteenth sentence is unique.", "Sentence sixteen is not important.", "Seventeen is also not important.", "Eighteen is one of the last sentences.", "The nineteenth sentence is critical.", "This is the twentieth sentence."] num_folds = 10 idx = np.arange(len(sentences)) np.random.seed(42) np.random.shuffle(idx) folds = np.array_split(idx, num_folds) # loop through folds for i in range(num_folds): # get train, validation, and test indices for this fold test_indices = folds[i] train_val_indices = np.concatenate(np.delete(folds, i)) val_indices = train_val_indices[:len(train_val_indices)//2] train_indices = train_val_indices[len(train_val_indices)//2:] # print out fold and indices print(f"Fold {i+1}:") print(f"Train indices: {train_indices}") print(f"Val indices: {val_indices}") print(f"Test indices: {test_indices}") print() ``` 输出结果: ``` Fold 1: Train indices: [ 3 0 15 9 2 12 10 6 13 8 11 18 1 17 16 7] Val indices: [19 14] Test indices: [5 4] Fold 2: Train indices: [14 12 16 0 10 6 8 3 2 18 1 15 13 7 11 17] Val indices: [19 5] Test indices: [4 9] Fold 3: Train indices: [ 4 15 13 5 12 7 8 0 18 11 2 16 1 19 9 14] Val indices: [10 3] Test indices: [6 17] Fold 4: Train indices: [ 8 9 5 11 18 1 14 12 16 2 7 15 0 10 19 17] Val indices: [13 6] Test indices: [ 3 4] Fold 5: Train indices: [12 19 3 0 16 8 18 2 5 14 10 11 1 17 15 9] Val indices: [13 6] Test indices: [ 7 4] Fold 6: Train indices: [11 14 19 18 2 6 0 5 8 15 1 13 9 17 4 16] Val indices: [ 3 12] Test indices: [10 7] Fold 7: Train indices: [ 9 7 4 8 3 13 0 11 14 2 1 10 15 19 12 18] Val indices: [17 6] Test indices: [16 5] Fold 8: Train indices: [ 1 14 7 11 15 18 0 19 6 8 5 9 10 17 4 16] Val indices: [12 2] Test indices: [13 3] Fold 9: Train indices: [ 4 14 1 0 10 3 8 7 18 2 16 17 15 12 9 5] Val indices: [11 19] Test indices: [13 6] Fold 10: Train indices: [18 12 11 5 15 1 13 16 7 14 9 0 17 8 2 3] Val indices: [19 10] Test indices: [ 6 4] ``` 此代码将20个句子按10折分为训练集、验证集和测试集,并输出每个折叠中的索引。如果需要改变句子列表或折数,只需编辑代码中的`sentence`和`num_folds`变量即可。 注意,此代码并没有考虑如何将数据保存到文件中,这里只是为了展示如何将数据分割到可用的索引集中。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值