deferring exiting on --help when using parse_known_args()

Viewed 102

I have a code that needs to build its command line arguments dynamically, based on configuration file. Schematically, what I end up doing is

parser = argparse.ArgumentParser()
parser.add_argument("-c", "--config", type=str, default="",
                        help="Path to config file.")
args, unknown = parser.parse_known_args()

#here do stuff with args.config to extend parser list of arguments, and then:

parser.parse_args()

The argument management seems to work perfectly well but the trouble I have is that --help will exit at the first call parse_known_args, instead of the second parser.parse_args() which would have shown all the dynamically added arguments.... Is there a way to solve this?

1 Answers

I had the same problem some time ago. It can be solved by using two parsers.

  • A first pre-parser, with add_help=False to determine the configuration file;
  • The second full parser with help.
# test.py
import argparse

# First pre-parser to determine the configuration file
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument("-c", "--config", default="", help="Path to config file.")
args = parser.parse_known_args()

# Do something with args.config

# Full and real parser
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--config", default="", help="Path to config file.")
parser.add_argument("-o", "--option", help="Option with default value from config file")

parser.parse_args()

This result in:

$ python3 test.py --help
usage: test.py [-h] [-c CONFIG] [-o OPTION]

optional arguments:
  -h, --help            show this help message and exit
  -c CONFIG, --config CONFIG
                        Path to config file.
  -o OPTION, --option OPTION
                        Option with default value from config file
Related