Python 中的安全表达式解析器 [英] Safe expression parser in Python

查看:43
本文介绍了Python 中的安全表达式解析器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何让用户以安全的方式执行数学表达式?我需要写一个完整的解析器吗?

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?

推荐答案

Pyparsing 示例页面列出了几个表达式解析器:

The Pyparsing examples page lists several expression parsers:

http://pyparsing.wikispaces.com/file/view/fourFn.py - 使用 pyparsing 的传统算术中缀符号解析器/评估器实现(尽管它的名字,它实际上执行 5 函数算术,加上几个触发函数)

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 中的安全表达式解析器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆