By default, the default argparse augment parameters are used by global parameters

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

# Global parser and options.
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.")

# Sub-command parser and options.
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:

    # Parse the command minus the help to obtain the global options. 
    args = sys.argv[1:]
    args.remove("--help")

    # Update the defaults with the global options.
    options = parser.parse_args(args) 
    command.set_defaults(config="~%s/config" % options.user)

    # Re-parse the options.
    parser.parse_args()

. /?

+5
2

, , parse_known_args, , --user. , --user, --config, parse_args .

, argparse.

( , ).

import os
import argparse

# Global preparser and options.
preparser = argparse.ArgumentParser(add_help=False)
preparser.add_argument("--user", dest="user", default=os.environ.get("USER"))

# ****** NEW *******
options, _ = preparser.parse_known_args() # Ignore what we haven't defined yet
user = options.user                       # Use this to define the default of --config

parser = argparse.ArgumentParser(parents=[ preparser ], add_help=True,
                   formatter_class=argparse.ArgumentDefaultsHelpFormatter)

# Sub-command parser and options.
subparsers = parser.add_subparsers()

command = subparsers.add_parser("command")

# ****** MODIFIED *******
command.add_argument("--config", dest="config", default="~%s/config" % (user,))

options = parser.parse_args()
+4

, . os.environ - , . , add_argument('--config'...) . help - . .

class FooAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        config.help = 'new user (%s)'% values
        setattr(namespace, self.dest, values)

parser = argparse.ArgumentParser()
parser.add_argument('--user',action=FooAction)
sub = parser.add_subparsers()
cmd = sub.add_parser('cmd')
config = cmd.add_argument('--config',help='initial help')
config.help = 'default help' # alt way of setting 'help'
# print config  # to see other attributes of the config action
args = parser.parse_args()
print args

cmd -h, default help

$ python stack12167228.py cmd -h
usage: stack12167228.py cmd [-h] [--config CONFIG]

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

--user xxx cmd -h,

$ python stack12167228.py --user xxx cmd -h
usage: stack12167228.py cmd [-h] [--config CONFIG]

optional arguments:
  -h, --help       show this help message and exit
  --config CONFIG  new user (xxx)
0

All Articles