options.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  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. import datetime
  76. import numbers
  77. import re
  78. import sys
  79. import os
  80. import textwrap
  81. from tornado.escape import _unicode, native_str
  82. from tornado.log import define_logging_options
  83. from tornado.util import basestring_type, exec_in
  84. import typing
  85. from typing import Any, Iterator, Iterable, Tuple, Set, Dict, Callable, List, TextIO
  86. if typing.TYPE_CHECKING:
  87. from typing import Optional # noqa: F401
  88. class Error(Exception):
  89. """Exception raised by errors in the options module."""
  90. pass
  91. class OptionParser(object):
  92. """A collection of options, a dictionary with object-like access.
  93. Normally accessed via static functions in the `tornado.options` module,
  94. which reference a global instance.
  95. """
  96. def __init__(self) -> None:
  97. # we have to use self.__dict__ because we override setattr.
  98. self.__dict__["_options"] = {}
  99. self.__dict__["_parse_callbacks"] = []
  100. self.define(
  101. "help",
  102. type=bool,
  103. help="show this help information",
  104. callback=self._help_callback,
  105. )
  106. def _normalize_name(self, name: str) -> str:
  107. return name.replace("_", "-")
  108. def __getattr__(self, name: str) -> Any:
  109. name = self._normalize_name(name)
  110. if isinstance(self._options.get(name), _Option):
  111. return self._options[name].value()
  112. raise AttributeError("Unrecognized option %r" % name)
  113. def __setattr__(self, name: str, value: Any) -> None:
  114. name = self._normalize_name(name)
  115. if isinstance(self._options.get(name), _Option):
  116. return self._options[name].set(value)
  117. raise AttributeError("Unrecognized option %r" % name)
  118. def __iter__(self) -> Iterator:
  119. return (opt.name for opt in self._options.values())
  120. def __contains__(self, name: str) -> bool:
  121. name = self._normalize_name(name)
  122. return name in self._options
  123. def __getitem__(self, name: str) -> Any:
  124. return self.__getattr__(name)
  125. def __setitem__(self, name: str, value: Any) -> None:
  126. return self.__setattr__(name, value)
  127. def items(self) -> Iterable[Tuple[str, Any]]:
  128. """An iterable of (name, value) pairs.
  129. .. versionadded:: 3.1
  130. """
  131. return [(opt.name, opt.value()) for name, opt in self._options.items()]
  132. def groups(self) -> Set[str]:
  133. """The set of option-groups created by ``define``.
  134. .. versionadded:: 3.1
  135. """
  136. return set(opt.group_name for opt in self._options.values())
  137. def group_dict(self, group: str) -> Dict[str, Any]:
  138. """The names and values of options in a group.
  139. Useful for copying options into Application settings::
  140. from tornado.options import define, parse_command_line, options
  141. define('template_path', group='application')
  142. define('static_path', group='application')
  143. parse_command_line()
  144. application = Application(
  145. handlers, **options.group_dict('application'))
  146. .. versionadded:: 3.1
  147. """
  148. return dict(
  149. (opt.name, opt.value())
  150. for name, opt in self._options.items()
  151. if not group or group == opt.group_name
  152. )
  153. def as_dict(self) -> Dict[str, Any]:
  154. """The names and values of all options.
  155. .. versionadded:: 3.1
  156. """
  157. return dict((opt.name, opt.value()) for name, opt in self._options.items())
  158. def define(
  159. self,
  160. name: str,
  161. default: Any = None,
  162. type: type = None,
  163. help: str = None,
  164. metavar: str = None,
  165. multiple: bool = False,
  166. group: str = None,
  167. callback: Callable[[Any], None] = None,
  168. ) -> None:
  169. """Defines a new command line option.
  170. ``type`` can be any of `str`, `int`, `float`, `bool`,
  171. `~datetime.datetime`, or `~datetime.timedelta`. If no ``type``
  172. is given but a ``default`` is, ``type`` is the type of
  173. ``default``. Otherwise, ``type`` defaults to `str`.
  174. If ``multiple`` is True, the option value is a list of ``type``
  175. instead of an instance of ``type``.
  176. ``help`` and ``metavar`` are used to construct the
  177. automatically generated command line help string. The help
  178. message is formatted like::
  179. --name=METAVAR help string
  180. ``group`` is used to group the defined options in logical
  181. groups. By default, command line options are grouped by the
  182. file in which they are defined.
  183. Command line option names must be unique globally.
  184. If a ``callback`` is given, it will be run with the new value whenever
  185. the option is changed. This can be used to combine command-line
  186. and file-based options::
  187. define("config", type=str, help="path to config file",
  188. callback=lambda path: parse_config_file(path, final=False))
  189. With this definition, options in the file specified by ``--config`` will
  190. override options set earlier on the command line, but can be overridden
  191. by later flags.
  192. """
  193. normalized = self._normalize_name(name)
  194. if normalized in self._options:
  195. raise Error(
  196. "Option %r already defined in %s"
  197. % (normalized, self._options[normalized].file_name)
  198. )
  199. frame = sys._getframe(0)
  200. options_file = frame.f_code.co_filename
  201. # Can be called directly, or through top level define() fn, in which
  202. # case, step up above that frame to look for real caller.
  203. if (
  204. frame.f_back.f_code.co_filename == options_file
  205. and frame.f_back.f_code.co_name == "define"
  206. ):
  207. frame = frame.f_back
  208. file_name = frame.f_back.f_code.co_filename
  209. if file_name == options_file:
  210. file_name = ""
  211. if type is None:
  212. if not multiple and default is not None:
  213. type = default.__class__
  214. else:
  215. type = str
  216. if group:
  217. group_name = group # type: Optional[str]
  218. else:
  219. group_name = file_name
  220. option = _Option(
  221. name,
  222. file_name=file_name,
  223. default=default,
  224. type=type,
  225. help=help,
  226. metavar=metavar,
  227. multiple=multiple,
  228. group_name=group_name,
  229. callback=callback,
  230. )
  231. self._options[normalized] = option
  232. def parse_command_line(
  233. self, args: List[str] = None, final: bool = True
  234. ) -> List[str]:
  235. """Parses all options given on the command line (defaults to
  236. `sys.argv`).
  237. Options look like ``--option=value`` and are parsed according
  238. to their ``type``. For boolean options, ``--option`` is
  239. equivalent to ``--option=true``
  240. If the option has ``multiple=True``, comma-separated values
  241. are accepted. For multi-value integer options, the syntax
  242. ``x:y`` is also accepted and equivalent to ``range(x, y)``.
  243. Note that ``args[0]`` is ignored since it is the program name
  244. in `sys.argv`.
  245. We return a list of all arguments that are not parsed as options.
  246. If ``final`` is ``False``, parse callbacks will not be run.
  247. This is useful for applications that wish to combine configurations
  248. from multiple sources.
  249. """
  250. if args is None:
  251. args = sys.argv
  252. remaining = [] # type: List[str]
  253. for i in range(1, len(args)):
  254. # All things after the last option are command line arguments
  255. if not args[i].startswith("-"):
  256. remaining = args[i:]
  257. break
  258. if args[i] == "--":
  259. remaining = args[i + 1 :]
  260. break
  261. arg = args[i].lstrip("-")
  262. name, equals, value = arg.partition("=")
  263. name = self._normalize_name(name)
  264. if name not in self._options:
  265. self.print_help()
  266. raise Error("Unrecognized command line option: %r" % name)
  267. option = self._options[name]
  268. if not equals:
  269. if option.type == bool:
  270. value = "true"
  271. else:
  272. raise Error("Option %r requires a value" % name)
  273. option.parse(value)
  274. if final:
  275. self.run_parse_callbacks()
  276. return remaining
  277. def parse_config_file(self, path: str, final: bool = True) -> None:
  278. """Parses and loads the config file at the given path.
  279. The config file contains Python code that will be executed (so
  280. it is **not safe** to use untrusted config files). Anything in
  281. the global namespace that matches a defined option will be
  282. used to set that option's value.
  283. Options may either be the specified type for the option or
  284. strings (in which case they will be parsed the same way as in
  285. `.parse_command_line`)
  286. Example (using the options defined in the top-level docs of
  287. this module)::
  288. port = 80
  289. mysql_host = 'mydb.example.com:3306'
  290. # Both lists and comma-separated strings are allowed for
  291. # multiple=True.
  292. memcache_hosts = ['cache1.example.com:11011',
  293. 'cache2.example.com:11011']
  294. memcache_hosts = 'cache1.example.com:11011,cache2.example.com:11011'
  295. If ``final`` is ``False``, parse callbacks will not be run.
  296. This is useful for applications that wish to combine configurations
  297. from multiple sources.
  298. .. note::
  299. `tornado.options` is primarily a command-line library.
  300. Config file support is provided for applications that wish
  301. to use it, but applications that prefer config files may
  302. wish to look at other libraries instead.
  303. .. versionchanged:: 4.1
  304. Config files are now always interpreted as utf-8 instead of
  305. the system default encoding.
  306. .. versionchanged:: 4.4
  307. The special variable ``__file__`` is available inside config
  308. files, specifying the absolute path to the config file itself.
  309. .. versionchanged:: 5.1
  310. Added the ability to set options via strings in config files.
  311. """
  312. config = {"__file__": os.path.abspath(path)}
  313. with open(path, "rb") as f:
  314. exec_in(native_str(f.read()), config, config)
  315. for name in config:
  316. normalized = self._normalize_name(name)
  317. if normalized in self._options:
  318. option = self._options[normalized]
  319. if option.multiple:
  320. if not isinstance(config[name], (list, str)):
  321. raise Error(
  322. "Option %r is required to be a list of %s "
  323. "or a comma-separated string"
  324. % (option.name, option.type.__name__)
  325. )
  326. if type(config[name]) == str and option.type != str:
  327. option.parse(config[name])
  328. else:
  329. option.set(config[name])
  330. if final:
  331. self.run_parse_callbacks()
  332. def print_help(self, file: TextIO = None) -> None:
  333. """Prints all the command line options to stderr (or another file)."""
  334. if file is None:
  335. file = sys.stderr
  336. print("Usage: %s [OPTIONS]" % sys.argv[0], file=file)
  337. print("\nOptions:\n", file=file)
  338. by_group = {} # type: Dict[str, List[_Option]]
  339. for option in self._options.values():
  340. by_group.setdefault(option.group_name, []).append(option)
  341. for filename, o in sorted(by_group.items()):
  342. if filename:
  343. print("\n%s options:\n" % os.path.normpath(filename), file=file)
  344. o.sort(key=lambda option: option.name)
  345. for option in o:
  346. # Always print names with dashes in a CLI context.
  347. prefix = self._normalize_name(option.name)
  348. if option.metavar:
  349. prefix += "=" + option.metavar
  350. description = option.help or ""
  351. if option.default is not None and option.default != "":
  352. description += " (default %s)" % option.default
  353. lines = textwrap.wrap(description, 79 - 35)
  354. if len(prefix) > 30 or len(lines) == 0:
  355. lines.insert(0, "")
  356. print(" --%-30s %s" % (prefix, lines[0]), file=file)
  357. for line in lines[1:]:
  358. print("%-34s %s" % (" ", line), file=file)
  359. print(file=file)
  360. def _help_callback(self, value: bool) -> None:
  361. if value:
  362. self.print_help()
  363. sys.exit(0)
  364. def add_parse_callback(self, callback: Callable[[], None]) -> None:
  365. """Adds a parse callback, to be invoked when option parsing is done."""
  366. self._parse_callbacks.append(callback)
  367. def run_parse_callbacks(self) -> None:
  368. for callback in self._parse_callbacks:
  369. callback()
  370. def mockable(self) -> "_Mockable":
  371. """Returns a wrapper around self that is compatible with
  372. `mock.patch <unittest.mock.patch>`.
  373. The `mock.patch <unittest.mock.patch>` function (included in
  374. the standard library `unittest.mock` package since Python 3.3,
  375. or in the third-party ``mock`` package for older versions of
  376. Python) is incompatible with objects like ``options`` that
  377. override ``__getattr__`` and ``__setattr__``. This function
  378. returns an object that can be used with `mock.patch.object
  379. <unittest.mock.patch.object>` to modify option values::
  380. with mock.patch.object(options.mockable(), 'name', value):
  381. assert options.name == value
  382. """
  383. return _Mockable(self)
  384. class _Mockable(object):
  385. """`mock.patch` compatible wrapper for `OptionParser`.
  386. As of ``mock`` version 1.0.1, when an object uses ``__getattr__``
  387. hooks instead of ``__dict__``, ``patch.__exit__`` tries to delete
  388. the attribute it set instead of setting a new one (assuming that
  389. the object does not catpure ``__setattr__``, so the patch
  390. created a new attribute in ``__dict__``).
  391. _Mockable's getattr and setattr pass through to the underlying
  392. OptionParser, and delattr undoes the effect of a previous setattr.
  393. """
  394. def __init__(self, options: OptionParser) -> None:
  395. # Modify __dict__ directly to bypass __setattr__
  396. self.__dict__["_options"] = options
  397. self.__dict__["_originals"] = {}
  398. def __getattr__(self, name: str) -> Any:
  399. return getattr(self._options, name)
  400. def __setattr__(self, name: str, value: Any) -> None:
  401. assert name not in self._originals, "don't reuse mockable objects"
  402. self._originals[name] = getattr(self._options, name)
  403. setattr(self._options, name, value)
  404. def __delattr__(self, name: str) -> None:
  405. setattr(self._options, name, self._originals.pop(name))
  406. class _Option(object):
  407. # This class could almost be made generic, but the way the types
  408. # interact with the multiple argument makes this tricky. (default
  409. # and the callback use List[T], but type is still Type[T]).
  410. UNSET = object()
  411. def __init__(
  412. self,
  413. name: str,
  414. default: Any = None,
  415. type: type = None,
  416. help: str = None,
  417. metavar: str = None,
  418. multiple: bool = False,
  419. file_name: str = None,
  420. group_name: str = None,
  421. callback: Callable[[Any], None] = None,
  422. ) -> None:
  423. if default is None and multiple:
  424. default = []
  425. self.name = name
  426. if type is None:
  427. raise ValueError("type must not be None")
  428. self.type = type
  429. self.help = help
  430. self.metavar = metavar
  431. self.multiple = multiple
  432. self.file_name = file_name
  433. self.group_name = group_name
  434. self.callback = callback
  435. self.default = default
  436. self._value = _Option.UNSET # type: Any
  437. def value(self) -> Any:
  438. return self.default if self._value is _Option.UNSET else self._value
  439. def parse(self, value: str) -> Any:
  440. _parse = {
  441. datetime.datetime: self._parse_datetime,
  442. datetime.timedelta: self._parse_timedelta,
  443. bool: self._parse_bool,
  444. basestring_type: self._parse_string,
  445. }.get(
  446. self.type, self.type
  447. ) # type: Callable[[str], Any]
  448. if self.multiple:
  449. self._value = []
  450. for part in value.split(","):
  451. if issubclass(self.type, numbers.Integral):
  452. # allow ranges of the form X:Y (inclusive at both ends)
  453. lo_str, _, hi_str = part.partition(":")
  454. lo = _parse(lo_str)
  455. hi = _parse(hi_str) if hi_str else lo
  456. self._value.extend(range(lo, hi + 1))
  457. else:
  458. self._value.append(_parse(part))
  459. else:
  460. self._value = _parse(value)
  461. if self.callback is not None:
  462. self.callback(self._value)
  463. return self.value()
  464. def set(self, value: Any) -> None:
  465. if self.multiple:
  466. if not isinstance(value, list):
  467. raise Error(
  468. "Option %r is required to be a list of %s"
  469. % (self.name, self.type.__name__)
  470. )
  471. for item in value:
  472. if item is not None and not isinstance(item, self.type):
  473. raise Error(
  474. "Option %r is required to be a list of %s"
  475. % (self.name, self.type.__name__)
  476. )
  477. else:
  478. if value is not None and not isinstance(value, self.type):
  479. raise Error(
  480. "Option %r is required to be a %s (%s given)"
  481. % (self.name, self.type.__name__, type(value))
  482. )
  483. self._value = value
  484. if self.callback is not None:
  485. self.callback(self._value)
  486. # Supported date/time formats in our options
  487. _DATETIME_FORMATS = [
  488. "%a %b %d %H:%M:%S %Y",
  489. "%Y-%m-%d %H:%M:%S",
  490. "%Y-%m-%d %H:%M",
  491. "%Y-%m-%dT%H:%M",
  492. "%Y%m%d %H:%M:%S",
  493. "%Y%m%d %H:%M",
  494. "%Y-%m-%d",
  495. "%Y%m%d",
  496. "%H:%M:%S",
  497. "%H:%M",
  498. ]
  499. def _parse_datetime(self, value: str) -> datetime.datetime:
  500. for format in self._DATETIME_FORMATS:
  501. try:
  502. return datetime.datetime.strptime(value, format)
  503. except ValueError:
  504. pass
  505. raise Error("Unrecognized date/time format: %r" % value)
  506. _TIMEDELTA_ABBREV_DICT = {
  507. "h": "hours",
  508. "m": "minutes",
  509. "min": "minutes",
  510. "s": "seconds",
  511. "sec": "seconds",
  512. "ms": "milliseconds",
  513. "us": "microseconds",
  514. "d": "days",
  515. "w": "weeks",
  516. }
  517. _FLOAT_PATTERN = r"[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?"
  518. _TIMEDELTA_PATTERN = re.compile(
  519. r"\s*(%s)\s*(\w*)\s*" % _FLOAT_PATTERN, re.IGNORECASE
  520. )
  521. def _parse_timedelta(self, value: str) -> datetime.timedelta:
  522. try:
  523. sum = datetime.timedelta()
  524. start = 0
  525. while start < len(value):
  526. m = self._TIMEDELTA_PATTERN.match(value, start)
  527. if not m:
  528. raise Exception()
  529. num = float(m.group(1))
  530. units = m.group(2) or "seconds"
  531. units = self._TIMEDELTA_ABBREV_DICT.get(units, units)
  532. sum += datetime.timedelta(**{units: num})
  533. start = m.end()
  534. return sum
  535. except Exception:
  536. raise
  537. def _parse_bool(self, value: str) -> bool:
  538. return value.lower() not in ("false", "0", "f")
  539. def _parse_string(self, value: str) -> str:
  540. return _unicode(value)
  541. options = OptionParser()
  542. """Global options object.
  543. All defined options are available as attributes on this object.
  544. """
  545. def define(
  546. name: str,
  547. default: Any = None,
  548. type: type = None,
  549. help: str = None,
  550. metavar: str = None,
  551. multiple: bool = False,
  552. group: str = None,
  553. callback: Callable[[Any], None] = None,
  554. ) -> None:
  555. """Defines an option in the global namespace.
  556. See `OptionParser.define`.
  557. """
  558. return options.define(
  559. name,
  560. default=default,
  561. type=type,
  562. help=help,
  563. metavar=metavar,
  564. multiple=multiple,
  565. group=group,
  566. callback=callback,
  567. )
  568. def parse_command_line(args: List[str] = None, final: bool = True) -> List[str]:
  569. """Parses global options from the command line.
  570. See `OptionParser.parse_command_line`.
  571. """
  572. return options.parse_command_line(args, final=final)
  573. def parse_config_file(path: str, final: bool = True) -> None:
  574. """Parses global options from a config file.
  575. See `OptionParser.parse_config_file`.
  576. """
  577. return options.parse_config_file(path, final=final)
  578. def print_help(file: TextIO = None) -> None:
  579. """Prints all the command line options to stderr (or another file).
  580. See `OptionParser.print_help`.
  581. """
  582. return options.print_help(file)
  583. def add_parse_callback(callback: Callable[[], None]) -> None:
  584. """Adds a parse callback, to be invoked when option parsing is done.
  585. See `OptionParser.add_parse_callback`
  586. """
  587. options.add_parse_callback(callback)
  588. # Default options
  589. define_logging_options(options)