Welcome to opts

opts is a simple python library which allows you to easiely parse command line arguments.

Features

  • Supports so called commands e.g. hg clone.
  • Supports abbreviations of commands and options e.g. hg cl instead of hg clone or hg --he instead of hg --help.
  • Shows possible alternatives if you pass a command or an option does not exist
  • Declarative syntax for commands and parser.

Usage

Here’s a simple example:

from opts import Parser, Option, BooleanOption

parser = Parser(options={
    "filename": Option("f", "--file",
        short_description=u"write report to this file"),
    "verbose": BooleanOption("q", "quiet", default=True,
        short_description=u"don't print status messages")
})

options, arguments = parser.evaluate()

options will be a dictionary which looks like this:

# ./script
{"verbose": True}
# ./script -q
{"verbose": False}
# ./script -f /home/foobar
{"verbose": True, "file": u"/home/foobar"}
# ./script -qf /home/foobar or ./script -q -f /home/foobar
{"verbose": False, "file": u"/home/foobar"}

As you can see options will be decoded, the same goes for any remaining arguments passed to your application which can be found in the returned arguments list.

There are options for strings, booleans, numbers or even multiple strings already available but you can easiely create your own option by subclassing.

In case you have a more complicated application you might need so called commands. A command is similar to an option but it looks like a regular argument. Every other argument followed by a command will be evaluated by this command. Let’s take a dvcs for example:

from opts import Parser, Command, BooleanOption

parser = Parser(description=u"Our own awesome dvcs", commands={
    "add": Command(
        short_description=u"Adds a file to the repository",
        options={
            "dry-run": BooleanOption("n", "dry-run"),
            "interactive": BooleanOption("i", "interactive"),
        },
    ),
    "stack": Command(),
    "stash": Command(),
})

print parser.evaluate(["add"])
# ({"add": ({"dry-run": False, "interactive": False}, [])}, [])

As for the previous example opts automatically provides a help command which allows you to list every command and option associated with a command or look at the long, detailed description of a command or option.

Also the user is able to abbreviate commands:

$ ./git help
usage: ./git [commands]

Our own awesome dvcs

Commands:
 add        Adds a file to the repository
 stack      No short description.
 stash      No short description.
 help       Shows this message.

$ ./git help a # equivalent to ./git help add
usage: ./git add [options]

Adds a file to the repository.

Commands:
 help       Shows this message.

Options:
 -n --dry-run     No short description.
 -i --interactive No short description.

$ ./git help s
usage: ./git help

The given command "s" does not exist, did you mean?
 - stack
 - stash

Now you know the basic concepts and should be able to make an awesome command line interface for your application. If you need a more detailed explanation about a certain feature take a look at the API Reference.

API Reference

class Option(short=None, long=None, default=missing, short_description=None, long_description=None)

Represents a string option.

Parameters:
  • short – A short variant of the option without the prefixed -.
  • long – A long variant of the option without the prefixed --.
  • default – The default value for this option.
  • short_description – A short one-line description which can be displayed along with several other short descriptions by the help command.
  • long_description – A long detailed description.
allows_optional_argument
Set this to True if the option allows an argument but does not require it.
evaluate(callpath, argument=missing)
Evaluates the argument for this option.
requires_argument
Set to True if this option requires an argument for evaluation.
class BooleanOption(short=None, long=None, default=False, short_description=None, long_description=None)
Represents a boolean option, it evaluates always to the opposite of the default value.
class IntOption(short=None, long=None, default=missing, short_description=None, long_description=None)
Represents an integer option.
class FloatOption(short=None, long=None, default=missing, short_description=None, long_description=None)
Represents a float option.
class DecimalOption(short=None, long=None, default=missing, short_description=None, long_description=None)
Represents a decimal option.
class MultipleOptions(sub_option=<class 'opts.Option'>, short=None, long=None, default=missing, short_description=None, long_description=None)

Represents multiple values which are evaluated using the given sub_option.

The values are seperated by commas, strings containing commas can be represented using single and double quotes:

"foo,bar,baz"   -> ["foo", "bar", "baz"]
"foo,'bar,bar'" -> ["foo", "bar,baz"]
'foo,"bar,baz"' -> ["foo", "bar,baz"]
class Command(options=None, commands=None, short_description=None, long_description=None, callback=None, allow_abbreviated_commands=None, allow_abbreviated_options=None, takes_arguments=None)

Represents a command which unlike an option is not prefixed. A command can have several options and/or commands.

Options or commands can be defined by passing them to the constructor in a dictionary or by defining them declerativley on a subclass.

Parameter:callback – A function which get’s called with the result of the evaluation instead of returning it.
all_commands
A dictionary mapping the command names (including abbreviations) to a tuple of the complete command name and the command itself.
allow_abbreviated_commands
If True allows commands to be abbreviated e.g. you can pass he instead of help as long as there is no conflict with other commands.
allow_abbreviated_options
The same as allow_abbreviated_commands for long options.
evaluate(callpath, arguments)
Evaluates the given list of arguments and returns a dictionary with the options and a list with remaining arguments.
long_options
A dictionary mapping the long variants of the options to a tuple of the name of the option and the option itself.
short_options
A dictionary mapping the short variants of the options to a tuple of the name of the option and the option itself.
takes_arguments
If the command does not require any arguments additional to the options and commands, set this to False.
class Parser(options=None, commands=None, script_name=None, description=None, out_file=<open file '<stdout>', mode 'w' at 0x2baa1a9e4150>, takes_arguments=None)
evaluate(arguments=None)
Evaluates the given list of arguments and returns a dictionary with the options and a list with the remaining arguments.
out_file
A file-like object to which any output is being written.

License Text

Copyright (c) 2010, Daniel Neuhäuser

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OR MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUISNESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Table Of Contents