I would like to be able to use the global parameters of the argparse.ArgumentParser object to override / increase the default values โโfor the subcommand.
An example is the fact that the displayed help reflects global updates, i.e. for the following toy example:
import argparse
import os
import sys
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--user",
dest="user",
default=os.environ.get("USER"),
help="Override the setting of the $USER variable.")
subparsers = parser.add_subparsers()
command = subparsers.add_parser(
"command",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
command.add_argument("--config",
dest="config",
default="~%s/config" % os.environ.get("USER"),
help="The config file.")
options = parser.parse_args()
Ideally, when I run this in help mode, I get
> python example.py --user thing command --help
usage: example.py command [-h] [--config CONFIG]
optional arguments:
-h, --help show this help message and exit
--config CONFIG The config file. (default: ~thing/config)
ie, the path of the configuration file depends on the user (item). I understand that I can change the default configuration as "~%(user)s/config", and then enable it at runtime using the option namespace, however I would like the help to be more explicit.
- , , ..
if "--help" in sys.argv:
args = sys.argv[1:]
args.remove("--help")
options = parser.parse_args(args)
command.set_defaults(config="~%s/config" % options.user)
parser.parse_args()
. /?