Home > other >  Python: help menu doesn't show all options when using parse_known_args()
Python: help menu doesn't show all options when using parse_known_args()

Time:08-26

I went through a "little" issue using python argument parser, I've created a parser like shown below:

parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)

parser.add_argument('-l', '--log-level', help="log level")
parser.add_argument('-o', '--out-dir', help="output directory")

args, remaining = parser.parse_known_args()

outpu_dir = args.out_dir

parser.add_argument('-f', '--log-file', help = "log file directory")

args = parser.parse_args()

and the problem is that when calling the program with --help option, arguments added after parse_known_args() are not listed in the menu, I checked other topics related to this, but my case is a bit different! could any one give a help here please ?

CodePudding user response:

Any code which is below the call to parse_known_args will not execute at all.

from argparse import ArgumentParser

parser = ArgumentParser()

parser.add_argument('-a')
parser.parse_known_args()
1/0

When running with --help this generates

usage: main.py [-h] [-a A]

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

Process finished with exit code 0

and not a ZeroDivisionError exception.

CodePudding user response:

You can work around it by adding the help option after all the other args have been added & you've parsed the known args.

from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter, SUPPRESS

# don't add help right now
parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter, add_help=False)

parser.add_argument('-l', '--log-level', help="log level")
parser.add_argument('-o', '--out-dir', help="output directory")

args, remaining = parser.parse_known_args()

outpu_dir = args.out_dir

parser.add_argument('-f', '--log-file', help="log file directory")
# add help later, when all other args have been added
parser.add_argument('-h', '--help', action='help', default=SUPPRESS,
                    help='Show this help message and exit.')

args = parser.parse_args()

Which results in:

(venv) ➜  python main.py --help
usage: main.py [-l LOG_LEVEL] [-o OUT_DIR] [-f LOG_FILE] [-h]

optional arguments:
  -l LOG_LEVEL, --log-level LOG_LEVEL
                        log level (default: None)
  -o OUT_DIR, --out-dir OUT_DIR
                        output directory (default: None)
  -f LOG_FILE, --log-file LOG_FILE
                        log file directory (default: None)
  -h, --help            Show this help message and exit.

But it's much better if you can restructure your code to add all the argusments first before doing any parsing (i.e. avoid the call to parse_known_aergs before any other add_argument calls)

  • Related