如何存储单击命令行参数/选项以供参考?

问题描述 投票:1回答:1

新的点击这里,所以我还在学习。如何将单击参数/选项存储在对象中,以供以后在应用程序中参考?我想到只是创建一个对象,然后从设置函数返回它,但它似乎没有用。这是我所做的:

import click
import sys


class Cfg(object):
    component = ""
    command = ""
    obj = ""


my_cfg = Cfg()


@click.command()
@click.argument('component')
@click.argument("command")
@click.argument("obj")
def set_args(component, command, obj):
    cfg = Cfg()
    if component != "optdata":
        sys.stderr.write("Invalid option")
        sys.exit(1)
    else:
        cfg.component = component
        cfg.command = command
        cfg.obj = obj

    return cfg


if __name__ == "__main__":
    app_cfg = Cfg()
    app_cfg = set_args() # Never actually completes here. 
    print("Component = ", app_cfg.component, "Command = ", app_cfg.command, "Obj = ", app_cfg.obj)

[core.py中引发了某种异常,它只是执行sys.exit而不会引发任何实际错误。

python command-line-interface python-click
1个回答
1
投票

您的设计违背了Click的想法:您不应将“解析选项”和“完成工作”视为两个单独的步骤:

import click

@click.command()
@click.argument("component", type=click.Choice(["optdata"]))
@click.argument("command")
@click.argument("obj")
def cli(component, command, obj):
    print("Component = ", component, "Command = ", command, "Obj = ", obj)
    # put your business logic here

if __name__ == "__main__":
    cli()

模式是调用处理命令行选项的函数,然后让该函数调用任何其他功能。

© www.soinside.com 2019 - 2024. All rights reserved.