eval只支持解析Python的表达式语法,并且存在注入式攻击漏洞。如果想要快速构建任意表达式语法的解释器,推荐使用pyparsing库。下面摘自它的GitHub Wiki:
Combined with a fear/dismay at using regular expressions, I wanted an object-assembly model for building up parsers. Since then, tools of this style have come to be called PEG's, orParsing Expression Grammars. I also related to Python's operator overloading features, and so pyparsing has become an embedded DSL within Python, making heavy use of operators for grammar construction and call syntax for grammar element naming.
翻译过来就是:「由于使用正则表达式让我恐惧/沮丧,我希望能有一个用于构建解释器的面向对象的框架。从那时起,这种类型的工具逐渐被称做PEG(Parsing Expression Grammars,即解析表达式语法)。PyParasing已经成为嵌入在Python语法中的领域专用语言,并且引入了Python的运算符重载特性。通过它,你可以方便地使用运算符进行语法构造,并可以为可调用的语法产生式符号进行命名。」可以参考一下我的这篇文章: