我可以从一个配置文件构建一个Python Click cli吗?它的路径本身就是一个参数?

2024-05-16 21:10:50 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个配置文件cfg.yaml

# cfg.yaml
opt1: "Bailey is the cutest doggo ever!!!"
opt2: 42

我希望动态构建cli接口,而不提前知道cfg.yaml中有哪些项。其中cfg.yaml中的值是选项的默认值。比如:

python cli.py config.yaml run --help

Usage: cli.py run [OPTIONS]

Options:
  --opt1 TEXT
  --opt2 INTEGER

然后我可以跑:

python cli.py config.yaml run --opt1 my_str --opt2 314159

Tags: therunpyconfigyamlcliis配置文件
1条回答
网友
1楼 · 发布于 2024-05-16 21:10:50

好吧,这并不漂亮,但我有一个黑客继续前进

here关于cli编程构建的一些帮助下,以及良好的旧sys.argv:-)

import click
import yaml
import sys

cfg_path = sys.argv[1]
if cfg_path.endswith('.yaml'):
    with open(cfg_path, 'r') as f:
        cfg = yaml.load(f, Loader=yaml.SafeLoader)
    sys.argv.remove(cfg_path)
else:
    cfg = {}

def options_from_pipeline_def(cfg):
    def decorator(f):
        for k,v in cfg.items():
            param_decls = [
                f' {k}',
            ]

            attrs = dict(
                required=False,
                default=v,
                type=type(v)
                )
            click.option(*param_decls, **attrs)(f)
        return f
    return decorator 


@click.group()
def cli():
    pass

@cli.command("run")
@options_from_pipeline_def(cfg)
def run(**kwargs):
    print(f"kwargs: {kwargs}")


if __name__ == '__main__':
    cli()

例子

$ python build-cli.py  help
 -

Usage: build-cli.py [OPTIONS] COMMAND [ARGS]...

Options:
   help  Show this message and exit.

Commands:
  run

########################################

$ python build-cli.py cfg.yaml run  help
 -

Usage: build-cli.py run [OPTIONS]

Options:
   opt2 INTEGER
   opt1 TEXT
   help          Show this message and exit.

########################################

$ python z-build-cli.py cfg.yaml run
 -

kwargs: {'opt2': 42, 'opt1': 'Bailey is the cutest doggo ever!!!'}

########################################

$ python build-cli.py cfg.yaml run  opt1 "I cannot stress how cute Bailey is!"  opt2 314159
 -

kwargs: {'opt1': 'I cannot stress how cute Bailey is!', 'opt2': 314159}

相关问题 更多 >