问题描述
如何允许用户以安全的方式执行数学表达式?我需要编写一个完整的解析器吗?
How can I allow users to execute mathematical expressions in a safe way?Do I need to write a full parser?
是否有类似 ast.literal_eval()之类的东西,但对于表情?
Is there something like ast.literal_eval(), but for expressions?
推荐答案
剖析示例"页面列出了几个表达式解析器:
The Pyparsing examples page lists several expression parsers:
http://pyparsing.wikispaces.com/file/view/fourFn.py -使用pyparsing的常规算术中缀表示法解析器/求值器实现(尽管它的名称是5函数算术,再加上一些trig函数)
http://pyparsing.wikispaces.com/file/view/fourFn.py - A conventional arithmetic infix notation parser/evaluator implementation using pyparsing (despite its name, this actually does 5-function arithmetic, plus several trig functions)
http://pyparsing.wikispaces.com/file/view/simpleBool.py -使用pyparsing辅助方法operatorPrecedence
的布尔值中缀表示法解析器/评估器,它简化了中缀运算符表示法的定义
http://pyparsing.wikispaces.com/file/view/simpleBool.py - A boolean infix notation parser/evaluator, using a pyparsing helper method operatorPrecedence
, which simplifies the definition of infix operator notations
http://pyparsing.wikispaces.com/file/view/simpleArith.py http://pyparsing.wikispaces.com/file/view/eval_arith.py -一对使用operatorPrecedence
重铸fourFn.py的示例.第一个仅解析并返回一个解析树,第二个添加评估逻辑.
http://pyparsing.wikispaces.com/file/view/simpleArith.py http://pyparsing.wikispaces.com/file/view/eval_arith.py -A pair of examples recasting fourFn.py using operatorPrecedence
. The first just parses and returns a parse tree, the second adds evaluation logic.
这篇关于Python中的安全表达式解析器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!