我可以确定单击命令是直接调用还是由其他命令调用?

时间:2019-06-10 14:39:38

标签: python click

我构建了一个小的CLI,该CLI允许用户一次通过API向我的系统添加一项。这是可行的,但如果用户希望快速连续添加多个内容,则很烦人。

我当前的计划是添加一个新命令,该命令接受具有对象适当属性的JSON文件。 JSON文件中的每个对象都会被循环,并且CLI将使用JSON文件中的适当值调用现有命令。

现在,由于API速度可能很慢,所以我提供了一个进度条,该进度条显示了在系统中完全设置产品之前的时间。该进度条在每次添加项目的调用后运行。批量添加项目时,我不需要多个进度栏。最后只有一个进度条可以很好地工作。

我目前的想法是在现有的添加项命令中检测是否直接调用了该命令,还是由批量添加命令调用了该命令。 Click可以做到吗?

一些伪代码有助于可视化:

@click.command()
@click.option('--attribute1')
@click.option('--attribute2')
def additem(attribute1, attribute2):
    add_via_api(attribute1, attribute2)
    # This is going to take 10-15 seconds for everything to set up
    # so show a progressbar here normally, just sleep for this example
    # I want to detect right here though, so I can not sleep if this is a 
    # bulk insert
    sleep(15)

@click.command()
@click.arugment('f', type=click.File(exists=True))
def bulkadditems(ctx, f):
    with open(f) as items_file:
        items = json.load(items_file)
    for item in items:
        ctx.invoke(additem, attribute1=item['attribute1'], attribute2=item['attribute2'])

    # Once all items have invoked the other command, this is where I want 
    # a progress bar

0 个答案:

没有答案
相关问题