python 构建开发环境

在使用 conda 管理开发库的时候,对于 Python 包的管理,conda 命令本身不如 poetry 好用,所以查看了相关的资料,决定使用 conda 来管理环境,使用 poetry 来管理 Python 的包。

poetry 管理 Python 依赖

安装

可以通过包管理器来安装 poetry 包

conda install -c conda-forge -n base poetry

也可以使用 brew 命令来安装:

brew install poetry

安装好之后,还需要引入到 shell 环境中,zsh 需要配置 $ZSH_CUSTOM/plugins.zshrc 文件。

mkdir $ZSH_CUSTOM/plugins/poetry
poetry completions zsh > $ZSH_CUSTOM/plugins/poetry/_poetry
plugins = (... poetry ...)

然后重新加载 .zshrc 即可。

如果使用 poetry 来管理存在的项目,需要使用 poetry init 来启用,如果想通过 poetry 来管理环境的话,就需要使用 poetry new project_name ,2 个操作都会生成一个新建 pyproject.toml 文件用来管理项目的引用。

与 pip 命令不同, poetry 有点类似于 yarn 是使用 add 进行依赖的添加的。 poetry add pandas

而在执行项目的时候,可以使用 poetry run python xxx.py 来运行代码,如果想进行测试,则利用 poetry run pytest 来执行,当然使用的命令取决于使用测试框架,可以是 pytest ,也可以是 black 。

poetry 可以指定依赖分组,用来增加项目可控性,比如测试的代码,可以增加测试组来指定依赖,命令如下:

poetry add pytest --group test

这样命令就可以向 project.toml 文件中增加 [tool.poetry.group.test.dependencies] ,同样的道理,也可以通过这个方法,增加开发使用到的库或者实际项目使用的库,这样就可以用 npm 一样,拆分不同的依赖组了。

除了上面的方法,也可以通过 --with--without 来看来分组,比如 poetry install --with docs, test 就可以增加 docs 和 test 分组,而使用 poetry install --without test 就可以移除 test 分组。

另外,poetry 利用 remove 方法来移除对应在依赖,比如 poetry remove pytest --group test 就可以从 test 依赖中将 pytest 包移除了。

poetry 关闭虚拟环境

因为是使用 conda 管理开发环境,所以在使用的时候,需要配置关闭 poetry 的环境管理的内容。

poetry config virtualenvs.create false

在使用的时候,还需要具体的确认一下,环境的信息:

poetry env info

展示的信息如下:

Virtualenv
Python:         3.9.15
Implementation: CPython
Path:           /usr/local/Caskroom/miniconda/base/envs/backtrader
Executable:     /usr/local/Caskroom/miniconda/base/envs/backtrader/bin/python
Valid:          True

示例

environment.yml

name: base
channels:
  - conda-forge
  - defaults
dependencies:
  - python=3.9.15=h709bd14_0_cpython
  - poetry=1.1.15=pyhd8ed1ab_1

backtrader.toml

name: backtrader
channels:
  - conda-forge
  - defaults
dependencies:
  - numpy=1.23.4=py39hdfa1d0c_1
  - openssl=1.1.1s=hfd90126_0
  - pip=22.2.2=py39hecd8cb5_0
  - python=3.9.15=hdfd78df_0
  - pip:
    - akshare==1.3.76
    - backtrader==1.9.76.123