-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathcommand.py
45 lines (35 loc) · 1.21 KB
/
command.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
from __future__ import absolute_import, division, print_function, unicode_literals
import os, sys
import shlex
class Command:
"""Parse a text command into command name and arguments, both positional and keyword"""
def __init__(self, string):
self.name = None
self.string = None
self.body = None
self.args = []
self.kwargs = {}
self.chunks = [] # Raw splitted chunks
self.parse(string)
def name(self):
return self.name
def get(self, key, value=None):
return self.kwargs.get(key, value)
def has_key(self, key):
return key in self.kwargs
def __contains__(self, key):
return key in self.kwargs
def parse(self, string):
self.string = string
self.body = string
self.chunks = shlex.split(string)
for i,chunk in enumerate(self.chunks):
if '=' not in chunk:
if i == 0:
self.name = chunk
self.body = self.string.strip()[len(chunk):].strip()
else:
self.args.append(chunk)
else:
pos = chunk.find('=')
self.kwargs[chunk[:pos]] = chunk[pos+1:]