def onecmd(self, line):
""" This executes the actual do_* method for a command.
If the command provided doesn't exist, then it executes _default() instead.
:param line: ParsedString - subclass of string including the pyparsing ParseResults
:return: bool - a flag indicating whether the interpretation of commands should stop
"""
statement = self.parser_manager.parsed(line)
funcname = self._func_named(statement.parsed.command)
if not funcname:
return self.default(statement)
try:
func = getattr(self, funcname)
except AttributeError:
return self.default(statement)
stop = func(statement)
return stop
python类ParseResults()的实例源码
def _addSimpleData(self, data_list, data):
if isinstance(data[0], ParseResults):
inferred_dimen = len(data[0])
else:
inferred_dimen = 1
if self.dimen == None:
# infer dimension from records
self.dimen = inferred_dimen
if self.current_slice == None:
self._setSlice(tuple(['*'] * self.dimen))
if len(self.free_indices) == inferred_dimen:
for d in data.asList():
self._addValue(data_list, d)
elif len(self.free_indices) > 1 and inferred_dimen:
for c in chunk(data, len(self.free_indices)):
self._addValue(data_list, c)
else:
raise AmplyError("Dimension of elements (%d) does not match "
"declared dimension, (%d)" %
(inferred_dimen, self.dimen))
def make_span(s, l, t):
def compute_hi(init_loc, tokens):
hi = init_loc
for tok in tokens:
if isinstance(tok, ASTNode):
hi = max(hi, tok.span.hi)
elif isinstance(tok, basestring):
hi += len(tok)
elif isinstance(tok, p.ParseResults):
hi = max(hi, compute_hi(init_loc, tok))
else:
raise exception.BananaGrammarBug(
"Couldn't create span for: {}".format(tok)
)
return hi
if len(t) > 0:
span_hi = compute_hi(l, t)
return Span(s, l, span_hi)
else:
return Span(s, l, 2)
def __init__(self, span, expr_tree):
"""
Construct an expression
:type span: Span
:param span: Span for the expression.
:type expr_tree: p.ParseResults
;:param expr_tree: The tree generated by pyparsing.infixNotation
"""
super(Expr, self).__init__(span)
# We don't use this tree at this point.
# During typecheck we will make sure
# that the expression can evaluate
# Finally during evaluation, we will evaluate
# the final result.
if isinstance(expr_tree, p.ParseResults):
expr_tree = expr_tree.asList()
if isinstance(expr_tree, list):
for i in range(0, len(expr_tree)):
if isinstance(expr_tree[i], list):
expr_tree[i] = Expr(span, expr_tree[i])
self.expr_tree = expr_tree
else:
self.expr_tree = [expr_tree]
def paren_pop(self, parsed_tokens):
'''
Args:
parsed_tokens: a ParseResult object
Returns:
content: a list of string sentences
'''
# must convert the ParseResult to a list, otherwise adding it to a list
# causes weird results.
if isinstance(parsed_tokens, pypar.ParseResults):
parsed_tokens = parsed_tokens.asList()
content = self.paren_pop_helper(parsed_tokens)
return content
def paren_pop(self, parsed_tokens):
'''
Args:
parsed_tokens: a ParseResult object
Returns:
content: a list of string sentences
'''
# must convert the ParseResult to a list, otherwise adding it to a list
# causes weird results.
if isinstance(parsed_tokens, pypar.ParseResults):
parsed_tokens = parsed_tokens.asList()
content = self.paren_pop_helper(parsed_tokens)
return content
def simplify(expr):
if isinstance(expr, ParseResults) and len(expr) == 1:
return simplify(expr[0])
if isinstance(expr, (list, ParseResults)):
return map(simplify, expr)
if not isinstance(expr, CompValue):
return expr
if expr.name.endswith('Expression'):
if expr.other is None:
return simplify(expr.expr)
for k in expr.keys():
expr[k] = simplify(expr[k])
# expr['expr']=simplify(expr.expr)
# expr['other']=simplify(expr.other)
return expr
def _traverseAgg(e, visitor=lambda n, v: None):
"""
Traverse a parse-tree, visit each node
if visit functions return a value, replace current node
"""
res = []
if isinstance(e, (list, ParseResults, tuple)):
res = [_traverseAgg(x, visitor) for x in e]
elif isinstance(e, CompValue):
for k, val in e.iteritems():
if val != None:
res.append(_traverseAgg(val, visitor))
return visitor(e, res)
def simplify(expr):
if isinstance(expr, ParseResults) and len(expr) == 1:
return simplify(expr[0])
if isinstance(expr, (list, ParseResults)):
return map(simplify, expr)
if not isinstance(expr, CompValue):
return expr
if expr.name.endswith('Expression'):
if expr.other is None:
return simplify(expr.expr)
for k in expr.keys():
expr[k] = simplify(expr[k])
# expr['expr']=simplify(expr.expr)
# expr['other']=simplify(expr.other)
return expr
def _traverseAgg(e, visitor=lambda n, v: None):
"""
Traverse a parse-tree, visit each node
if visit functions return a value, replace current node
"""
res = []
if isinstance(e, (list, ParseResults, tuple)):
res = [_traverseAgg(x, visitor) for x in e]
elif isinstance(e, CompValue):
for k, val in e.iteritems():
if val != None:
res.append(_traverseAgg(val, visitor))
return visitor(e, res)
def u(x, ip=None):
if type(x) is pyparsing.ParseResults:
return x.asList()[0]
if isinstance(x, Symbolic):
return x.value(ip)
return x
def _coerce_parse_result(results):
if isinstance(results, ParseResults):
return [_coerce_parse_result(i) for i in results]
else:
return results
def precmd(self, statement):
"""Hook method executed just before the command is processed by ``onecmd()`` and after adding it to the history.
:param statement: ParsedString - subclass of str which also contains pyparsing ParseResults instance
:return: ParsedString - a potentially modified version of the input ParsedString statement
"""
return statement
# ----- Methods which are cmd2-specific lifecycle hooks which are not present in cmd -----
# noinspection PyMethodMayBeStatic
def postparse(self, parse_result):
"""Hook that runs immediately after parsing the command-line but before ``parsed()`` returns a ParsedString.
:param parse_result: pyparsing.ParseResults - parsing results output by the pyparsing parser
:return: pyparsing.ParseResults - potentially modified ParseResults object
"""
return parse_result
# noinspection PyMethodMayBeStatic
def _restore_output(self, statement):
"""Handles restoring state after output redirection as well as the actual pipe operation if present.
:param statement: ParsedString - subclass of str which also contains pyparsing ParseResults instance
"""
# If we have redirected output to a file or the clipboard or piped it to a shell command, then restore state
if self.kept_state is not None:
# If we redirected output to the clipboard
if statement.parsed.output and not statement.parsed.outputTo:
self.stdout.seek(0)
write_to_paste_buffer(self.stdout.read())
try:
# Close the file or pipe that stdout was redirected to
self.stdout.close()
except BROKEN_PIPE_ERROR:
pass
finally:
# Restore self.stdout
self.kept_state.restore()
self.kept_state = None
# If we were piping output to a shell command, then close the subprocess the shell command was running in
if self.pipe_proc is not None:
self.pipe_proc.communicate()
self.pipe_proc = None
# Restore sys.stdout if need be
if self.kept_sys is not None:
self.kept_sys.restore()
self.kept_sys = None
def _coerce_parse_result(results):
if isinstance(results, ParseResults):
return [_coerce_parse_result(i) for i in results]
else:
return results
def get_port(node):
if len(node) > 1:
if isinstance(node[1], pyparsing.ParseResults):
if len(node[1][0]) == 2:
if node[1][0][0] == ':':
return node[1][0][1]
return None
def _coerce_parse_result(results):
if isinstance(results, ParseResults):
return [_coerce_parse_result(i) for i in results]
else:
return results
def _coerce_parse_result(results):
if isinstance(results, ParseResults):
return [_coerce_parse_result(i) for i in results]
else:
return results
def _coerce_parse_result(results):
if isinstance(results, ParseResults):
return [_coerce_parse_result(i) for i in results]
else:
return results
def _coerce_parse_result(results):
if isinstance(results, ParseResults):
return [_coerce_parse_result(i) for i in results]
else:
return results
def _coerce_parse_result(results):
if isinstance(results, ParseResults):
return [_coerce_parse_result(i) for i in results]
else:
return results
def _coerce_parse_result(results):
if isinstance(results, ParseResults):
return [_coerce_parse_result(i) for i in results]
else:
return results
def _coerce_parse_result(results):
if isinstance(results, ParseResults):
return [_coerce_parse_result(i) for i in results]
else:
return results
def _parsed_query2dict(cls, parsed_query):
result = None
while parsed_query:
part = parsed_query.pop()
if part in cls.binary_operator:
result = {part: {parsed_query.pop(): result}}
elif part in cls.multiple_operators:
if result.get(part):
result[part].append(
cls._parsed_query2dict(parsed_query.pop()))
else:
result = {part: [result]}
elif part in cls.uninary_operators:
result = {part: result}
elif isinstance(part, pyparsing.ParseResults):
kind = part.getName()
if kind == "list":
res = part.asList()
else:
res = cls._parsed_query2dict(part)
if result is None:
result = res
elif isinstance(result, dict):
list(result.values())[0].append(res)
else:
result = part
return result
def _coerce_parse_result(results):
if isinstance(results, ParseResults):
return [_coerce_parse_result(i) for i in results]
else:
return results
def _coerce_parse_result(results):
if isinstance(results, ParseResults):
return [_coerce_parse_result(i) for i in results]
else:
return results
def _coerce_parse_result(results):
if isinstance(results, ParseResults):
return [_coerce_parse_result(i) for i in results]
else:
return results
def _coerce_parse_result(results):
if isinstance(results, ParseResults):
return [_coerce_parse_result(i) for i in results]
else:
return results
def parent_children(self, *children):
for i in children:
if isinstance(i, languageSyntaxOBbase):
i.set_parent(self)
i.parent_own_children()
elif isinstance(i, (list, tuple, pp.ParseResults)):
self.parent_children(*i)