When I need that some arguments change the way how other arguments are parsed, I first parse the deciding arguments then I parse the rest:
import argparse
def parse_arguments(args=None):
deciding_args_parser = argparse.ArgumentParser(add_help=False)
deciding_args_parser.add_argument(
'--advanced-help', required=False, action='store_true',
help='show the full list of options')
deciding_args, _ = deciding_args_parser.parse_known_args(args)
parser = argparse.ArgumentParser(
description='This is a demonstration of argument parser.',
parents=[deciding_args_parser])
parser.add_argument('-b', '--basic-option', help='Just a basic option.')
parser.add_argument(
'-a', '--advanced-option',
help=('Advanced option!' if deciding_args.advanced_help
else argparse.SUPPRESS))
return parser.parse_args(
args + (['-h'] if deciding_args.advanced_help else []))
parse_arguments(['-h'])
usage: ipykernel_launcher.py [-h] [--advanced-help] [-b BASIC_OPTION]
This is a demonstration of argument parser.
options:
-h, --help show this help message and exit
--advanced-help show the full list of options
-b BASIC_OPTION, --basic-option BASIC_OPTION
Just a basic option.
parse_arguments(['--advanced-help'])
usage: ipykernel_launcher.py [-h] [--advanced-help] [-b BASIC_OPTION]
[-a ADVANCED_OPTION]
This is a demonstration of argument parser.
options:
-h, --help show this help message and exit
--advanced-help show the full list of options
-b BASIC_OPTION, --basic-option BASIC_OPTION
Just a basic option.
-a ADVANCED_OPTION, --advanced-option ADVANCED_OPTION
Advanced option!