简体   繁体   中英

How to make an argument optional based upon another argument's value in Python using click?

I have this following CLI method that I have created using click module in python.

import click

@click.command()
@click.argument("name")
@click.option("--provider", "-p", default="aws", help="Cloud Provider")
@click.argument("view", required=True)

def create(name, view, provider):
   print name
   print view
   print provider

if __name__ == '__main__':
    create()

I want to manipulate view option based on the value it gets for --provider . For example if --provider is aws then required=True for view else required=False making view optional while running my code.

There's no need for anything fancy, something like this will work

def create(name, provider, view=None):
    if provider == "aws" and view is None:
        raise AttributeError("View is required when provider is 'aws'")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM