API Reference¶
Command decorators¶
-
argh.decorators.
aliases
(*names)¶ Defines alternative command name(s) for given function (along with its original name). Usage:
@aliases('co', 'check') def checkout(args): ...
The resulting command will be available as
checkout
,check
andco
.Note
This decorator only works with a recent version of argparse (see Python issue 9324 and Python rev 4c0426). Such version ships with Python 3.2+ and may be available in other environments as a separate package. Argh does not issue warnings and simply ignores aliases if they are not supported. See
SUPPORTS_ALIASES
.New in version 0.19.
-
argh.decorators.
named
(new_name)¶ Sets given string as command name instead of the function name. The string is used verbatim without further processing.
Usage:
@named('load') def do_load_some_stuff_and_keep_the_original_function_name(args): ...
The resulting command will be available only as
load
. To add aliases without renaming the command, checkaliases()
.New in version 0.19.
-
argh.decorators.
arg
(*args, **kwargs)¶ Declares an argument for given function. Does not register the function anywhere, nor does it modify the function in any way. The signature is exactly the same as that of
argparse.ArgumentParser.add_argument()
, only some keywords are not required if they can be easily guessed.Usage:
@arg('path') @arg('--format', choices=['yaml','json'], default='json') @arg('--dry-run', default=False) @arg('-v', '--verbosity', choices=range(0,3), default=1) def load(args): loaders = {'json': json.load, 'yaml': yaml.load} loader = loaders[args.format] data = loader(args.path) if not args.dry_run: if 1 < verbosity: print('saving to the database') put_to_database(data)
Note that:
- you didn’t have to specify
action="store_true"
for--dry-run
; - you didn’t have to specify
type=int
for--verbosity
.
- you didn’t have to specify
-
argh.decorators.
wrap_errors
(errors=None, processor=None, *args)¶ Decorator. Wraps given exceptions into
CommandError
. Usage:@wrap_errors([AssertionError]) def foo(x=None, y=None): assert x or y, 'x or y must be specified'
If the assertion fails, its message will be correctly printed and the stack hidden. This helps to avoid boilerplate code.
Parameters: - errors – A list of exception classes to catch.
- processor –
A callable that expects the exception object and returns a string. For example, this renders all wrapped errors in red colour:
from termcolor import colored def failure(err): return colored(str(err), 'red') @wrap_errors(processor=failure) def my_command(...): ...
-
argh.decorators.
expects_obj
(func)¶ Marks given function as expecting a namespace object.
Usage:
@arg('bar') @arg('--quux', default=123) @expects_obj def foo(args): yield args.bar, args.quux
This is equivalent to:
def foo(bar, quux=123): yield bar, quux
In most cases you don’t need this decorator.
Assembling¶
Functions and classes to properly assemble your commands in a parser.
-
argh.assembling.
SUPPORTS_ALIASES
= False¶ Calculated on load. If True, current version of argparse supports alternative command names (can be set via
aliases()
).
-
argh.assembling.
set_default_command
(parser, function)¶ Sets default command (i.e. a function) for given parser.
If parser.description is empty and the function has a docstring, it is used as the description.
Note
An attempt to set default command to a parser which already has subparsers (e.g. added with
add_commands()
) results in a AssemblingError.Note
If there are both explicitly declared arguments (e.g. via
arg()
) and ones inferred from the function signature (e.g. viacommand()
), declared ones will be merged into inferred ones. If an argument does not conform function signature, AssemblingError is raised.Note
If the parser was created with
add_help=True
(which is by default), option name-h
is silently removed from any argument.
-
argh.assembling.
add_commands
(parser, functions, namespace=None, namespace_kwargs=None, func_kwargs=None, title=None, description=None, help=None)¶ Adds given functions as commands to given parser.
Parameters: - parser – an
argparse.ArgumentParser
instance. - functions – a list of functions. A subparser is created for each of them.
If the function is decorated with
arg()
, the arguments are passed toargparse.ArgumentParser.add_argument
. See alsodispatch()
for requirements concerning function signatures. The command name is inferred from the function name. Note that the underscores in the name are replaced with hyphens, i.e. function name “foo_bar” becomes command name “foo-bar”. - namespace – an optional string representing the group of commands. For example, if a command named “hello” is added without the namespace, it will be available as “prog.py hello”; if the namespace if specified as “greet”, then the command will be accessible as “prog.py greet hello”. The namespace itself is not callable, so “prog.py greet” will fail and only display a help message.
- func_kwargs – a dict of keyword arguments to be passed to each nested ArgumentParser instance created per command (i.e. per function). Members of this dictionary have the highest priority, so a function’s docstring is overridden by a help in func_kwargs (if present).
- namespace_kwargs – a dict of keyword arguments to be passed to the nested ArgumentParser instance under given namespace.
Deprecated params that should be moved into namespace_kwargs:
Parameters: - title –
passed to
argparse.ArgumentParser.add_subparsers()
as title.Deprecated since version 0.26.0: Please use namespace_kwargs instead.
- description –
passed to
argparse.ArgumentParser.add_subparsers()
as description.Deprecated since version 0.26.0: Please use namespace_kwargs instead.
- help –
passed to
argparse.ArgumentParser.add_subparsers()
as help.Deprecated since version 0.26.0: Please use namespace_kwargs instead.
Note
This function modifies the parser object. Generally side effects are bad practice but we don’t seem to have any choice as ArgumentParser is pretty opaque. You may prefer
add_commands
for a bit more predictable API.Note
An attempt to add commands to a parser which already has a default function (e.g. added with
set_default_command()
) results in AssemblingError.- parser – an
-
argh.assembling.
add_subcommands
(parser, namespace, functions, **namespace_kwargs)¶ A wrapper for
add_commands()
.These examples are equivalent:
add_commands(parser, [get, put], namespace='db', namespace_kwargs={ 'title': 'database commands', 'help': 'CRUD for our silly database' }) add_subcommands(parser, 'db', [get, put], title='database commands', help='CRUD for our silly database')
Dispatching¶
-
argh.dispatching.
dispatch
(parser, argv=None, add_help_command=True, completion=True, pre_call=None, output_file=<open file '<stdout>', mode 'w'>, errors_file=<open file '<stderr>', mode 'w'>, raw_output=False, namespace=None, skip_unknown_args=False)¶ Parses given list of arguments using given parser, calls the relevant function and prints the result.
The target function should expect one positional argument: the
argparse.Namespace
object. However, if the function is decorated withplain_signature()
, the positional and named arguments from the namespace object are passed to the function instead of the object itself.Parameters: - parser – the ArgumentParser instance.
- argv – a list of strings representing the arguments. If None,
sys.argv
is used instead. Default is None. - add_help_command – if True, converts first positional argument “help” to a keyword
argument so that
help foo
becomesfoo --help
and displays usage information for “foo”. Default is True. - output_file – A file-like object for output. If None, the resulting lines are
collected and returned as a string. Default is
sys.stdout
. - errors_file – Same as output_file but for
sys.stderr
. - raw_output – If True, results are written to the output file raw, without adding whitespaces or newlines between yielded strings. Default is False.
- completion – If True, shell tab completion is enabled. Default is True. (You
will also need to install it.) See
argh.completion
. - skip_unknown_args – If True, unknown arguments do not cause an error (ArgumentParser.parse_known_args is used).
- namespace – An argparse.Namespace-like object. By default an
ArghNamespace
object is used. Please note that support for combined default and nested functions may be broken if a different type of object is forced.
By default the exceptions are not wrapped and will propagate. The only exception that is always wrapped is
CommandError
which is interpreted as an expected event so the traceback is hidden. You can also mark arbitrary exceptions as “wrappable” by using thewrap_errors()
decorator.
-
argh.dispatching.
dispatch_command
(function, *args, **kwargs)¶ A wrapper for
dispatch()
that creates a one-command parser. UsesPARSER_FORMATTER
.This:
dispatch_command(foo)
…is a shortcut for:
parser = ArgumentParser() set_default_command(parser, foo) dispatch(parser)
This function can be also used as a decorator.
-
argh.dispatching.
dispatch_commands
(functions, *args, **kwargs)¶ A wrapper for
dispatch()
that creates a parser, adds commands to the parser and dispatches them. UsesPARSER_FORMATTER
.This:
dispatch_commands([foo, bar])
…is a shortcut for:
parser = ArgumentParser() add_commands(parser, [foo, bar]) dispatch(parser)
-
class
argh.dispatching.
EntryPoint
(name=None, parser_kwargs=None)¶ An object to which functions can be attached and then dispatched.
When called with an argument, the argument (a function) is registered at this entry point as a command.
When called without an argument, dispatching is triggered with all previously registered commands.
Usage:
from argh import EntryPoint app = EntryPoint('main', dict(description='This is a cool app')) @app def ls(): for i in range(10): print i @app def greet(): print 'hello' if __name__ == '__main__': app()
Interaction¶
-
argh.interaction.
confirm
(action, default=None, skip=False)¶ A shortcut for typical confirmation prompt.
Parameters: - action – a string describing the action, e.g. “Apply changes”. A question mark will be appended.
- default – bool or None. Determines what happens when user hits
Enter
without typing in a choice. If True, default choice is “yes”. If False, it is “no”. If None the prompt keeps reappearing until user types in a choice (not necessarily acceptable) or until the number of iteration reaches the limit. Default is None. - skip – bool; if True, no interactive prompt is used and default choice is returned (useful for batch mode). Default is False.
Usage:
def delete(key, silent=False): item = db.get(Item, args.key) if confirm('Delete '+item.title, default=True, skip=silent): item.delete() print('Item deleted.') else: print('Operation cancelled.')
Returns None on KeyboardInterrupt event.
-
argh.interaction.
safe_input
(prompt)¶ Prompts user for input. Correctly handles prompt message encoding.
Shell completion¶
Command and argument completion is a great way to reduce the number of keystrokes and improve user experience.
To display suggestions when you press tab
, a shell must obtain choices
from your program. It calls the program in a specific environment and expects
it to return a list of relevant choices.
Argparse does not support completion out of the box. However, there are 3rd-party apps that do the job, such as argcomplete and python-selfcompletion.
Argh supports only argcomplete which doesn’t require subclassing the parser and monkey-patches it instead. Combining Argh with python-selfcompletion isn’t much harder though: simply use SelfCompletingArgumentParser instead of vanilla ArgumentParser.
See installation details and gotchas in the documentation of the 3rd-party app you’ve chosen for the completion backend.
Argh automatically enables completion if argcomplete is available
(see COMPLETION_ENABLED
). If completion is undesirable in given app by
design, it can be turned off by setting completion=False
in argh.dispatching.dispatch()
.
Note that you don’t have to add completion via Argh; it doesn’t matter whether you let it do it for you or use the underlying API.
Argument-level completion¶
Argcomplete supports custom “completers”. The documentation suggests adding the completer as an attribute of the argument parser action:
parser.add_argument("--env-var1").completer = EnvironCompleter
However, this doesn’t fit the normal Argh-assisted workflow.
It is recommended to use the arg()
decorator:
@arg('--env-var1', completer=EnvironCompleter)
def func(...):
...
-
argh.completion.
autocomplete
(parser)¶ Adds support for shell completion via argcomplete by patching given argparse.ArgumentParser (sub)class.
If completion is not enabled, logs a debug-level message.
-
argh.completion.
COMPLETION_ENABLED
= True¶ Dynamically set to True on load if argcomplete was successfully imported.
Helpers¶
-
class
argh.helpers.
ArghParser
(*args, **kwargs)¶ A subclass of
ArgumentParser
with support for and a couple of convenience methods.All methods are but wrappers for stand-alone functions
add_commands()
,autocomplete()
anddispatch()
.Uses
PARSER_FORMATTER
.-
add_commands
(*args, **kwargs)¶ Wrapper for
add_commands()
.
-
autocomplete
()¶ Wrapper for
autocomplete()
.
-
dispatch
(*args, **kwargs)¶ Wrapper for
dispatch()
.
-
parse_args
(args=None, namespace=None)¶ Wrapper for
argparse.ArgumentParser.parse_args()
. If namespace is not defined,argh.dispatching.ArghNamespace
is used. This is required for functions to be properly used as commands.
-
set_default_command
(*args, **kwargs)¶ Wrapper for
set_default_command()
.
-
Exceptions¶
-
exception
argh.exceptions.
AssemblingError
¶ Raised if the parser could not be configured due to malformed or conflicting command declarations.
-
exception
argh.exceptions.
CommandError
¶ Intended to be raised from within a command. The dispatcher wraps this exception by default and prints its message without traceback.
Useful for print-and-exit tasks when you expect a failure and don’t want to startle the ordinary user by the cryptic output.
Consider the following example:
def foo(args): try: ... except KeyError as e: print(u'Could not fetch item: {0}'.format(e)) return
It is exactly the same as:
def bar(args): try: ... except KeyError as e: raise CommandError(u'Could not fetch item: {0}'.format(e))
This exception can be safely used in both print-style and yield-style commands (see Tutorial).
-
exception
argh.exceptions.
DispatchingError
¶ Raised if the dispatching could not be completed due to misconfiguration which could not be determined on an earlier stage.
Output Processing¶
-
argh.io.
dump
(raw_data, output_file)¶ Writes given line to given output file. See
encode_output()
for details.
-
argh.io.
encode_output
(value, output_file)¶ Encodes given value so it can be written to given file object.
Value may be Unicode, binary string or any other data type.
The exact behaviour depends on the Python version:
Python 3.x
sys.stdout is a _io.TextIOWrapper instance that accepts str (unicode) and breaks on bytes.
It is OK to simply assume that everything is Unicode unless special handling is introduced in the client code.
Thus, no additional processing is performed.
Python 2.x
sys.stdout is a file-like object that accepts str (bytes) and breaks when unicode is passed to sys.stdout.write().
We can expect both Unicode and bytes. They need to be encoded so as to match the file object encoding.
The output is binary if the object doesn’t explicitly require Unicode.
-
argh.io.
safe_input
(prompt)¶ Prompts user for input. Correctly handles prompt message encoding.
Utilities¶
-
argh.utils.
get_arg_spec
(function)¶ Returns argument specification for given function. Omits special arguments of instance methods (self) and static methods (usually cls or something like this).
-
argh.utils.
get_subparsers
(parser, create=False)¶ Returns the
argparse._SubParsersAction
instance for givenArgumentParser
instance as would have been returned byArgumentParser.add_subparsers()
. The problem with the latter is that it only works once and raises an exception on the second attempt, and the public API seems to lack a method to get existing subparsers.Parameters: create – If True, creates the subparser if it does not exist. Default if False.