options.py 25 KB

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