command line - Python argparse: "unrecognized arguments" -


i trying use program command line option. here code:

import argparse  def main():      parser = argparse.argumentparser()     parser.add_argument("-u","--upgrade", help="fully automatized upgrade")     args = parser.parse_args()      if args.upgrade:         print "starting upgrade procedure" main() 

when try run program terminal (python script.py -u), expect message starting upgrade procedure, instead error message unrecognized arguments -u.

the error getting because -u expecting value after it. if use python script.py -h find in usage statement saying [-u upgrade].

if want use boolean or flag (true if -u used), add additional parameter action:

parser.add_argument("-u","--upgrade", help="fully automatized upgrade", action="store_true") 

action - basic type of action taken when argument encountered @ command line

with action="store_true", if option -u specified, value true assigned args.upgrade. not specifying implies false.

source: python argparse documentation


Comments