I'm trying to create small command line tool. My approach was to start off with a list of commands that I would like to run and then create a parser accommodate those commands. Rather than set up the parser and then have the dictate what the input should be.
I'm struggling to figure out how to set up arguments based on previous inputs. Below are a few examples of the commands I am aiming for.
cgen create test-runner
cgen create config --branch branch_name
cgen create guide --branch branch_name
I currently have it set up so that create has set choices as an argument. Then, depending on the inputted argument, I would like to have branch be a required argument if config or guide is run, but not if test-runner is inputted.
I keep tearing things down and trying different approaches so what I have is really basic at the moment but look something like this...
def main():
def run_create(args):
print('run_create')
if args.create_type == 'test-runner':
create_test_runner(args)
if args.create_type == 'config':
print(f'Creating config')
if args.create_type == 'guide':
print(f'Creating guide')
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
# create the parser for the "create" command
parser_create = subparsers.add_parser('create')
parser_create.add_argument(choices=['test-runner', 'config', 'guide'], dest='create_type')
parser_create.set_defaults(func=run_create)
args = parser.parse_args()
args.func(args)
parse_create.add_subparsers()with.add_parserfor 'config' and 'guide'` is one possibility. You might want to give thesubparsersadest. Inargparsearguments are either flagged (with the '--') orpositional. In 'cgen create config --branch branch_name', 'create' and 'config' arepositional, '--branch' is a flag, and 'branch_name' is its argument.subparsersis a kind ofpositional.cgen create --config branch_name, making a--configas flagged argument that takes a value.