# arghandler [![Build Status](https://travis-ci.org/druths/arghandler.svg?branch=master)](https://travis-ci.org/druths/arghandler) #
*Making argparse even more awesome*
I love [argparse](https://docs.python.org/3/library/argparse.html), 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 argparse
*plus* some 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:
1. Adding subcommands with basically zero extra lines of code. This gives
support for writing programs like `git` and `svn` which have nested
subcommands.
1. 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 me](mailto:druths@networkdynamics.org) or code it up
and generate a pull request!
## Installation ##
Use `pip` or `easy_install` to install the library:
pip install arghandler
or
easy_install arghandler
You can find arghandler on pypi for relevant details should you need them.
## Usage ##
Just like with
[argparse.ArgumentParser](https://docs.python.org/3/library/argparse.html#argumentparser-objects),
in `arghandler` everything revolves around `ArgumentHandler`. In fact, it's
(not so secretly) a subclass of ArgumentParser, so you can use it exactly the
way you use `ArgumentParser`. But `ArgumentHandler` has some new tricks.
To benefit from `ArgumentHandler`, 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 ArgumentHandler ###
`ArgumentHandler` can be invoked on arguments in two ways.
*`ArgumentHandler.parse_args([argv])`* is little different from
`ArgumentParser.parse_args([argv])`. If `argv` is omitted, then the value of
`sys.argv` is 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 of `args.cmd` and the subcommand's arguments will be given by
`args.cargs`.
*`ArgumentHandler.run(argv,context_fxn)`* makes the class perform its more
unique and powerful capabilities. Notably: configuring the logger and running
subcommands. As with `parse_args(...)`, if `argv` is not specified, then
`sys.argv` will be used. The `context_fxn` is also optional and is used as
part of subcommand processing. See that [section](#subcommands) below for more
details.
#### Enabling autocompletion ####
When constructing an `ArgumentHandler`, you can enable autocompletion. This
requires doing two separate things.
First, pass the keyword argument `enable_autocompetion=True` to
`ArgumentHandler(...)`.
Second, in the top-level script that will be your command-line tool, include
the line
# PYTHON_ARGCOMPLETE_OK
near the top (in the first 1024 bytes). For more details on this, see the
[argcomplete](https://argcomplete.readthedocs.io/en/latest/) documentation.
For an example of this in action, see [examples/dummy.py!](examples/dummy.py).
### Setting the logging level ###
If you use the python [logging](https://docs.python.org/3/library/logging.html)
package, this feature will save you some time.
The `ArgumentParser.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)
* `*names` stands in for one or more arguments that specify the
argument names that will be used. These follow the same rules as ones
passed into
[ArgumentParser.add_argument(...)](https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.add_argument).
Moreover, they MUST be optional arguments (i.e., start with a '-'
character).
* `default_level` indicates the default level the logging
framework will be set to should the level not be specified on the command
line.
* `config_fxn` allows the developer to write special logging
configuration code. If not specified, the
[logging.basicConfig](https://docs.python.org/3/library/logging.html#logging.basicConfig)
function will be invoked with the appropriate logging level. The function
must accept two arguments: the logging level and the namespace args object
returned by the `ArgumentParser.parse_args` method. The configuration
itself will happen when the `ArgumentHandler.run(...)` method is called.
If you're cool with the defaults in `basicConfig`, then your method call will
look something like this
handler.set_logging_argument('-l','-log_level',default_level=logging.INFO)
If you do want to do some customization, then your code will look like this
handler.set_logging_argument('-l','-llevel',
config_fxn=lambda level,args: logging.basicConfig(level=level,format='%(message)'))
### <a name="subcommands"></a>Declaring subcommands using decorators ###
This feature makes it possible to write nested commands like `git commit` and
`svn checkout` with basically zero boilerplate code. To do this `arghandler`
provides the `@subcmd` decorator. 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 printed
Notice that the subcommands always take three arguments.
`args` is the set of arguments that *follow* the subcommand on the command
line.
`context` is an object that can make valuable global information available to
subcommands. By default, the context is the namespace object returned by the
internal call to `ArgumentHandler.parse_args(...)`. Other contexts can be
produced by passing a context-producing function to the
`ArgumentHandler.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.server
Finally, `parser` is an instance of `argparse.ArgumentParser` which has been
preconfigured to behave properly for the subcommand. Most crucially, this
means that `parser.prog` is 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 decorators ###
While decorators are the preferred way to specify subcommands, subcommands can
also be specified using the `ArgumentHandler.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 printed
All 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 the `set_subcommands(...)` method.
#### Making subcommands in subcommands ####
One valuable use for the `set_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
- proj
```
In this case, `create` and `run` would be top-level subcommands that could be
declared using standard `subcmd` decorators. But what about the `config` and
`proj` commands underneath `create`? These can be created using a new
`ArgumentHandler` inside the `create` function 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 of `use_registered_subcmds=False` - this is important to omit any
functions globally registered as commands using the `@subcmd` decorator.
### Setting the help message ###
The format of the help message can be set to one more friendly for subcommands
by passing the `ArgumentHandler` constructor the keyword argument
`use_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 exit
## Some best practices ##
*Use `ArgumentParser` or `ArgumentHandler` inside 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 printed
*Use logging.* Logging gives you much more control over what
debugging/informational content is printed out by your program. And with
`arghandler` it's easier than ever to configure from the command line!
Raw data
{
"_id": null,
"home_page": "http://www.github.com/druths/arghandler",
"name": "arghandler",
"maintainer": "",
"docs_url": null,
"requires_python": "",
"maintainer_email": "",
"keywords": "argparse command-line parsing",
"author": "Derek Ruths",
"author_email": "druths@networkdynamics.org",
"download_url": "https://files.pythonhosted.org/packages/81/41/11ca052f1cf33e0c9fd4d07414f8e60bc9f97568c9d0dc43649e54ea2eaa/arghandler-1.3.1.tar.gz",
"platform": "",
"description": "# arghandler [![Build Status](https://travis-ci.org/druths/arghandler.svg?branch=master)](https://travis-ci.org/druths/arghandler) #\n*Making argparse even more awesome*\n\nI love [argparse](https://docs.python.org/3/library/argparse.html), but there\nare some things that it simply doesn't help with as much as I'd like. Enter\narghandler.\n\nThe goal behind arghandler is to provide all the capabilities of argparse\n*plus* some high-level capabilities that crop up a lot when writing\ncommand-line tools: the library aims for high quality command line interfaces\nwith (even more) minimal code.\n\nAt present, arghandler provides two key capabilities:\n\n 1. Adding subcommands with basically zero extra lines of code. This gives\n support for writing programs like `git` and `svn` which have nested\n subcommands.\n\n 1. Configuring the logging framework (e.g., the desired logging level) from\n the command line - again with basically one line of code.\n\nWe have lots more improvements we want to add - and as we have time and receive\nfeedback, we'll add more features.\n\nIf you have ideas, [email me](mailto:druths@networkdynamics.org) or code it up\nand generate a pull request!\n\n## Installation ##\n\nUse `pip` or `easy_install` to install the library:\n\n\tpip install arghandler\n\nor\n\n\teasy_install arghandler\n\nYou can find arghandler on pypi for relevant details should you need them.\n\n## Usage ##\n\nJust like with\n[argparse.ArgumentParser](https://docs.python.org/3/library/argparse.html#argumentparser-objects),\nin `arghandler` everything revolves around `ArgumentHandler`. In fact, it's\n(not so secretly) a subclass of ArgumentParser, so you can use it exactly the\nway you use `ArgumentParser`. But `ArgumentHandler` has some new tricks.\n\nTo benefit from `ArgumentHandler`, your command-line configuration code will\nfollow this logic:\n\n\tfrom arghandler import ArgumentHandler\n\n\thandler = ArgumentHandler() # this accepts all args supported by ArgumentParser\n\n\t# config the handler using add_argument, set_logging_level, set_subcommands, etc...\n\n\thandler.run() # throw the configured handler at an argument string!\n\nNow for some details...\n\n### Invoking ArgumentHandler ###\n\n`ArgumentHandler` can be invoked on arguments in two ways. \n\n*`ArgumentHandler.parse_args([argv])`* is little different from\n`ArgumentParser.parse_args([argv])`. If `argv` is omitted, then the value of\n`sys.argv` is used. The only notable differences are:\n\n * If a logging argument was set, then this will be included in the namespace\n object returned.\n\n * If subcommands are available, then the subcommand will be given by the\n\tvalue of `args.cmd` and the subcommand's arguments will be given by\n\t`args.cargs`.\n\n*`ArgumentHandler.run(argv,context_fxn)`* makes the class perform its more\nunique and powerful capabilities. Notably: configuring the logger and running\nsubcommands. As with `parse_args(...)`, if `argv` is not specified, then\n`sys.argv` will be used. The `context_fxn` is also optional and is used as\npart of subcommand processing. See that [section](#subcommands) below for more\ndetails.\n\n#### Enabling autocompletion ####\n\nWhen constructing an `ArgumentHandler`, you can enable autocompletion. This\nrequires doing two separate things.\n\nFirst, pass the keyword argument `enable_autocompetion=True` to\n`ArgumentHandler(...)`.\n\nSecond, in the top-level script that will be your command-line tool, include\nthe line\n\n\t# PYTHON_ARGCOMPLETE_OK\n\nnear the top (in the first 1024 bytes). For more details on this, see the\n[argcomplete](https://argcomplete.readthedocs.io/en/latest/) documentation.\n\nFor an example of this in action, see [examples/dummy.py!](examples/dummy.py).\n\n### Setting the logging level ###\n\nIf you use the python [logging](https://docs.python.org/3/library/logging.html)\npackage, this feature will save you some time.\n\nThe `ArgumentParser.set_logging_argument(...)` method allows you to specify a\ncommand-line argument that will set the logging level. The method accepts\nseveral arguments:\n\n\tArgumentParser.set_logging_argument(*names,default_level=logging.ERROR,config_fxn=None)\n\n\n * `*names` stands in for one or more arguments that specify the\n\targument names that will be used. These follow the same rules as ones\n\tpassed into\n\t[ArgumentParser.add_argument(...)](https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.add_argument).\n\tMoreover, they MUST be optional arguments (i.e., start with a '-'\n\tcharacter).\n\n * `default_level` indicates the default level the logging\n\tframework will be set to should the level not be specified on the command\n\tline.\n\n * `config_fxn` allows the developer to write special logging\n\tconfiguration code. If not specified, the\n\t[logging.basicConfig](https://docs.python.org/3/library/logging.html#logging.basicConfig)\n\tfunction will be invoked with the appropriate logging level. The function\n\tmust accept two arguments: the logging level and the namespace args object\n\treturned by the `ArgumentParser.parse_args` method. The configuration\n\titself will happen when the `ArgumentHandler.run(...)` method is called.\n\nIf you're cool with the defaults in `basicConfig`, then your method call will\nlook something like this\n\n\thandler.set_logging_argument('-l','-log_level',default_level=logging.INFO)\n\nIf you do want to do some customization, then your code will look like this\n\n\thandler.set_logging_argument('-l','-llevel',\n\t\tconfig_fxn=lambda level,args: logging.basicConfig(level=level,format='%(message)'))\n\n### <a name=\"subcommands\"></a>Declaring subcommands using decorators ###\n\nThis feature makes it possible to write nested commands like `git commit` and\n`svn checkout` with basically zero boilerplate code. To do this `arghandler`\nprovides the `@subcmd` decorator. To declare a subcommand, just put the\ndecorator on the function you want to act as the subcommand.\n\n\tfrom arghandler import *\n\n\t@subcmd\n\tdef echo(parser,context,args):\n\t\tprint ' '.join(args)\n\n\t# here we associate the subcommand 'foobar' with function cmd_foobar\n\t@subcmd('foobar', help = 'Does foobar')\n\tdef cmd_foobar(parser,context,args):\n\t\tprint 'foobar'\n\n\thandler = ArgumentHandler()\n\thandler.run(['echo','hello','world']) # echo will be called and 'hello world' will be printed\n\nNotice that the subcommands always take three arguments.\n\n`args` is the set of arguments that *follow* the subcommand on the command\nline.\n\n`context` is an object that can make valuable global information available to\nsubcommands. By default, the context is the namespace object returned by the\ninternal call to `ArgumentHandler.parse_args(...)`. Other contexts can be\nproduced by passing a context-producing function to the\n`ArgumentHandler.run(...)` function:\n\n\t@subcmd('ping')\n\tdef ping_server(parser,server_address,args):\n\t\tos.system('ping %s' % server_address)\n\n\thandler = ArgumentHandler()\n\thandler.add_argument('-s','--server')\n\n\t# when this is run, the context will be set to the return value of context_fxn\n\t# in this case, it will be the string '127.0.0.1'\n\thandler.run(['-s','127.0.0.1','ping'],context_fxn=lambda args: args.server\n\nFinally, `parser` is an instance of `argparse.ArgumentParser` which has been\npreconfigured to behave properly for the subcommand. Most crucially, this\nmeans that `parser.prog` is set to `<top_level_program> <sub_command>` so that\nhelp messages print out correctly for the subcommand. Should your subcommand\nwant to parse arguments, this parser object should be used.\n\n### Declaring subcommands without decorators ###\n\nWhile decorators are the preferred way to specify subcommands, subcommands can\nalso be specified using the `ArgumentHandler.set_subcommands(...)` function.\nThis method expects a dictionary: keys are command names, values are the\ncommand functions:\n\n\tfrom arghandler import *\n\n\tdef echo(parser,context,args):\n\t\tprint ' '.join(args)\n\n\tdef cmd_foobar(parser,context,args):\n\t\tprint 'foobar'\n\n\thandler = ArgumentHandler()\n\thandler.set_subcommands( {'echo':echo, 'foobar':cmd_foobar} )\n\thandler.run(['echo','hello','world']) # echo will be called and 'hello world' will be printed\n\nAll the logic and rules around the context function apply here. Moreoever, the\ncomplete set of subcommands include those specified using decorators AND those\nspecified through the `set_subcommands(...)` method.\n\n#### Making subcommands in subcommands ####\nOne valuable use for the `set_subcommands(...)` method is implementing\nsubcommand options for a subcommand. For example, suppose you want a program with the following\ncommand subtree:\n\n```\npower\n - create\n - config\n - proj\n - run\n - all\n - proj\n```\n\nIn this case, `create` and `run` would be top-level subcommands that could be\ndeclared using standard `subcmd` decorators. But what about the `config` and\n`proj` commands underneath `create`? These can be created using a new\n`ArgumentHandler` inside the `create` function like this:\n\n```\ndef create_config(parser, context, args):\n parser.add_argument('location')\n args = parser.parse_args(args)\n\n # do stuff\n\n return\n\ndef create_proj(parser, context, args):\n parser.add_argument('name')\n args = parser.parse_args(args)\n\n print(f'Creating the project: {args.name}')\n\n # do stuff\n\n return\n\n\n@subcmd('create', help='create a resource')\ndef create(parser, context, args):\n handler = ArgumentHandler()\n\n handler.set_subcommands({'config': (create_config, 'create a config file'),\n 'proj': (create_proj, 'create a project')\n },\n use_registered_subcmds=False)\n\n handler.run(args)\n```\n\nNote the use of `use_registered_subcmds=False` - this is important to omit any\nfunctions globally registered as commands using the `@subcmd` decorator.\n\n### Setting the help message ###\n\nThe format of the help message can be set to one more friendly for subcommands\nby passing the `ArgumentHandler` constructor the keyword argument\n`use_subcommand_help=True`.\n\nThis will produce a help message that looks something like this:\n\n\tusage: test.py [-h] subcommand\n\n\tpositional arguments:\n\t subcommand\n cmd1 cmd1_help_str\n\n\toptional arguments:\n \t -h, --help show this help message and exit\n\n## Some best practices ##\n\n*Use `ArgumentParser` or `ArgumentHandler` inside subcommands.* This will\nensure that informative help messages are available for all your subcommands.\n\n\tfrom arghandler import *\n\n\t@subcmd\n\tdef echo(parser,context,args):\n\t\tparser.add_argument('-q','--quote_char',required=True)\n\t\targs = parser.parse_args(args)\n\t\tprint '%s%s%s' % (args.quote_char,' '.join(args),args.quote_char)\n\n\t@subcmd('foobar')\n\tdef cmd_foobar(parser,context,args):\n\t\tprint 'foobar'\n\n\thandler = ArgumentHandler()\n\thandler.run(['echo','-h']) # the help message for echo will be printed\n\n*Use logging.* Logging gives you much more control over what\ndebugging/informational content is printed out by your program. And with\n`arghandler` it's easier than ever to configure from the command line!\n\n\n",
"bugtrack_url": null,
"license": "Apache",
"summary": "argparse extended with awesome feature enhancements to make life easier",
"version": "1.3.1",
"project_urls": {
"Homepage": "http://www.github.com/druths/arghandler"
},
"split_keywords": [
"argparse",
"command-line",
"parsing"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "a9bd9321d23485d82d366e97598b3116df04665ebc3b54891038a07e94e09528",
"md5": "a4b1828971b341ad80d7ca1b88731be3",
"sha256": "cb2ca0491cde72ee1c1f22907ccd3d12eb3f7d84aa56d5c4fe20e1d7d14b94db"
},
"downloads": -1,
"filename": "arghandler-1.3.1-py3-none-any.whl",
"has_sig": false,
"md5_digest": "a4b1828971b341ad80d7ca1b88731be3",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": null,
"size": 14212,
"upload_time": "2022-02-23T22:42:41",
"upload_time_iso_8601": "2022-02-23T22:42:41.674710Z",
"url": "https://files.pythonhosted.org/packages/a9/bd/9321d23485d82d366e97598b3116df04665ebc3b54891038a07e94e09528/arghandler-1.3.1-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "814111ca052f1cf33e0c9fd4d07414f8e60bc9f97568c9d0dc43649e54ea2eaa",
"md5": "a4d314fd038e296d21265b3716fd7843",
"sha256": "497a1053c20ad512ccc972eae2c32546b7ac90b7947a17bf391db6f9da5cc25a"
},
"downloads": -1,
"filename": "arghandler-1.3.1.tar.gz",
"has_sig": false,
"md5_digest": "a4d314fd038e296d21265b3716fd7843",
"packagetype": "sdist",
"python_version": "source",
"requires_python": null,
"size": 10675,
"upload_time": "2022-02-23T22:42:45",
"upload_time_iso_8601": "2022-02-23T22:42:45.104980Z",
"url": "https://files.pythonhosted.org/packages/81/41/11ca052f1cf33e0c9fd4d07414f8e60bc9f97568c9d0dc43649e54ea2eaa/arghandler-1.3.1.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2022-02-23 22:42:45",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "druths",
"github_project": "arghandler",
"travis_ci": true,
"coveralls": false,
"github_actions": false,
"lcname": "arghandler"
}