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)
When you add arguments you can specify if you want them to be required or not link.
So you can test on the fly and make an argument obligatory.
def arguments_is_given(*args: str) -> bool:
return len(set(args) & set(sys.argv)) > 0
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("--branch",required=not arguments_is_given("config", "guide"))
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)