The Road to Python 1 Conda and Poetry

Guidance on creating a clean & isolated Python environment

Posted by Huajian on August 18, 2022
Viewed times

Reference - Conda & Poetry

Reference - Conda 操作

Reference - Poetry/Reference - Poetry(Chinese Version)

序言

在这篇文章中,我想介绍如何使用Conda以及Poetry管理项目环境。
我们使用Conda实现Ptyhon多版本的管理
使用Poetry实现Ptyhon项目的依赖包管理

Conda:环境(env)管理

  • 安装Minconda
    wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh 
    bash Miniconda3-latest-Linux-x86_64.sh
    
  • 第一次安装时使用 source ~/.bashrc 激活base环境

  • 使用conda config --set auto_activate_base false 关闭base环境的自动激活

  • 创建虚拟环境
    conda create -n your_env_name python=3.9 
    
  • 激活虚拟环境
    conda activate your_env_name
    
  • 退出虚拟环境
    conda deactivate your_env_name
    
  • 删除环境(如果需要)
    conda remove -n your_env_name --all
    
  • 如果需要的话
    • 在虚拟环境中使用conda env export > environment.yml 导出虚拟环境
    • 在base环境中使用conda env export -n ENVNAME > environment.yml 导出虚拟环境
    • 也可以用conda env export --from-history > environment.yml 仅导出包,不导出依赖包
  • 使用conda env create -f environment.yaml 重新生成环境

Poetry: 依赖(dependence)管理

  • 安装Poetry
    curl -sSL https://install.python-poetry.org | python3 -
    
  • export PATH="$HOME/.local/bin:$PATH" 加入.bashrc
    echo 'export PATH="$HOME/.local/bin:$PATH"'>> ~/.bashrc
    source ~/.bashrc
    
  • 全局关闭poetry的创建虚拟环境,注意此时不要在conda环境中
    poetry config virtualenvs.create false
    
  • 关于Poetry的操作见Reference - Poetry(Chinese Version),这里只提及与conda的协作

pyporject.toml

  • 这是poetry最重要的文件之一,一个基本的pyproject.toml 如下所示

      # pyproject.toml  
        
      [tool.poetry]  
      name = "rp-poetry"  
      version = "0.1.0"  
      description = ""  
      authors = ["Philipp <philipp@realpython.com>"]  
        
      [tool.poetry.dependencies]  
      python = "^3.9"  
        
      [tool.poetry.dev-dependencies]  
      pytest = "^5.2"  
        
      [build-system]  
      requires = ["poetry-core>=1.0.0"]  
      build-backend = "poetry.core.masonry.api"
    
  • 在激活了conda以后

    • [tool.poetry.dependencies]添加需要的包 / 使用 poetry add <package name> 添加包
    • 使用poetry lock 锁定依赖
    • 使用poetry install 安装依赖
    • 使用poetry show 查看
      此时所有的poetry依赖将都安装在当前conda环境内,对外部不会有影响

总结

使用Conda + Poetry的方式,可以根据Python的版本管理不同的依赖


Top
Down