Commands are the central focus of Clap. Even if you’re just writing a plain old application, you will need to use a command if you want to use a Base.
The most straightforward way to create a command is to create a subclass of the class Command.
In addition to the run(options, arguments) method, you can (and should) also override:
The most important part is the options. You can have a static iterable of Option instances named options, as well as an instance method named get_options that returns an iterable. A property named all_options does a union of both.
When a command is added to a base, its set_base() method is called. This sets the base attribute to the given base.
You should override this method to do whatever you want this command to do when it is called from the command line.
Parameters: |
|
---|
You can also use a decorator, command(), to create commands.
This is a magical command decorator. You pass it various options, and it will return a function you can decorate another function with to make it a command.
Parameters: |
|
---|
For example:
@command(
options=(
Option('l', 'language', argument=True, desc="Language to write "
"Hello, World in")
),
aliases=('hi',),
short_desc=DOC,
long_desc=DOC,
usage='[OPTIONS] [PERSON]'
)
def hello(options, arguments):
"Prints 'Hello, world!' or just 'Hello' to a given person"
if arguments:
person = arguments[0]
else:
person = None
if options['language'] == 'es':
print "Hola, %s!" % (person or 'mundo')
else:
print "Hello, %s!" % (person or 'world')
If you want to interrupt the command with a “normal” error message, then raise a ScriptError exception with your message. It will be displayed as a normal usage error would.
If your command encounters an error due to something the user did, raise ScriptError with the error message, like this:
raise ScriptError("can't read from a file and stdin at the same time")
The Base will automatically display it as it would a usage error, without the full traceback listing.
Parameters: |
|
---|