# `tornado.options` — Command-line parsing

A command line parsing module that lets modules define their own options.

Each module defines its own options which are added to the global option namespace, e.g.:

    from tornado4.options import define, options

    define("mysql_host", default="127.0.0.1:3306", help="Main user DB")
    define("memcache_hosts", default="127.0.0.1:11011", multiple=True,
           help="Main user memcache servers")

    def connect():
        db = database.Connection(options.mysql_host)
        ...

The `main()` method of your application does not need to be aware of all of the options used throughout your program; they are all automatically loaded when the modules are loaded. However, all modules that define options must have been imported before the command line is parsed.

Your `main()` method can parse the command line or parse a config file with either:

    tornado4.options.parse_command_line()
    # or
    tornado4.options.parse_config_file("/etc/server.conf")

Command line formats are what you would expect (`--myoption=myvalue`). Config files are just Python files. Global names become options, e.g.:

    myoption = "myvalue"
    myotheroption = "myothervalue"

We support `datetimes`, `timedeltas`, ints, and floats (just pass a `type` kwarg to `define`). We also accept multi-value options. See the documentation for `define()` below.

`tornado4.options.options` is a singleton instance of `OptionParser`, and the top-level functions in this module (`define`, `parse_command_line`, etc) simply call methods on it. You may create additional `OptionParser` instances to define isolated sets of options, such as for subcommands.

Note

By default, several options are defined that will configure the standard `logging` module when `parse_command_line` or `parse_config_file` are called. If you want Tornado to leave the logging configuration alone so you can manage it yourself, either pass `--logging=none` on the command line or do the following to disable it in code:

    from tornado4.options import options, parse_command_line
    options.logging = None
    parse_command_line()

Changed in version 4.3: Dashes and underscores are fully interchangeable in option names; options can be defined, set, and read with any mix of the two. Dashes are typical for command-line usage while config files require underscores.

## Global functions

`tornado.options.``define`(name, default=None, type=None, help=None, metavar=None, multiple=False, group=None, callback=None)

  Defines an option in the global namespace.

  See `OptionParser.define`.

`tornado.options.``options`

  Global options object. All defined options are available as attributes on this object.

`tornado.options.``parse_command_line`(args=None, final=True)

  Parses global options from the command line.

  See `OptionParser.parse_command_line`.

`tornado.options.``parse_config_file`(path, final=True)

  Parses global options from a config file.

  See `OptionParser.parse_config_file`.

`tornado.options.``print_help`(file=sys.stderr)

  Prints all the command line options to stderr (or another file).

  See `OptionParser.print_help`.

`tornado.options.``add_parse_callback`(callback)

  Adds a parse callback, to be invoked when option parsing is done.

  See `OptionParser.add_parse_callback`

exception `tornado.options.``Error`

  Exception raised by errors in the options module.

## OptionParser class

class `tornado.options.``OptionParser`

  A collection of options, a dictionary with object-like access.

  Normally accessed via static functions in the `tornado4.options` module, which reference a global instance.

  `items`()

    A sequence of (name, value) pairs.

    New in version 3.1.

  `groups`()

    The set of option-groups created by `define`.

    New in version 3.1.

  `group_dict`(group)

    The names and values of options in a group.

    Useful for copying options into Application settings:

        from tornado4.options import define, parse_command_line, options

        define('template_path', group='application')
        define('static_path', group='application')

        parse_command_line()

        application = Application(
            handlers, **options.group_dict('application'))

    New in version 3.1.

  `as_dict`()

    The names and values of all options.

    New in version 3.1.

  `define`(name, default=None, type=None, help=None, metavar=None, multiple=False, group=None, callback=None)

    Defines a new command line option.

    If `type` is given (one of str, float, int, datetime, or timedelta) or can be inferred from the `default`, we parse the command line arguments based on the given type. If `multiple` is True, we accept comma-separated values, and the option value is always a list.

    For multi-value integers, we also accept the syntax `x:y`, which turns into `range(x, y)` - very useful for long integer ranges.

    `help` and `metavar` are used to construct the automatically generated command line help string. The help message is formatted like:

        --name=METAVAR      help string

    `group` is used to group the defined options in logical groups. By default, command line options are grouped by the file in which they are defined.

    Command line option names must be unique globally. They can be parsed from the command line with `parse_command_line` or parsed from a config file with `parse_config_file`.

    If a `callback` is given, it will be run with the new value whenever the option is changed. This can be used to combine command-line and file-based options:

        define("config", type=str, help="path to config file",
               callback=lambda path: parse_config_file(path, final=False))

    With this definition, options in the file specified by `--config` will override options set earlier on the command line, but can be overridden by later flags.

  `parse_command_line`(args=None, final=True)

    Parses all options given on the command line (defaults to `sys.argv`).

    Note that `args[0]` is ignored since it is the program name in `sys.argv`.

    We return a list of all arguments that are not parsed as options.

    If `final` is `False`, parse callbacks will not be run. This is useful for applications that wish to combine configurations from multiple sources.

  `parse_config_file`(path, final=True)

    Parses and loads the Python config file at the given path.

    If `final` is `False`, parse callbacks will not be run. This is useful for applications that wish to combine configurations from multiple sources.

    Changed in version 4.1: Config files are now always interpreted as utf-8 instead of the system default encoding.

    Changed in version 4.4: The special variable `__file__` is available inside config files, specifying the absolute path to the config file itself.

  `print_help`(file=None)

    Prints all the command line options to stderr (or another file).

  `add_parse_callback`(callback)

    Adds a parse callback, to be invoked when option parsing is done.

  `mockable`()

    Returns a wrapper around self that is compatible with `mock.patch`.

    The `mock.patch` function (included in the standard library `unittest.mock` package since Python 3.3, or in the third-party `mock` package for older versions of Python) is incompatible with objects like `options` that override `__getattr__` and `__setattr__`. This function returns an object that can be used with `mock.patch.object` to modify option values:

        with mock.patch.object(options.mockable(), 'name', value):
            assert options.name == value