ArgumentParser -h not printing options after parse_known_args

Viewed 660

I have script with a long list of optional arguments where I recently added the option to pass the arguments through a file. The code for this is below: I first add the from_file args and then parse_known_args. Everything works except for the -h flag. The output when calling this flag only refers to the arguments added before the parse_known_args call.

Question: how can I get the help option to recognize all arguments after the parse_known_args call?

# grab values from file_parser or default
def getInitVar(variable, parser, default, varList=False):
    if parser:
        if varList:
            return [o.strip() for o in parser.get('constants',variable).split(",")] if parser.has_option('constants',variable) else default
        else:
            return parser.get('constants',variable) if parser.has_option('constants',variable) else default
    else:
        return default

# first parser for to/from file parameters
parser = argparse.ArgumentParser(
    description='', prefix_chars='-+', formatter_class=argparse.ArgumentDefaultsHelpFormatter)

# Meta variables
group = parser.add_argument_group('Meta Variables', '')
group.add_argument('--to_file', dest='toinitfile', nargs='?', const=DEF_INIT_FILE, default=None,
                  help='write flag values to text file')
group.add_argument('--from_file', type=str, dest='frominitfile', default='',
                   help='reads flag values from file')

args, remaining_argv = parser.parse_known_args()

# create second parser for reading from files
if args.frominitfile:
    conf_parser = SafeConfigParser()
    conf_parser.read(args.frominitfile)
else:
    conf_parser = None

group = parser.add_argument_group('Some Group', 'blah blah')

group.add_argument('-someFlag', dest='somevar', default=getInitVar('corpdb', conf_parser, DEF_VAR),
                    help='Some help.')
....

Output when using the -h flag:

optional arguments:
-h, --help            show this help message and exit

Meta Variables:
--to_file [TOINITFILE]
                    write flag values to text file (default: None)
--from_file FROMINITFILE
                    reads flag values from file (default: )

EDIT: Added some details (as suggested in the comments) to my code as to why I am calling parse_known_args:

  1. I create the parsers and add two arguments: from_file and to_file
  2. Parse the arguments. If from_file is present I create a second parser and read the input variable.
  3. Continue adding arguments to the parser. Default value is a function to which I pass the second parser and default value.

EDIT: Finally figured out how to do this, posted the answer below.

2 Answers
Related