You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何向基于Pydantic-CLI的参数解析器传入可选字符串列表?

解决方案

问题根源是Pydantic-CLI默认不会自动识别列表类型的参数需要接受多个值,必须在Field中通过cli_options明确配置nargs属性,告诉解析器参数的取值数量规则。

修改后的正确代码

from pydantic import BaseModel, Field
from typing import List, Optional
from pydantic_cli import run_and_exit


class CommandLineArguments(BaseModel):
    """Command Line Arguments."""
    config_files: Optional[List[str]] = Field(
        [],
        description='Paths to the config files that should be validated',
        cli=('--config-files',),
        # 核心配置:指定接受0个或多个参数值,对应argparse的nargs='*'
        cli_options={"nargs": "*"}
    )
    with_log: Optional[bool] = Field(
        False,
        description='Enable logging output',
        cli=('--with-log', '--no-log'),
    )
    stacktrace: Optional[bool] = Field(
        False,
        description='Enable stack trace output',
        cli=('--with-stacktrace', '--no-stacktrace'),
    )


def main(args: CommandLineArguments):
    print(f"待验证的配置文件: {args.config_files}")
    print(f"是否开启日志: {args.with_log}")
    print(f"是否开启堆栈追踪: {args.stacktrace}")


if __name__ == "__main__":
    run_and_exit(CommandLineArguments, main)

关键说明

  • cli_options={"nargs": "*"}:表示该参数可以接受0个或多个输入值;如果要求必须至少传入一个配置文件,可改用nargs='+'。
  • 执行命令时,直接在--config-files后跟上多个文件路径即可,无需重复指定参数名:
    python src/scripts/config_validation.py --config-files src/config/some.json src/config/another.json --with-log
    

另外,你之前尝试的根模型写法完全没必要,Pydantic-CLI支持直接解析List[str]类型字段,只要正确配置cli_options即可。


内容的提问来源于stack exchange,提问作者Andreas L.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 12:50:19