[Answer]-Working with argparse need explaination of how to use it properly

1πŸ‘

βœ…

  1. What is the question here? Personally I think it depends on the use case, there is something to be said for your old system. Especially when used with subparsers.

  2. The dash is the default and commonly understood way

  3. There is a required=True argument which tells argparse what to require.

For the command-type I would recommend using the choices parameter so it will be automatically constrained to create,delete,status

Also, in the case of the url you could consider adding a regular expression to validate, you can add this using the type parameter.

Here’s my version of your argument code:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument(
    '-c',
    '--command-type',
    required=True,
    help='The command to run against ElasticSearch',
    choices=('create', 'delete', 'status'),
)
parser.add_argument(
    '-i',
    '--index_name',
    required=True,
    help='Name of ElasticSearch index to run the command against',
)
parser.add_argument(
    '-u',
    '--elastic-search-url',
    required=True,
    help='Base URl of ElasticSearch',
)
parser.add_argument(
    '-f',
    '--file_to_index',
    type=argparse.FileType(),
    help='The file name of the index map',
)


args = parser.parse_args()

print args

I believe that should work as you expect it to.

πŸ‘€Wolph

Leave a comment