🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
### Navigation - [index](# "General Index") - [modules](# "Python Module Index") | - [next](# "tornado.stack_context — Exception handling across asynchronous callbacks") | - [previous](# "tornado.log — Logging support") | - [Tornado 4.4.dev1 documentation](#) » - [Utilities](#) » # `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.: ~~~ from tornado.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 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: ~~~ tornado.options.parse_command_line() # or 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.: ~~~ myoption = "myvalue" myotheroption = "myothervalue" ~~~ We support [`datetimes`](https://docs.python.org/3.4/library/datetime.html#datetime.datetime "(in Python v3.4)") [https://docs.python.org/3.4/library/datetime.html#datetime.datetime], [`timedeltas`](https://docs.python.org/3.4/library/datetime.html#datetime.timedelta "(in Python v3.4)") [https://docs.python.org/3.4/library/datetime.html#datetime.timedelta], ints, and floats (just pass a `type` kwarg to[`define`](# "tornado.options.define")). We also accept multi-value options. See the documentation for[`define()`](# "tornado.options.define") below. [`tornado.options.options`](# "tornado.options.options") is a singleton instance of [`OptionParser`](# "tornado.options.OptionParser"), andthe top-level functions in this module ([`define`](# "tornado.options.define"), [`parse_command_line`](# "tornado.options.parse_command_line"), etc)simply call methods on it. You may create additional [`OptionParser`](# "tornado.options.OptionParser")instances to define isolated sets of options, such as for subcommands. Note By default, several options are defined that will configure thestandard [`logging`](https://docs.python.org/3.4/library/logging.html#module-logging "(in Python v3.4)") [https://docs.python.org/3.4/library/logging.html#module-logging] module when [`parse_command_line`](# "tornado.options.parse_command_line") or [`parse_config_file`](# "tornado.options.parse_config_file")are called. If you want Tornado to leave the logging configurationalone so you can manage it yourself, either pass `--logging=none`on the command line or do the following to disable it in code: ~~~ from tornado.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 requireunderscores. ### Global functions `tornado.options.``define`(*name*, *default=None*, *type=None*, *help=None*, *metavar=None*, *multiple=False*, *group=None*, *callback=None*)[[source]](#) Defines an option in the global namespace. See [`OptionParser.define`](# "tornado.options.OptionParser.define"). `tornado.options.``options` Global options object. All defined options are available as attributeson this object. `tornado.options.``parse_command_line`(*args=None*, *final=True*)[[source]](#) Parses global options from the command line. See [`OptionParser.parse_command_line`](# "tornado.options.OptionParser.parse_command_line"). `tornado.options.``parse_config_file`(*path*, *final=True*)[[source]](#) Parses global options from a config file. See [`OptionParser.parse_config_file`](# "tornado.options.OptionParser.parse_config_file"). `tornado.options.``print_help`(*file=sys.stderr*)[[source]](#) Prints all the command line options to stderr (or another file). See [`OptionParser.print_help`](# "tornado.options.OptionParser.print_help"). `tornado.options.``add_parse_callback`(*callback*)[[source]](#) Adds a parse callback, to be invoked when option parsing is done. See [`OptionParser.add_parse_callback`](# "tornado.options.OptionParser.add_parse_callback") *exception *`tornado.options.``Error`[[source]](#) Exception raised by errors in the options module. ### OptionParser class *class *`tornado.options.``OptionParser`[[source]](#) A collection of options, a dictionary with object-like access. Normally accessed via static functions in the [`tornado.options`](# "tornado.options") module,which reference a global instance. `items`()[[source]](#) A sequence of (name, value) pairs. New in version 3.1. `groups`()[[source]](#) The set of option-groups created by `define`. New in version 3.1. `group_dict`(*group*)[[source]](#) The names and values of options in a group. Useful for copying options into Application settings: ~~~ from tornado.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`()[[source]](#) 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*)[[source]](#) 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: ~~~ --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`](# "tornado.options.parse_command_line") or parsed from aconfig file with [`parse_config_file`](# "tornado.options.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: ~~~ 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` willoverride options set earlier on the command line, but can be overriddenby later flags. `parse_command_line`(*args=None*, *final=True*)[[source]](#) Parses all options given on the command line (defaults to[`sys.argv`](https://docs.python.org/3.4/library/sys.html#sys.argv "(in Python v3.4)") [https://docs.python.org/3.4/library/sys.html#sys.argv]). Note that `args[0]` is ignored since it is the program namein [`sys.argv`](https://docs.python.org/3.4/library/sys.html#sys.argv "(in Python v3.4)") [https://docs.python.org/3.4/library/sys.html#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. `parse_config_file`(*path*, *final=True*)[[source]](#) 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. Changed in version 4.1: Config files are now always interpreted as utf-8 instead ofthe system default encoding. `print_help`(*file=None*)[[source]](#) Prints all the command line options to stderr (or another file). `add_parse_callback`(*callback*)[[source]](#) Adds a parse callback, to be invoked when option parsing is done. `mockable`()[[source]](#) Returns a wrapper around self that is compatible with[`mock.patch`](https://docs.python.org/3.4/library/unittest.mock.html#unittest.mock.patch "(in Python v3.4)") [https://docs.python.org/3.4/library/unittest.mock.html#unittest.mock.patch]. The [`mock.patch`](https://docs.python.org/3.4/library/unittest.mock.html#unittest.mock.patch "(in Python v3.4)") [https://docs.python.org/3.4/library/unittest.mock.html#unittest.mock.patch] function (included inthe standard library [`unittest.mock`](https://docs.python.org/3.4/library/unittest.mock.html#module-unittest.mock "(in Python v3.4)") [https://docs.python.org/3.4/library/unittest.mock.html#module-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`](https://docs.python.org/3.4/library/unittest.mock.html#unittest.mock.patch.object "(in Python v3.4)") [https://docs.python.org/3.4/library/unittest.mock.html#unittest.mock.patch.object] to modify option values: ~~~ with mock.patch.object(options.mockable(), 'name', value): assert options.name == value ~~~ © Copyright 2009-2016, The Tornado Authors. Created using [Sphinx](http://sphinx-doc.org/) 1.3.5.