Conda 管理虚拟环境
概要: 使用miniconda,管理Python虚拟环境
创建时间: 2022.06.03 20:27:37
更新时间: 2023.07.30 10:11:58
conda获取与配置
Linux
在miniconda页面,下载对应的安装包安装即可。或者使用下面命令直接下载64位python3.9版本的miniconda:
Bash |
---|
| wget https://repo.anaconda.com/miniconda/Miniconda3-py39_4.9.2-Linux-x86_64.sh
|
下载完毕后,首先给予安装包可执行权限:
Bash |
---|
| sudo chmod +x Miniconda3-py39_4.9.2-Linux-x86_64.sh
|
然后按照官方指引,在交互式命令中安装即可:
Bash |
---|
| ./Miniconda3-py39_4.9.2-Linux-x86_64.sh
|
提示
- 如果需要升级覆盖式安装,使用
./Miniconda3-py39_4.9.2-Linux-x86_64.sh -u
命令
- 如果需要静默安装,使用
./Miniconda3-py39_4.9.2-Linux-x86_64.sh -b
命令
安装完成后,终端前面(base) [lzwang@localhost ~]$
会有前缀base
,代表当前使用的是默认的conda环境,检测方式如下:
Bash |
---|
| (base) [lzwang@localhost ~]$ python -V
Python 3.9.1
(base) [lzwang@localhost ~]$ pip -V
pip 20.3.1 from /home/lzwang/miniconda3/lib/python3.9/site-packages/pip (python 3.9)
|
可以看到当前的python和pip已经指向了conda的安装位置。
macOS
在已有brew
环境下,一行命令即可(但更推荐从官网处下载,更新更加及时):
配置conda源
推荐使用 清华大学conda源 提高访问速度
Bash |
---|
| channels:
- defaults
show_channel_urls: true
default_channels:
- https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
- https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/r
- https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/msys2
custom_channels:
conda-forge: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
msys2: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
bioconda: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
menpo: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
pytorch: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
simpleitk: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
|
conda常用命令
查看conda信息
更新conda环境
Bash |
---|
| conda update -n base update conda
|
更新Python
更新/安装指定版本Python
创建指定版本虚拟环境
Bash |
---|
| conda create -n ${your_venv_name} python=x.y.z
|
激活虚拟环境
Bash |
---|
| conda activate ${your_venv_name}
|
反激活虚拟环境
移除虚拟环境
Bash |
---|
| conda env remove -n ${your_venv_name} # -n 即 --name
|
列出conda创建的所有虚拟环境
为特定虚拟环境安装pip包
Bash |
---|
| # 缺省-n的话,默认为当前环境
conda install gitpython -n ${your_venv_name} -y
|
查看conda已安装的包
Bash |
---|
| conda list -n ${your_venv_name} # 缺省-n的话,默认为当前环境
|
在shell启动时默认激活base虚拟环境
Bash |
---|
| conda config --set auto_activate_base true
|
在shell启动时默认不激活base虚拟环境
Bash |
---|
| conda config --set auto_activate_base false
|
从系统中移除miniconda
假定miniconda位置在~/miniconda3
(默认位置)
在PyCharm中使用conda
此处以macOS为例,Linux和Windows与之类似
新建项目时,创建虚拟环境
如下图,选择使用conda创建即可:

为当前项目创建虚拟环境
设置 --> 项目 --> Python解释器 --> 全部显示 --> 新建虚拟环境即可;


参考
- Miniconda — Conda documentation
- anaconda | 镜像站使用帮助 | 清华大学开源软件镜像站 | Tsinghua Open Source Mirror