简体   繁体   中英

Validate expression/infix in python

How do I validate an expression/infix in python? Is it possible? For example:

a-d*9
5-(a*0.3-d+(0.4-e))/k*5
(a-d*9)/(k-y-4.3*e)+(t-7*c)

If you want Python-style expressions, you can use the parser in the ast module and check for SyntaxError :

>>> ast.parse('5-(a*0.3-d+(0.4-e))/k*5')
<_ast.Module object at 0x7fc7bdd9e790>
>>> ast.parse('5-(a*0.3-d+(0.4-e))/k*')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.6/ast.py", line 37, in parse
    return compile(expr, filename, mode, PyCF_ONLY_AST)
  File "<unknown>", line 1
    5-(a*0.3-d+(0.4-e))/k*
                        ^
SyntaxError: unexpected EOF while parsing

Though that might parse much more than you actually need:

>>> ast.parse('def spam(): return "ham"')
<_ast.Module object at 0x7fc7bdd9e790>

so you might want to inspect the returned parse tree carefully.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM