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 globaloption namespace, e.g.:

  1. from tornado.options import define, options
  2.  
  3. define("mysql_host", default="127.0.0.1:3306", help="Main user DB")
  4. define("memcache_hosts", default="127.0.0.1:11011", multiple=True,
  5. help="Main user memcache servers")
  6.  
  7. def connect():
  8. db = database.Connection(options.mysql_host)
  9. ...

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

Your main() method can parse the command line or parse a config file witheither:

  1. tornado.options.parse_command_line()
  2. # or
  3. tornado.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.:

  1. myoption = "myvalue"
  2. myotheroption = "myothervalue"

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

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

注解

By default, several options are defined that will configure thestandard logging module when parse_command_line or parse_config_fileare called. If you want Tornado to leave the logging configurationalone so you can manage it yourself, either pass —logging=noneon the command line or do the following to disable it in code:

  1. from tornado.options import options, parse_command_line
  2. options.logging = None
  3. parse_command_line()

在 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 requireunderscores.

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 attributeson this object.
tornado.options.parsecommand_line(_args=None, final=True)[源代码]

Parses global options from the command line.

See OptionParser.parse_command_line.
tornado.options.parseconfig_file(_path, final=True)[源代码]

Parses global options from a config file.

See OptionParser.parse_config_file.
tornado.options.printhelp(_file=sys.stderr)[源代码]

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

See OptionParser.print_help.
tornado.options.addparse_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 tornado.options module,which reference a global instance.
addparse_callback(_callback)[源代码]

Adds a parse callback, to be invoked when option parsing is done.
asdict()[源代码]

The names and values of all options.


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 linearguments based on the given type. If multiple is True, we acceptcomma-separated values, and the option value is always a list.

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

help and metavar are used to construct theautomatically generated command line help string. The helpmessage is formatted like:



  1. name=METAVAR help string




group is used to group the defined options in logicalgroups. By default, command line options are grouped by thefile in which they are defined.

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

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



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




With this definition, options in the file specified by —config willoverride options set earlier on the command line, but can be overriddenby later flags.
group_dict(_group)[源代码]

The names and values of options in a group.

Useful for copying options into Application settings:



  1. from tornado.options import define, parsecommandline, options

    define('templatepath', group='application')
    define('staticpath', group='application')

    parsecommand_line()

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





3.1 新版功能.

groups()[源代码]

The set of option-groups created by define.


3.1 新版功能.

items()[源代码]

A sequence of (name, value) pairs.


3.1 新版功能.

mockable()[源代码]

Returns a wrapper around self that is compatible withmock.patch.

The mock.patch function (included inthe standard library unittest.mock package since Python 3.3,or in the third-party mock package for older versions ofPython) is incompatible with objects like options thatoverride __getattr
and __setattr
. This functionreturns an object that can be used with mock.patch.object to modify option values:



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



parse_command_line(_args=None, final=True)[源代码]

Parses all options given on the command line (defaults tosys.argv).

Note that args[0] is ignored since it is the program namein 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 configurationsfrom multiple sources.
parseconfig_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 configurationsfrom multiple sources.


在 4.1 版更改: Config files are now always interpreted as utf-8 instead ofthe system default encoding.



在 4.4 版更改: The special variable file is available inside configfiles, specifying the absolute path to the config file itself.

printhelp(_file=None)[源代码]

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

原文:

https://tornado-zh-cn.readthedocs.io/zh_CN/latest/options.html