+ There is no restriction about the order, a keyword argument can be
+ followed by a positional argument and vice-versa. All type of arguments
+ are grouped in the list/dict returned. The order of the positional
+ arguments is preserved and if there are multiple keyword arguments with
+ the same key, the last value is the winner (all other values are lost).
+
+ Examples:
+
+ >>> parse_command('hello world')
+ ([u'hello', u'world'], {})
+ >>> parse_command('hello planet=earth')
+ ([u'hello'], {'planet': u'earth'})
+ >>> parse_command('hello planet="third rock from the sun"')
+ ([u'hello'], {'planet': u'third rock from the sun'})
+ >>> parse_command(u' planet="third rock from the sun" hello ')
+ ([u'hello'], {'planet': u'third rock from the sun'})
+ >>> parse_command(u' planet="third rock from the sun" "hi, hello"'
+ '"how are you" ')
+ ([u'hi, hello', u'how are you'], {'planet': u'third rock from the sun'})
+ >>> parse_command(u'one two three "fourth number"=four')
+ ([u'one', u'two', u'three'], {'fourth number': u'four'})
+ >>> parse_command(u'one two three "fourth number=four"')
+ ([u'one', u'two', u'three', u'fourth number=four'], {})
+ >>> parse_command(u'one two three fourth\=four')
+ ([u'one', u'two', u'three', u'fourth=four'], {})
+ >>> parse_command(u'one two three fourth=four=five')
+ ([u'one', u'two', u'three'], {'fourth': u'four=five'})
+ >>> parse_command(ur'nice\nlong\n\ttext')
+ ([u'nice\nlong\n\ttext'], {})
+ >>> parse_command('=hello')
+ ([u'=hello'], {})
+ >>> parse_command(r'\thello')
+ ([u'\thello'], {})
+ >>> parse_command(r'\N')
+ ([None], {})
+ >>> parse_command(r'none=\N')
+ ([], {'none': None})
+ >>> parse_command(r'\N=none')
+ ([], {'\\N': 'none'})
+ >>> parse_command(r'Not\N')
+ ([u'Not\\N'], {})
+ >>> parse_command(r'\None')
+ ([u'\\None'], {})
+
+ This examples are syntax errors:
+ Missing quote: "hello world
+ Missing value: hello=
+ """
+ SEP, TOKEN, DQUOTE, SQUOTE, EQUAL = u' ', None, u'"', u"'", u'=' # states
+ separators = (u' ', u'\t', u'\v', u'\n') # token separators
+ escaped_chars = (u'a', u'n', u'r', u'b', u'v', u't') # escaped sequences
+ seq = []
+ dic = {}
+ buff = u''
+ escape = False
+ keyword = None
+ state = SEP
+ for n, c in enumerate(command):
+ # Escaped character
+ if escape:
+ for e in escaped_chars:
+ if c == e:
+ buff += eval(u'"\\' + e + u'"')
+ break
+ else:
+ if c == 'N':
+ buff += r'\N'
+ else:
+ buff += c
+ escape = False
+ continue
+ # Escaped sequence start
+ if c == u'\\':
+ escape = True
+ continue
+ # Looking for spaces
+ if state == SEP:
+ if c in separators:
+ continue
+ if buff and n != 2: # Not the first item (even if was a escape seq)
+ if c == EQUAL: # Keyword found
+ keyword = buff
+ buff = u''
+ continue
+ if buff == r'\N':
+ buff = None
+ if keyword is not None: # Value found
+ dic[str(keyword)] = buff
+ keyword = None
+ else: # Normal parameter found
+ seq.append(buff)
+ buff = u''
+ state = TOKEN
+ # Getting a token
+ if state == TOKEN:
+ if c == DQUOTE:
+ state = DQUOTE
+ continue
+ if c == SQUOTE:
+ state = SQUOTE
+ continue
+ # Check if a keyword is added
+ if c == EQUAL and keyword is None and buff:
+ keyword = buff
+ buff = u''
+ state = SEP
+ continue
+ if c in separators:
+ state = SEP
+ continue
+ buff += c
+ continue
+ # Inside a double quote
+ if state == DQUOTE:
+ if c == DQUOTE:
+ state = TOKEN
+ continue
+ buff += c
+ continue
+ # Inside a single quote
+ if state == SQUOTE:
+ if c == SQUOTE:
+ state = TOKEN
+ continue
+ buff += c
+ continue
+ assert 0, u'Unexpected state'
+ if state == DQUOTE or state == SQUOTE:
+ raise ParseError(command, u'missing closing quote (%s)' % state)
+ if not buff and keyword is not None:
+ raise ParseError(command,
+ u'keyword argument (%s) without value' % keyword)
+ if buff:
+ if buff == r'\N':
+ buff = None
+ if keyword is not None:
+ dic[str(keyword)] = buff
+ else:
+ seq.append(buff)
+ return (seq, dic)
+
+class Dispatcher:
+ r"""Dispatcher([routes]) -> Dispatcher instance :: Command dispatcher
+
+ This class provides a modular and extensible dispatching mechanism. You
+ can specify root 'routes' (as a dict where the key is the string of the
+ root command and the value is a callable object to handle that command,
+ or a subcommand if the callable is an instance and the command can be
+ sub-routed).
+
+ The command can have arguments, separated by (any number of) spaces.
+
+ The dispatcher tries to route the command as deeply as it can, passing
+ the other "path" components as arguments to the callable. To route the
+ command it inspects the callable attributes to find a suitable callable
+ attribute to handle the command in a more specific way, and so on.
+
+ Example:
+ >>> d = Dispatcher(dict(handler=some_handler))
+ >>> d.dispatch('handler attribute method arg1 arg2 "third argument"')
+
+ If 'some_handler' is an object with an 'attribute' that is another
+ object which has a method named 'method', then
+ some_handler.attribute.method('arg1', 'arg2') will be called. If
+ some_handler is a function, then some_handler('attribute', 'method',
+ 'arg1', 'arg2') will be called. The handler "tree" can be as complex
+ and deep as you want.
+
+ If some command can't be dispatched (because there is no root handler or
+ there is no matching callable attribute), a CommandNotFoundError is raised.
+ """
+
+ def __init__(self, routes=dict()):
+ r"""Initialize the Dispatcher object.
+
+ See Dispatcher class documentation for more info.
+ """
+ self.routes = routes
+
+ def dispatch(self, route):
+ r"""dispatch(route) -> None :: Dispatch a command string.
+
+ This method searches for a suitable callable object in the routes
+ "tree" and call it, or raises a CommandNotFoundError if the command
+ can't be dispatched.
+ """
+ command = list()
+ (route, kwargs) = parse_command(route)
+ if not route:
+ raise CommandNotFoundError(command)
+ command.append(route[0])
+ handler = self.routes.get(route[0], None)
+ if handler is None:
+ raise CommandNotFoundError(command)
+ route = route[1:]
+ while not is_handler(handler):
+ if len(route) is 0:
+ raise CommandNotFoundError(command)
+ command.append(route[0])
+ if not hasattr(handler, route[0]):
+ raise CommandNotFoundError(command)
+ handler = getattr(handler, route[0])
+ route = route[1:]
+ return handler(*route, **kwargs)