How to conditionally make python argparse a module requires additional arguments

The main purpose:

my_framework create Project_title /path/to/project

OR

my_framework create Project_title

(i.e. use the current working directory)

OR

my_framework update

(i.e. update my_framework rather than create a new project)

I know I can make it name

optional by giving it a default, but it's actually name

not required if the user entered create

as the first argument.

The best solution I have come up with is to use the default for name

and then if the argument name

is equal to its default, throw an error. But if there is a way to do argparse, make this work for me, I'd rather learn it.

Write two scripts my_framework_create

, and my_framework_update

no appeal to me aesthetically.

#!/usr/bin/env python


import argparse
import os
import shutil
from subprocess import call

template_path = "/usr/local/klibs/template"
parser = argparse.ArgumentParser("MY_FRAMEWORK CLI", description='Creates a new MY_FRAMEWORK project or updates MY_FRAMEWORK')
parser.add_argument('action', choices=['create', 'update'], type=str, help='<help text>')
parser.add_argument('name', type=str, help='<help text>')
parser.add_argument('path', default=os.getcwd(), nargs="?", type=str, help='<help text>')
args = parser.parse_args()

if args.action == "create":
    # do the create stuff

if args.action == "update":
    # do the update stuff

      

+3


source to share


1 answer


The best way to do this is subparser

Example from docs:

>>> parser = argparse.ArgumentParser()
>>> subparsers = parser.add_subparsers(title='subcommands',
...                                    description='valid subcommands',
...                                    help='additional help')
>>> subparsers.add_parser('foo')
>>> subparsers.add_parser('bar')
>>> parser.parse_args(['-h'])
usage:  [-h] {foo,bar} ...

optional arguments:
  -h, --help  show this help message and exit

subcommands:
  valid subcommands

  {foo,bar}   additional help

      



In your case, you have create

both update

as separate sub-parameters.

Example:

def create(args):
    # do the create stuff
    print(args)


def update(args):
    # do the update stuff
    print(args)


parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(title='subcommands',
                                   description='valid subcommands',
                                   help='additional help')

create_parser = subparsers.add_parser('create')
create_parser.add_argument('name', type=str)
create_parser.set_defaults(func=create)

update_parser = subparsers.add_parser('update')
update_parser.set_defaults(func=update)

      

+4


source







All Articles