def CheckedEval(file_contents):
"""Return the eval of a gyp file.
The gyp file is restricted to dictionaries and lists only, and
repeated keys are not allowed.
Note that this is slower than eval() is.
"""
ast = compiler.parse(file_contents)
assert isinstance(ast, Module)
c1 = ast.getChildren()
assert c1[0] is None
assert isinstance(c1[1], Stmt)
c2 = c1[1].getChildren()
assert isinstance(c2[0], Discard)
c3 = c2[0].getChildren()
assert len(c3) == 1
return CheckNode(c3[0], [])
python类parse()的实例源码
def run(s, frame=None):
if frame is None:
frame = sys._getframe(1)
frame = py.code.Frame(frame)
module = Interpretable(parse(s, 'exec').node)
try:
module.run(frame)
except Failure:
e = sys.exc_info()[1]
report_failure(e)
def _get_tree(self):
tree = parse(self.source, self.mode)
misc.set_filename(self.filename, tree)
syntax.check(tree)
return tree
def getObj(s):
global compiler
if compiler is None:
import compiler
s = "a=" + s
p = compiler.parse(s)
return p.getChildren()[1].getChildren()[0].getChildren()[1]
def get_args(val):
d = {}
args = ast.parse("d(" + val + ")", mode='eval').body.args
i = 1
for arg in args:
if isinstance(arg, ast.Name):
d[str(i)] = literal_eval(arg.id)
else:
d[str(i)] = literal_eval(arg)
i += 1
return d
def get_kwargs(val):
d = {}
args = ast.parse("d(" + val + ")", mode='eval').body.keywords
for arg in args:
d[arg.arg] = literal_eval(arg.value)
return d
def parse_to_list(val):
values = ast.parse("[" + val + "]", mode='eval').body.elts
return [literal_eval(v) for v in values]
def literal_eval(node_or_string):
"""
Safely evaluate an expression node or a string containing a Python
expression. The string or node provided may only consist of the
following Python literal structures: strings, numbers, tuples,
lists, dicts, booleans, and None.
"""
_safe_names = {'None': None, 'True': True, 'False': False}
if isinstance(node_or_string, basestring):
node_or_string = compiler.parse(node_or_string, mode='eval')
if isinstance(node_or_string, Expression):
node_or_string = node_or_string.node
def _convert(node):
if isinstance(node, Const) and isinstance(node.value,
(basestring, int, float, long, complex)):
return node.value
elif isinstance(node, Tuple):
return tuple(map(_convert, node.nodes))
elif isinstance(node, compiler.ast.List):
return list(map(_convert, node.nodes))
elif isinstance(node, Dict):
return dict((_convert(k), _convert(v)) for k, v
in node.items)
elif isinstance(node, Name):
if node.name in _safe_names:
return _safe_names[node.name]
elif isinstance(node, UnarySub):
return -_convert(node.expr)
raise ValueError('malformed string')
return _convert(node_or_string)
def get_args(val):
d = {}
args = compiler.parse("d(" + val + ")", mode='eval').node.args
i = 1
for arg in args:
if isinstance(arg, Keyword):
break
d[str(i)] = literal_eval(arg)
i = i + 1
return d
def parse_to_list(val):
values = compiler.parse("[" + val + "]", mode='eval').node.asList()
return [literal_eval(v) for v in values]
def translate(skipsubs=False):
"""Parse the Title.attributes and Title.level from the reader. The
real work has already been done by parse()."""
assert Lex.next() in (Title,FloatingTitle)
# Discard title from reader.
for i in range(Title.linecount):
reader.read()
Title.setsectname()
if not skipsubs:
Title.attributes['title'] = Title.dosubs(Title.attributes['title'])
def isnext():
lines = reader.read_ahead(2)
return Title.parse(lines)
def parse_csv(self,rows):
"""Parse the list of source table rows. Each row item in the returned
list contains a list of cell data elements."""
import StringIO
import csv
result = []
rdr = csv.reader(StringIO.StringIO('\r\n'.join(rows)),
skipinitialspace=True)
try:
for row in rdr:
result.append(row)
except Exception:
raise EAsciiDoc,'csv parse error: %s' % row
return result
def literal_eval(node_or_string):
"""
Safely evaluate an expression node or a string containing a Python
expression. The string or node provided may only consist of the following
Python literal structures: strings, numbers, tuples, lists, dicts, booleans,
and None.
"""
_safe_names = {'None': None, 'True': True, 'False': False}
if isinstance(node_or_string, string_types):
node_or_string = parse(node_or_string, mode='eval')
if isinstance(node_or_string, ast.Expression):
node_or_string = node_or_string.node
def _convert(node):
# Okay to use long here because this is only for python 2.4 and 2.5
if isinstance(node, ast.Const) and isinstance(node.value, (text_type, binary_type, int, float, long, complex)):
return node.value
elif isinstance(node, ast.Tuple):
return tuple(map(_convert, node.nodes))
elif isinstance(node, ast.List):
return list(map(_convert, node.nodes))
elif isinstance(node, ast.Dict):
return dict((_convert(k), _convert(v)) for k, v in node.items())
elif isinstance(node, ast.Name):
if node.name in _safe_names:
return _safe_names[node.name]
elif isinstance(node, ast.UnarySub):
return -_convert(node.expr)
raise ValueError('malformed string')
return _convert(node_or_string)
def decode(self, str):
return str # It will not do to feed Unicode to *compiler.parse*.
def getObj(s):
global compiler
if compiler is None:
import compiler
s = "a=" + s
p = compiler.parse(s)
return p.getChildren()[1].getChildren()[0].getChildren()[1]
def main(files):
mf = MethodFinder()
for file in files:
f = open(file)
buf = f.read()
f.close()
ast = compiler.parse(buf)
compiler.walk(ast, mf)
def _get_tree(self):
tree = parse(self.source, self.mode)
misc.set_filename(self.filename, tree)
syntax.check(tree)
return tree
def main(files):
mf = MethodFinder()
for file in files:
f = open(file)
buf = f.read()
f.close()
ast = compiler.parse(buf)
compiler.walk(ast, mf)
def _get_tree(self):
tree = parse(self.source, self.mode)
misc.set_filename(self.filename, tree)
syntax.check(tree)
return tree