0%

使用pydantic-settings库创建CLI应用

最近读到一篇介绍 Pydantic 生态的文章,提到 pydantic-settings 库除了可以简化应用配置外,还可以用来创建命令行应用。在参阅了相关文档后,我完成了一个简单的示例,体验相当不错。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# /// script
# requires-python = ">=3.13"
# dependencies = ["pydantic-settings"]
# ///
import logging
from typing import Annotated, Literal

from pydantic import AliasChoices, Field, BeforeValidator
from pydantic_settings import BaseSettings, CliApp


class Settings(
BaseSettings, cli_parse_args=True, cli_prog_name="sum", cli_enforce_required=True
):
"""A simple CLI app to sum numbers."""

num: Annotated[list[int], Field(description="Numbers to sum")]
verbose: Annotated[
Literal[0, 1],
Field(
default=0,
validation_alias=AliasChoices("v", "verbose"),
description="Enable verbose output",
),
BeforeValidator(lambda v: int(v)),
]

def cli_cmd(self):
if self.verbose:
logging.basicConfig(level=logging.DEBUG, format="%(message)s")
logging.debug("Calculating sum of numbers %s", self.num)
print(sum(self.num))


if __name__ == "__main__":
CliApp.run(Settings)

可以直接使用 uv 运行该脚本。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

# 自动生成帮助信息

➜ uv run --script cli.py --help
usage: sum [-h] --num list[int] [-v {0,1}]

A simple CLI app to sum numbers.

options:
-h, --help show this help message and exit
--num list[int] Numbers to sum (required)
-v, --verbose {0,1} Enable verbose output (default: 0)

# 必填参数检查(开启 cli_enforce_required)

➜ uv run --script cli.py
usage: sum [-h] --num list[int] [-v {0,1}]
sum: error: the following arguments are required: --num

# 传入参数

➜ uv run --script cli.py --num 1 --num 2 --num 3
6

# 修改默认参数

➜ uv run --script cli.py --num 1 --num 2 --num 3 -v 1
Calculating sum of numbers [1, 2, 3]
6

# 传入 JSON 格式的参数

➜ uv run --script cli.py --num="[1,2,3]"
6

扫码加入技术交流群🖱️
QR code