conda虚拟环境的使用

Arthur_1668 / 2024-09-20 / 原文

conda虚拟环境的使用

conda虚拟环境使用前,需要在先安装并且配置好Anaconda。

一、基本使用方法

  1. 创建虚拟环境
conda create -n 虚拟环境名称 python=版本

#例如,创建名为genet的python版本3.11的环境:
conda create -n genet python=3.11
  1. 激活虚拟环境
conda activate 虚拟环境名称
  1. 退出虚拟环境
deactivate
  1. 查看虚拟环境列表
# 两个命令都可以查看虚拟环境列表
conda env list
conda info --envs

  1. 删除环境
conda remove -n xxxxx(环境名字) --all
  #解释:remove表示删除,-n是(name名字的缩写),xxxxx是要删除的虚拟环境的名字,最后的--all如果不加上的话代表删除的是当前环境下的一个包,比如numpy等,加上的话才是删除虚拟环境
  1. 环境重命名
conda rename -n genet fdl
# 以上即为把 genet 重命名为 fdl
  1. 使用虚拟环境打开python文件

    直接在此文件所在目录中输入cmd并回车,然后弹出的命令符就是直接转至这个位置之中。

    随后还要在输入 conda activate 虚拟环境名称打开虚拟环境。(每次打开cmd都要输入)

    然后输入python 文件名称就可以运行python文件了,注意python文件是.py结尾的后缀。

二、镜像源相关

如果用pip安装库的过程中,下载速度特别慢,或者出现红色报错,可以配置镜像源,能使下载速度快很多。

选择其中一种直接复制整条代码然后运行即可,然后再运行pip安装指令速度就很快了。

  1. 清华大学镜像源

    conda config --add channels  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
    conda config --add channels  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free
    conda config --add channels  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/r
    conda config --add channels  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/pro
    conda config --add channels  https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/msys2 
    
  2. 中科大源

    conda config --add channels https://mirrors.ustc.edu.cn/anaconda/pkgs/main/
    conda config --add channels https://mirrors.ustc.edu.cn/anaconda/pkgs/free/
    conda config --add channels https://mirrors.ustc.edu.cn/anaconda/cloud/conda-forge/
    conda config --add channels https://mirrors.ustc.edu.cn/anaconda/cloud/msys2/
    conda config --add channels https://mirrors.ustc.edu.cn/anaconda/cloud/bioconda/
    conda config --add channels https://mirrors.ustc.edu.cn/anaconda/cloud/menpo/
    conda config --add channels https://mirrors.ustc.edu.cn/anaconda/cloud/
    
  3. 临时使用某个源(只用于此条代码)

    在pip install --- 之后加上这些代码即可(分别为中科大源、清华源)
    # 例如安装Numpy库:
    pip install Numpy -i https://pypi.mirrors.ustc.edu.cn/simple/
    pip install Numpy -i https://pypi.tuna.tsinghua.edu.cn/simple
    
  4. 查看已添加的镜像

    conda config --show channels
    
  5. 删除镜像

    # 输入此条指令即可删除所有镜像源,在有时候镜像源出现问题报错时可以删除掉,或者换成其他源.
    conda config --remove-key channels