Reputation: 8338
I have 3 questions.
1). I would like to be able to use this python commandline program without worrying about order of the arguments. I was using sys.argv before and had my users use this script like this:
mypyscript.py create indexname http://localhost:9260 clientMap.json
That requires my users to remember the order.
I want something like this:
mypyscript.py -i indexname -c create -f clientMap.json -u http://localhost:9260
Notice how I have mutilated the order.
2). What commandline variable in my program will I be using as the conditional logic in my code? Will I need to access it via args.command-type? The dash is okay?
3). Only the file-to-index is the optional parameter. Can I pass to add_argument some optional = True parameter or something? How can I deal with that?
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-c","--command-type", help="The command to run against ElasticSearch are one of these: create|delete|status")
parser.add_argument("-i","--index_name", help="Name of ElasticSearch index to run the command against")
parser.add_argument("-u", "--elastic-search-url", help="Base URl of ElasticSearch")
parser.add_argument("-f", "--file_to_index", default = 'false', help="The file name of the index map")
args = parser.parse_args()
print args.elastic_search_url
Upvotes: 0
Views: 311
Reputation: 80021
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.
The dash is the default and commonly understood way
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.
Upvotes: 1