options.py 20 KB

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