Package: arghandler
arghandlerMaking argparse even more awesomeI loveargparse, but there
are some things that it simply doesn't help with as much as I'd like. Enter
arghandler.The goal behind arghandler is to provide all the capabilities of argparseplussome high-level capabilities that crop up a lot when writing
command-line tools: the library aims for high quality command line interfaces
with (even more) minimal code.At present, arghandler provides two key capabilities:Adding subcommands with basically zero extra lines of code. This gives
support for writing programs likegitandsvnwhich have nested
subcommands.Configuring the logging framework (e.g., the desired logging level) from
the command line - again with basically one line of code.We have lots more improvements we want to add - and as we have time and receive
feedback, we'll add more features.If you have ideas,email meor code it up
and generate a pull request!InstallationUsepiporeasy_installto install the library:pip install arghandleroreasy_install arghandlerYou can find arghandler on pypi for relevant details should you need them.UsageJust like withargparse.ArgumentParser,
inarghandlereverything revolves aroundArgumentHandler. In fact, it's
(not so secretly) a subclass of ArgumentParser, so you can use it exactly the
way you useArgumentParser.  ButArgumentHandlerhas some new tricks.To benefit fromArgumentHandler, your command-line configuration code will
follow this logic:from arghandler import ArgumentHandler

handler = ArgumentHandler() # this accepts all args supported by ArgumentParser

# config the handler using add_argument, set_logging_level, set_subcommands, etc...

handler.run() # throw the configured handler at an argument string!Now for some details...Invoking ArgumentHandlerArgumentHandlercan be invoked on arguments in two ways.ArgumentHandler.parse_args([argv])is little different fromArgumentParser.parse_args([argv]).  Ifargvis omitted, then the value ofsys.argvis used. The only notable differences are:If a logging argument was set, then this will be included in the namespace
object returned.If subcommands are available, then the subcommand will be given by the
value ofargs.cmdand the subcommand's arguments will be given byargs.cargs.ArgumentHandler.run(argv,context_fxn)makes the class perform its more
unique and powerful capabilities.  Notably: configuring the logger and running
subcommands.  As withparse_args(...), ifargvis not specified, thensys.argvwill be used.  Thecontext_fxnis also optional and is used as
part of subcommand processing.  See thatsectionbelow for more
details.Enabling autocompletionWhen constructing anArgumentHandler, you can enable autocompletion.  This
requires doing two separate things.First, pass the keyword argumentenable_autocompetion=TruetoArgumentHandler(...).Second, in the top-level script that will be your command-line tool, include
the line# PYTHON_ARGCOMPLETE_OKnear the top (in the first 1024 bytes).  For more details on this, see theargcompletedocumentation.For an example of this in action, seeexamples/dummy.py!.Setting the logging levelIf you use the pythonloggingpackage, this feature will save you some time.TheArgumentParser.set_logging_argument(...)method allows you to specify a
command-line argument that will set the logging level.  The method accepts
several arguments:ArgumentParser.set_logging_argument(*names,default_level=logging.ERROR,config_fxn=None)*namesstands in for one or more arguments that specify the
argument names that will be used. These follow the same rules as ones
passed intoArgumentParser.add_argument(...).
Moreover, they MUST be optional arguments (i.e., start with a '-'
character).default_levelindicates the default level the logging
framework will be set to should the level not be specified on the command
line.config_fxnallows the developer to write special logging
configuration code.  If not specified, thelogging.basicConfigfunction will be invoked with the appropriate logging level. The function
must accept two arguments: the logging level and the namespace args object
returned by theArgumentParser.parse_argsmethod. The configuration
itself will happen when theArgumentHandler.run(...)method is called.If you're cool with the defaults inbasicConfig, then your method call will
look something like thishandler.set_logging_argument('-l','-log_level',default_level=logging.INFO)If you do want to do some customization, then your code will look like thishandler.set_logging_argument('-l','-llevel',
	config_fxn=lambda level,args: logging.basicConfig(level=level,format='%(message)'))Declaring subcommands using decoratorsThis feature makes it possible to write nested commands likegit commitandsvn checkoutwith basically zero boilerplate code.  To do thisarghandlerprovides the@subcmddecorator.  To declare a subcommand, just put the
decorator on the function  you want to act as the subcommand.from arghandler import *

@subcmd
def echo(parser,context,args):
	print ' '.join(args)

# here we associate the subcommand 'foobar' with function cmd_foobar
@subcmd('foobar', help = 'Does foobar')
def cmd_foobar(parser,context,args):
	print 'foobar'

handler = ArgumentHandler()
handler.run(['echo','hello','world']) # echo will be called and 'hello world' will be printedNotice that the subcommands always take three arguments.argsis the set of arguments thatfollowthe subcommand on the command
line.contextis an object that can make valuable global information available to
subcommands.  By default, the context is the namespace object returned by the
internal call toArgumentHandler.parse_args(...).  Other contexts can be
produced by passing a context-producing function to theArgumentHandler.run(...)function:@subcmd('ping')
def ping_server(parser,server_address,args):
	os.system('ping %s' % server_address)

handler = ArgumentHandler()
handler.add_argument('-s','--server')

# when this is run, the context will be set to the return value of context_fxn
# in this case, it will be the string '127.0.0.1'
handler.run(['-s','127.0.0.1','ping'],context_fxn=lambda args: args.serverFinally,parseris an instance ofargparse.ArgumentParserwhich has been
preconfigured to behave properly for the subcommand.  Most crucially, this
means thatparser.progis set to<top_level_program> <sub_command>so that
help messages print out correctly for the subcommand.  Should your subcommand
want to parse arguments, this parser object should be used.Declaring subcommands without decoratorsWhile decorators are the preferred way to specify subcommands, subcommands can
also be specified using theArgumentHandler.set_subcommands(...)function.
This method expects a dictionary: keys are command names, values are the
command functions:from arghandler import *

def echo(parser,context,args):
	print ' '.join(args)

def cmd_foobar(parser,context,args):
	print 'foobar'

handler = ArgumentHandler()
handler.set_subcommands( {'echo':echo, 'foobar':cmd_foobar} )
handler.run(['echo','hello','world']) # echo will be called and 'hello world' will be printedAll the logic and rules around the context function apply here.  Moreoever, the
complete set of subcommands include those specified using decorators AND those
specified through theset_subcommands(...)method.Making subcommands in subcommandsOne valuable use for theset_subcommands(...)method is implementing
subcommand options for a subcommand.  For example, suppose you want a program with the following
command subtree:power
  - create
    - config
    - proj
  - run
    - all
    - projIn this case,createandrunwould be top-level subcommands that could be
declared using standardsubcmddecorators.  But what about theconfigandprojcommands underneathcreate?  These can be created using a newArgumentHandlerinside thecreatefunction like this:def create_config(parser, context, args):
    parser.add_argument('location')
    args = parser.parse_args(args)

    # do stuff

    return

def create_proj(parser, context, args):
    parser.add_argument('name')
    args = parser.parse_args(args)

    print(f'Creating the project: {args.name}')

    # do stuff

    return


@subcmd('create', help='create a resource')
def create(parser, context, args):
    handler = ArgumentHandler()

    handler.set_subcommands({'config': (create_config, 'create a config file'),
                             'proj': (create_proj, 'create a project')
                            },
                            use_registered_subcmds=False)

    handler.run(args)Note the use ofuse_registered_subcmds=False- this is important to omit any
functions globally registered as commands using the@subcmddecorator.Setting the help messageThe format of the help message can be set to one more friendly for subcommands
by passing theArgumentHandlerconstructor the keyword argumentuse_subcommand_help=True.This will produce a help message that looks something like this:usage: test.py [-h] subcommand

positional arguments:
  subcommand
    cmd1  cmd1_help_str

optional arguments:
  -h, --help  show this help message and exitSome best practicesUseArgumentParserorArgumentHandlerinside subcommands.This will
ensure that informative help messages are available for all your subcommands.from arghandler import *

@subcmd
def echo(parser,context,args):
	parser.add_argument('-q','--quote_char',required=True)
	args = parser.parse_args(args)
	print '%s%s%s' % (args.quote_char,' '.join(args),args.quote_char)

@subcmd('foobar')
def cmd_foobar(parser,context,args):
	print 'foobar'

handler = ArgumentHandler()
handler.run(['echo','-h']) # the help message for echo will be printedUse logging.Logging gives you much more control over what
debugging/informational content is printed out by your program. And witharghandlerit's easier than ever to configure from the command line!