options.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  1. #
  2. # Copyright 2009 Facebook
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  5. # not use this file except in compliance with the License. You may obtain
  6. # a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. # License for the specific language governing permissions and limitations
  14. # under the License.
  15. """A command line parsing module that lets modules define their own options.
  16. This module is inspired by Google's `gflags
  17. <https://github.com/google/python-gflags>`_. The primary difference
  18. with libraries such as `argparse` is that a global registry is used so
  19. that options may be defined in any module (it also enables
  20. `tornado.log` by default). The rest of Tornado does not depend on this
  21. module, so feel free to use `argparse` or other configuration
  22. libraries if you prefer them.
  23. Options must be defined with `tornado.options.define` before use,
  24. generally at the top level of a module. The options are then
  25. accessible as attributes of `tornado.options.options`::
  26. # myapp/db.py
  27. from tornado.options import define, options
  28. define("mysql_host", default="127.0.0.1:3306", help="Main user DB")
  29. define("memcache_hosts", default="127.0.0.1:11011", multiple=True,
  30. help="Main user memcache servers")
  31. def connect():
  32. db = database.Connection(options.mysql_host)
  33. ...
  34. # myapp/server.py
  35. from tornado.options import define, options
  36. define("port", default=8080, help="port to listen on")
  37. def start_server():
  38. app = make_app()
  39. app.listen(options.port)
  40. The ``main()`` method of your application does not need to be aware of all of
  41. the options used throughout your program; they are all automatically loaded
  42. when the modules are loaded. However, all modules that define options
  43. must have been imported before the command line is parsed.
  44. Your ``main()`` method can parse the command line or parse a config file with
  45. either `parse_command_line` or `parse_config_file`::
  46. import myapp.db, myapp.server
  47. import tornado.options
  48. if __name__ == '__main__':
  49. tornado.options.parse_command_line()
  50. # or
  51. tornado.options.parse_config_file("/etc/server.conf")
  52. .. note::
  53. When using multiple ``parse_*`` functions, pass ``final=False`` to all
  54. but the last one, or side effects may occur twice (in particular,
  55. this can result in log messages being doubled).
  56. `tornado.options.options` is a singleton instance of `OptionParser`, and
  57. the top-level functions in this module (`define`, `parse_command_line`, etc)
  58. simply call methods on it. You may create additional `OptionParser`
  59. instances to define isolated sets of options, such as for subcommands.
  60. .. note::
  61. By default, several options are defined that will configure the
  62. standard `logging` module when `parse_command_line` or `parse_config_file`
  63. are called. If you want Tornado to leave the logging configuration
  64. alone so you can manage it yourself, either pass ``--logging=none``
  65. on the command line or do the following to disable it in code::
  66. from tornado.options import options, parse_command_line
  67. options.logging = None
  68. parse_command_line()
  69. .. versionchanged:: 4.3
  70. Dashes and underscores are fully interchangeable in option names;
  71. options can be defined, set, and read with any mix of the two.
  72. Dashes are typical for command-line usage while config files require
  73. underscores.
  74. """
  75. from __future__ import absolute_import, division, print_function
  76. import datetime
  77. import numbers
  78. import re
  79. import sys
  80. import os
  81. import textwrap
  82. from tornado.escape import _unicode, native_str
  83. from tornado.log import define_logging_options
  84. from tornado import stack_context
  85. from tornado.util import basestring_type, exec_in
  86. class Error(Exception):
  87. """Exception raised by errors in the options module."""
  88. pass
  89. class OptionParser(object):
  90. """A collection of options, a dictionary with object-like access.
  91. Normally accessed via static functions in the `tornado.options` module,
  92. which reference a global instance.
  93. """
  94. def __init__(self):
  95. # we have to use self.__dict__ because we override setattr.
  96. self.__dict__['_options'] = {}
  97. self.__dict__['_parse_callbacks'] = []
  98. self.define("help", type=bool, help="show this help information",
  99. callback=self._help_callback)
  100. def _normalize_name(self, name):
  101. return name.replace('_', '-')
  102. def __getattr__(self, name):
  103. name = self._normalize_name(name)
  104. if isinstance(self._options.get(name), _Option):
  105. return self._options[name].value()
  106. raise AttributeError("Unrecognized option %r" % name)
  107. def __setattr__(self, name, value):
  108. name = self._normalize_name(name)
  109. if isinstance(self._options.get(name), _Option):
  110. return self._options[name].set(value)
  111. raise AttributeError("Unrecognized option %r" % name)
  112. def __iter__(self):
  113. return (opt.name for opt in self._options.values())
  114. def __contains__(self, name):
  115. name = self._normalize_name(name)
  116. return name in self._options
  117. def __getitem__(self, name):
  118. return self.__getattr__(name)
  119. def __setitem__(self, name, value):
  120. return self.__setattr__(name, value)
  121. def items(self):
  122. """A sequence of (name, value) pairs.
  123. .. versionadded:: 3.1
  124. """
  125. return [(opt.name, opt.value()) for name, opt in self._options.items()]
  126. def groups(self):
  127. """The set of option-groups created by ``define``.
  128. .. versionadded:: 3.1
  129. """
  130. return set(opt.group_name for opt in self._options.values())
  131. def group_dict(self, group):
  132. """The names and values of options in a group.
  133. Useful for copying options into Application settings::
  134. from tornado.options import define, parse_command_line, options
  135. define('template_path', group='application')
  136. define('static_path', group='application')
  137. parse_command_line()
  138. application = Application(
  139. handlers, **options.group_dict('application'))
  140. .. versionadded:: 3.1
  141. """
  142. return dict(
  143. (opt.name, opt.value()) for name, opt in self._options.items()
  144. if not group or group == opt.group_name)
  145. def as_dict(self):
  146. """The names and values of all options.
  147. .. versionadded:: 3.1
  148. """
  149. return dict(
  150. (opt.name, opt.value()) for name, opt in self._options.items())
  151. def define(self, name, default=None, type=None, help=None, metavar=None,
  152. multiple=False, group=None, callback=None):
  153. """Defines a new command line option.
  154. ``type`` can be any of `str`, `int`, `float`, `bool`,
  155. `~datetime.datetime`, or `~datetime.timedelta`. If no ``type``
  156. is given but a ``default`` is, ``type`` is the type of
  157. ``default``. Otherwise, ``type`` defaults to `str`.
  158. If ``multiple`` is True, the option value is a list of ``type``
  159. instead of an instance of ``type``.
  160. ``help`` and ``metavar`` are used to construct the
  161. automatically generated command line help string. The help
  162. message is formatted like::
  163. --name=METAVAR help string
  164. ``group`` is used to group the defined options in logical
  165. groups. By default, command line options are grouped by the
  166. file in which they are defined.
  167. Command line option names must be unique globally.
  168. If a ``callback`` is given, it will be run with the new value whenever
  169. the option is changed. This can be used to combine command-line
  170. and file-based options::
  171. define("config", type=str, help="path to config file",
  172. callback=lambda path: parse_config_file(path, final=False))
  173. With this definition, options in the file specified by ``--config`` will
  174. override options set earlier on the command line, but can be overridden
  175. by later flags.
  176. """
  177. normalized = self._normalize_name(name)
  178. if normalized in self._options:
  179. raise Error("Option %r already defined in %s" %
  180. (normalized, self._options[normalized].file_name))
  181. frame = sys._getframe(0)
  182. options_file = frame.f_code.co_filename
  183. # Can be called directly, or through top level define() fn, in which
  184. # case, step up above that frame to look for real caller.
  185. if (frame.f_back.f_code.co_filename == options_file and
  186. frame.f_back.f_code.co_name == 'define'):
  187. frame = frame.f_back
  188. file_name = frame.f_back.f_code.co_filename
  189. if file_name == options_file:
  190. file_name = ""
  191. if type is None:
  192. if not multiple and default is not None:
  193. type = default.__class__
  194. else:
  195. type = str
  196. if group:
  197. group_name = group
  198. else:
  199. group_name = file_name
  200. option = _Option(name, file_name=file_name,
  201. default=default, type=type, help=help,
  202. metavar=metavar, multiple=multiple,
  203. group_name=group_name,
  204. callback=callback)
  205. self._options[normalized] = option
  206. def parse_command_line(self, args=None, final=True):
  207. """Parses all options given on the command line (defaults to
  208. `sys.argv`).
  209. Options look like ``--option=value`` and are parsed according
  210. to their ``type``. For boolean options, ``--option`` is
  211. equivalent to ``--option=true``
  212. If the option has ``multiple=True``, comma-separated values
  213. are accepted. For multi-value integer options, the syntax
  214. ``x:y`` is also accepted and equivalent to ``range(x, y)``.
  215. Note that ``args[0]`` is ignored since it is the program name
  216. in `sys.argv`.
  217. We return a list of all arguments that are not parsed as options.
  218. If ``final`` is ``False``, parse callbacks will not be run.
  219. This is useful for applications that wish to combine configurations
  220. from multiple sources.
  221. """
  222. if args is None:
  223. args = sys.argv
  224. remaining = []
  225. for i in range(1, len(args)):
  226. # All things after the last option are command line arguments
  227. if not args[i].startswith("-"):
  228. remaining = args[i:]
  229. break
  230. if args[i] == "--":
  231. remaining = args[i + 1:]
  232. break
  233. arg = args[i].lstrip("-")
  234. name, equals, value = arg.partition("=")
  235. name = self._normalize_name(name)
  236. if name not in self._options:
  237. self.print_help()
  238. raise Error('Unrecognized command line option: %r' % name)
  239. option = self._options[name]
  240. if not equals:
  241. if option.type == bool:
  242. value = "true"
  243. else:
  244. raise Error('Option %r requires a value' % name)
  245. option.parse(value)
  246. if final:
  247. self.run_parse_callbacks()
  248. return remaining
  249. def parse_config_file(self, path, final=True):
  250. """Parses and loads the config file at the given path.
  251. The config file contains Python code that will be executed (so
  252. it is **not safe** to use untrusted config files). Anything in
  253. the global namespace that matches a defined option will be
  254. used to set that option's value.
  255. Options may either be the specified type for the option or
  256. strings (in which case they will be parsed the same way as in
  257. `.parse_command_line`)
  258. Example (using the options defined in the top-level docs of
  259. this module)::
  260. port = 80
  261. mysql_host = 'mydb.example.com:3306'
  262. # Both lists and comma-separated strings are allowed for
  263. # multiple=True.
  264. memcache_hosts = ['cache1.example.com:11011',
  265. 'cache2.example.com:11011']
  266. memcache_hosts = 'cache1.example.com:11011,cache2.example.com:11011'
  267. If ``final`` is ``False``, parse callbacks will not be run.
  268. This is useful for applications that wish to combine configurations
  269. from multiple sources.
  270. .. note::
  271. `tornado.options` is primarily a command-line library.
  272. Config file support is provided for applications that wish
  273. to use it, but applications that prefer config files may
  274. wish to look at other libraries instead.
  275. .. versionchanged:: 4.1
  276. Config files are now always interpreted as utf-8 instead of
  277. the system default encoding.
  278. .. versionchanged:: 4.4
  279. The special variable ``__file__`` is available inside config
  280. files, specifying the absolute path to the config file itself.
  281. .. versionchanged:: 5.1
  282. Added the ability to set options via strings in config files.
  283. """
  284. config = {'__file__': os.path.abspath(path)}
  285. with open(path, 'rb') as f:
  286. exec_in(native_str(f.read()), config, config)
  287. for name in config:
  288. normalized = self._normalize_name(name)
  289. if normalized in self._options:
  290. option = self._options[normalized]
  291. if option.multiple:
  292. if not isinstance(config[name], (list, str)):
  293. raise Error("Option %r is required to be a list of %s "
  294. "or a comma-separated string" %
  295. (option.name, option.type.__name__))
  296. if type(config[name]) == str and option.type != str:
  297. option.parse(config[name])
  298. else:
  299. option.set(config[name])
  300. if final:
  301. self.run_parse_callbacks()
  302. def print_help(self, file=None):
  303. """Prints all the command line options to stderr (or another file)."""
  304. if file is None:
  305. file = sys.stderr
  306. print("Usage: %s [OPTIONS]" % sys.argv[0], file=file)
  307. print("\nOptions:\n", file=file)
  308. by_group = {}
  309. for option in self._options.values():
  310. by_group.setdefault(option.group_name, []).append(option)
  311. for filename, o in sorted(by_group.items()):
  312. if filename:
  313. print("\n%s options:\n" % os.path.normpath(filename), file=file)
  314. o.sort(key=lambda option: option.name)
  315. for option in o:
  316. # Always print names with dashes in a CLI context.
  317. prefix = self._normalize_name(option.name)
  318. if option.metavar:
  319. prefix += "=" + option.metavar
  320. description = option.help or ""
  321. if option.default is not None and option.default != '':
  322. description += " (default %s)" % option.default
  323. lines = textwrap.wrap(description, 79 - 35)
  324. if len(prefix) > 30 or len(lines) == 0:
  325. lines.insert(0, '')
  326. print(" --%-30s %s" % (prefix, lines[0]), file=file)
  327. for line in lines[1:]:
  328. print("%-34s %s" % (' ', line), file=file)
  329. print(file=file)
  330. def _help_callback(self, value):
  331. if value:
  332. self.print_help()
  333. sys.exit(0)
  334. def add_parse_callback(self, callback):
  335. """Adds a parse callback, to be invoked when option parsing is done."""
  336. self._parse_callbacks.append(stack_context.wrap(callback))
  337. def run_parse_callbacks(self):
  338. for callback in self._parse_callbacks:
  339. callback()
  340. def mockable(self):
  341. """Returns a wrapper around self that is compatible with
  342. `mock.patch <unittest.mock.patch>`.
  343. The `mock.patch <unittest.mock.patch>` function (included in
  344. the standard library `unittest.mock` package since Python 3.3,
  345. or in the third-party ``mock`` package for older versions of
  346. Python) is incompatible with objects like ``options`` that
  347. override ``__getattr__`` and ``__setattr__``. This function
  348. returns an object that can be used with `mock.patch.object
  349. <unittest.mock.patch.object>` to modify option values::
  350. with mock.patch.object(options.mockable(), 'name', value):
  351. assert options.name == value
  352. """
  353. return _Mockable(self)
  354. class _Mockable(object):
  355. """`mock.patch` compatible wrapper for `OptionParser`.
  356. As of ``mock`` version 1.0.1, when an object uses ``__getattr__``
  357. hooks instead of ``__dict__``, ``patch.__exit__`` tries to delete
  358. the attribute it set instead of setting a new one (assuming that
  359. the object does not catpure ``__setattr__``, so the patch
  360. created a new attribute in ``__dict__``).
  361. _Mockable's getattr and setattr pass through to the underlying
  362. OptionParser, and delattr undoes the effect of a previous setattr.
  363. """
  364. def __init__(self, options):
  365. # Modify __dict__ directly to bypass __setattr__
  366. self.__dict__['_options'] = options
  367. self.__dict__['_originals'] = {}
  368. def __getattr__(self, name):
  369. return getattr(self._options, name)
  370. def __setattr__(self, name, value):
  371. assert name not in self._originals, "don't reuse mockable objects"
  372. self._originals[name] = getattr(self._options, name)
  373. setattr(self._options, name, value)
  374. def __delattr__(self, name):
  375. setattr(self._options, name, self._originals.pop(name))
  376. class _Option(object):
  377. UNSET = object()
  378. def __init__(self, name, default=None, type=basestring_type, help=None,
  379. metavar=None, multiple=False, file_name=None, group_name=None,
  380. callback=None):
  381. if default is None and multiple:
  382. default = []
  383. self.name = name
  384. self.type = type
  385. self.help = help
  386. self.metavar = metavar
  387. self.multiple = multiple
  388. self.file_name = file_name
  389. self.group_name = group_name
  390. self.callback = callback
  391. self.default = default
  392. self._value = _Option.UNSET
  393. def value(self):
  394. return self.default if self._value is _Option.UNSET else self._value
  395. def parse(self, value):
  396. _parse = {
  397. datetime.datetime: self._parse_datetime,
  398. datetime.timedelta: self._parse_timedelta,
  399. bool: self._parse_bool,
  400. basestring_type: self._parse_string,
  401. }.get(self.type, self.type)
  402. if self.multiple:
  403. self._value = []
  404. for part in value.split(","):
  405. if issubclass(self.type, numbers.Integral):
  406. # allow ranges of the form X:Y (inclusive at both ends)
  407. lo, _, hi = part.partition(":")
  408. lo = _parse(lo)
  409. hi = _parse(hi) if hi else lo
  410. self._value.extend(range(lo, hi + 1))
  411. else:
  412. self._value.append(_parse(part))
  413. else:
  414. self._value = _parse(value)
  415. if self.callback is not None:
  416. self.callback(self._value)
  417. return self.value()
  418. def set(self, value):
  419. if self.multiple:
  420. if not isinstance(value, list):
  421. raise Error("Option %r is required to be a list of %s" %
  422. (self.name, self.type.__name__))
  423. for item in value:
  424. if item is not None and not isinstance(item, self.type):
  425. raise Error("Option %r is required to be a list of %s" %
  426. (self.name, self.type.__name__))
  427. else:
  428. if value is not None and not isinstance(value, self.type):
  429. raise Error("Option %r is required to be a %s (%s given)" %
  430. (self.name, self.type.__name__, type(value)))
  431. self._value = value
  432. if self.callback is not None:
  433. self.callback(self._value)
  434. # Supported date/time formats in our options
  435. _DATETIME_FORMATS = [
  436. "%a %b %d %H:%M:%S %Y",
  437. "%Y-%m-%d %H:%M:%S",
  438. "%Y-%m-%d %H:%M",
  439. "%Y-%m-%dT%H:%M",
  440. "%Y%m%d %H:%M:%S",
  441. "%Y%m%d %H:%M",
  442. "%Y-%m-%d",
  443. "%Y%m%d",
  444. "%H:%M:%S",
  445. "%H:%M",
  446. ]
  447. def _parse_datetime(self, value):
  448. for format in self._DATETIME_FORMATS:
  449. try:
  450. return datetime.datetime.strptime(value, format)
  451. except ValueError:
  452. pass
  453. raise Error('Unrecognized date/time format: %r' % value)
  454. _TIMEDELTA_ABBREV_DICT = {
  455. 'h': 'hours',
  456. 'm': 'minutes',
  457. 'min': 'minutes',
  458. 's': 'seconds',
  459. 'sec': 'seconds',
  460. 'ms': 'milliseconds',
  461. 'us': 'microseconds',
  462. 'd': 'days',
  463. 'w': 'weeks',
  464. }
  465. _FLOAT_PATTERN = r'[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?'
  466. _TIMEDELTA_PATTERN = re.compile(
  467. r'\s*(%s)\s*(\w*)\s*' % _FLOAT_PATTERN, re.IGNORECASE)
  468. def _parse_timedelta(self, value):
  469. try:
  470. sum = datetime.timedelta()
  471. start = 0
  472. while start < len(value):
  473. m = self._TIMEDELTA_PATTERN.match(value, start)
  474. if not m:
  475. raise Exception()
  476. num = float(m.group(1))
  477. units = m.group(2) or 'seconds'
  478. units = self._TIMEDELTA_ABBREV_DICT.get(units, units)
  479. sum += datetime.timedelta(**{units: num})
  480. start = m.end()
  481. return sum
  482. except Exception:
  483. raise
  484. def _parse_bool(self, value):
  485. return value.lower() not in ("false", "0", "f")
  486. def _parse_string(self, value):
  487. return _unicode(value)
  488. options = OptionParser()
  489. """Global options object.
  490. All defined options are available as attributes on this object.
  491. """
  492. def define(name, default=None, type=None, help=None, metavar=None,
  493. multiple=False, group=None, callback=None):
  494. """Defines an option in the global namespace.
  495. See `OptionParser.define`.
  496. """
  497. return options.define(name, default=default, type=type, help=help,
  498. metavar=metavar, multiple=multiple, group=group,
  499. callback=callback)
  500. def parse_command_line(args=None, final=True):
  501. """Parses global options from the command line.
  502. See `OptionParser.parse_command_line`.
  503. """
  504. return options.parse_command_line(args, final=final)
  505. def parse_config_file(path, final=True):
  506. """Parses global options from a config file.
  507. See `OptionParser.parse_config_file`.
  508. """
  509. return options.parse_config_file(path, final=final)
  510. def print_help(file=None):
  511. """Prints all the command line options to stderr (or another file).
  512. See `OptionParser.print_help`.
  513. """
  514. return options.print_help(file)
  515. def add_parse_callback(callback):
  516. """Adds a parse callback, to be invoked when option parsing is done.
  517. See `OptionParser.add_parse_callback`
  518. """
  519. options.add_parse_callback(callback)
  520. # Default options
  521. define_logging_options(options)