Python 2.7 Argparse Yes or No input
You could simply add an argument with action='store_true'
, which will default args.calories
to False if the --calories
is not included. To further clarify, if the user adds --calories
, args.calories
will be set to True
.
parser = argparse.ArgumentParser(description='Get food details.')# adding the `--food` argumentparser.add_argument('--food', help='name of food to lookup', required=True, type=file)# adding the `--calories` argumentparser.add_argument('--calories', action='store_true', dest='calories', help='...')# note: `dest` is where the result of the argument will go.# as in, if `dest=foo`, then `--calories` would set `args.foo = True`.# in this case, it's redundant, but it's worth mentioning.args = parser.parse_args()if args.calories: # if the user specified `--calories`, # call the `calories()` method calories()else: do_whatever()
If, however, you would like to specifically check for yes
or no
, then replace the store_true
in
parser.add_argument('--calories', action='store_true', dest='calories', help='...')
with store
, as shown below
parser.add_argument('--calories', action='store', dest='calories', type='str', help='...')
This will then allow you to check later for
if args.calories == 'yes': calories()else: do_whatever()
Do note that in this case I added type=str
, which parses the argument as a string. Since you specified that the choices are either yes
or no
, argparse
actually allows us to further specify the domain of possible inputs with choices
:
parser.add_argument('--calories', action='store', dest='calories', type='str', choices=['yes', 'no'], help='...')
Now, if a user enters anything not in ['yes', 'no']
, it will raise an error.
One last possibility is adding a default
, such that users don't have to necessarily specify certain flags all the time:
parser.add_argument('--calories', action='store', dest='calories', type='str', choices=['yes', 'no'], default='no', help='...')
Edit: As @ShadowRanger pointed out in the comments, in this case, dest='calories'
, action='store'
, and type='str'
are the defaults, so you can omit them:
parser.add_argument('--calories', choices=['yes', 'no'], default='no', help='...')