Python Poetry 入门教程(代码依赖管理)

Python

Poetry 的历史

Poetry 是一个Python依赖项管理工具。

这里提到了开发 Poetry 的主要原因 项目 readme.

Python中的打包系统和依赖性管理相当复杂,对于新手来说很难理解。即使对于经验丰富的开发人员,有时创建Python项目所需的所有文件也可能很麻烦:setup.py, requirements.txt, setup.cfg, MANIFEST.in 和新添加的 Pipfile.

确实有很多我们应该考虑的文件,例如:

  • setup.py
  • requirements.txt
  • setup.cfg
  • MANIFEST.in
  • Pipfile and Pipfile.lock (pipenv)

为了解决这种混乱的情况,Poetry 提供了一个 pyproject.toml 文件来管理所有依赖项。

接下来,我们将对其进行设置!

配置 Poetry

要求

  • Python 2.7 or 3.4+。

我将在本文中使用Python 3.6.0。

$ python --version
Python 3.6.0

下载安装

通过提供的安装程序安装Poetry。

$ curl -sSL https://raw.githubusercontent.com/sdispater/poetry/master/get-poetry.py | python
Retrieving Poetry metadata

# Welcome to Poetry!

This will download and install the latest version of Poetry,
a dependency and package manager for Python.

It will add the `poetry` command to Poetry's bin directory, located at:

$HOME/.poetry/bin

This path will then be added to your `PATH` environment variable by
modifying the profile files located at:

$HOME/.profile
$HOME/.bash_profile

You can uninstall at any time with `poetry self:uninstall`,
or by executing this script with the --uninstall option,
and these changes will be reverted.

Installing version: 0.12.12
  - Downloading poetry-0.12.12-darwin.tar.gz (7.23MB)

Poetry (0.12.12) is installed now. Great!

To get started you need Poetry's bin directory ($HOME/.poetry/bin) in your `PATH`
environment variable. Next time you log in this will be done
automatically.

To configure your current shell run `source $HOME/.poetry/env`

要激活 poetry 命令,请运行以下命令:

source $HOME/.poetry/env

现在,poetry命令应该可用。让我们检查一下安装的 Poetry 版本。

$ poetry —version
Poetry 0.12.12

成功!

Poetry 演示

创建模板

首先,我将创建一个演示应用程序。

poetry new poetry-demo

项目结构是这样的。

$ cd poetry-demo
$ tree
.
├── README.rst
├── poetry_demo
│   └── __init__.py
├── pyproject.toml
└── tests
    ├── __init__.py
    └── test_poetry_demo.py

让我们来看看 pyproject.toml

[tool.poetry]
name = "poetry-demo"
version = "0.1.0"
description = ""
authors = ["[Your Name] <[Your Email]>"]

[tool.poetry.dependencies]
python = "^3.6"

[tool.poetry.dev-dependencies]
pytest = "^3.0"

[build-system]
requires = ["poetry>=0.12"]
build-backend = "poetry.masonry.api"

添加依赖

我可以直接在 pyproject.toml 文件中指定依赖项,但是使用 add 命令看起来很容易。

poetry add pendulum

自动将 pendulum 添加到 pyproject.toml 文件中。

[tool.poetry.dependencies]
python = "^3.6"
pendulum = "^2.0"

此外,还会创建 poetry.lock

$ tree
.
├── README.rst
├── poetry.lock
├── poetry_demo
│   └── __init__.py
├── pyproject.toml
└── tests
    ├── __init__.py
    └── test_poetry_demo.py

由于这只是首次尝试使用 Poetry,因此我将继续使用它,如果发现有用的东西,可能会再次写一篇博客文章 :)

本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

原文地址:https://dev.to/yukinagae/beginner-guide-...

译文地址:https://learnku.com/python/t/38708

本文为协同翻译文章,如您发现瑕疵请点击「改进」按钮提交优化建议
讨论数量: 1

果然很入门,我还没高潮呢...就结束了...

3年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!