pass
-class _Options(dict):
+class OptionParser(dict):
"""A collection of options, a dictionary with object-like access.
Normally accessed via static functions in the `tornado.options` module,
which reference a global instance.
"""
def __init__(self):
- super(_Options, self).__init__()
+ super(OptionParser, self).__init__()
self.__dict__['_parse_callbacks'] = []
self.define("help", type=bool, help="show this help information",
callback=self._help_callback)
name, equals, value = arg.partition("=")
name = name.replace('-', '_')
if not name in self:
- print_help()
+ self.print_help()
raise Error('Unrecognized command line option: %r' % name)
option = self[name]
if not equals:
return _unicode(value)
-options = _Options()
+options = OptionParser()
"""Global options dictionary.
Supports both attribute-style and dict-style access.
return options.parse_config_file(path, final=final)
-def print_help(file=sys.stdout):
+def print_help(file=None):
"""Prints all the command line options to stdout."""
return options.print_help(file)
import sys
-from tornado.options import _Options
+from tornado.options import OptionParser, Error
from tornado.test.util import unittest
try:
class OptionsTest(unittest.TestCase):
def test_parse_command_line(self):
- options = _Options()
+ options = OptionParser()
options.define("port", default=80)
options.parse_command_line(["main.py", "--port=443"])
self.assertEqual(options.port, 443)
def test_parse_callbacks(self):
- options = _Options()
+ options = OptionParser()
self.called = False
def callback():
self.called = True
self.assertTrue(self.called)
def test_help(self):
- options = _Options()
+ options = OptionParser()
try:
orig_stderr = sys.stderr
sys.stderr = StringIO()
finally:
sys.stderr = orig_stderr
self.assertIn("Usage:", usage)
+
+ def test_subcommand(self):
+ base_options = OptionParser()
+ base_options.define("verbose", default=False)
+ sub_options = OptionParser()
+ sub_options.define("foo", type=str)
+ rest = base_options.parse_command_line(
+ ["main.py", "--verbose", "subcommand", "--foo=bar"])
+ self.assertEqual(rest, ["subcommand", "--foo=bar"])
+ self.assertTrue(base_options.verbose)
+ rest2 = sub_options.parse_command_line(rest)
+ self.assertEqual(rest2, [])
+ self.assertEqual(sub_options.foo, "bar")
+
+ # the two option sets are distinct
+ try:
+ orig_stderr = sys.stderr
+ sys.stderr = StringIO()
+ with self.assertRaises(Error):
+ sub_options.parse_command_line(["subcommand", "--verbose"])
+ finally:
+ sys.stderr = orig_stderr