Here is an example code:
import argparse
parser=argparse.ArgumentParser()
parser.add_argument('-main_arg')
subparser=parser.add_subparser()
a=subparser.add_parser('run')
a.add_argument('required_sub_arg')
a.add_argument('arg_a')
b=subparser.add_parser('b')
parser.parse_args()
I want it to read in -main_arg if I enter program run required_sub_arg -main_arg -arg_a
Right now, it doesn’t recognize -main_arg as a valid argument.
PSA to recent readers
As this question still has visits in 2018, before doing anything this complex with argparse, please consider using docopt or click instead. It will improve both your sanity and that of anyone who might read or modify your code. Thank you.
Original answer
As is, you have a few issues.
First,
parser.parse_argsis a method that returns a namespace ofparser‘s arguments, so you should do something likeThen
args.main_argsto get-main_argfrom a call likeYour issue with
main_argis that you have created a argument toparsernamedmain_arg, and you make a call likethat refers to an argument to
anamedmain_arg. Sinceadoesn’t have such an argument, it is invalid.In order to refer to a parser’s argument from one of its subparser, you have to make said subparser inherit the arguments of its parent. This is done with
You have mistaken subparser for child parser. See http://docs.python.org/dev/py3k/library/argparse.html and https://code.google.com/p/argparse/issues/detail?id=54 for more informations.