Safe expression parser in Python

前端 未结 5 1124
小鲜肉
小鲜肉 2020-12-01 16:23

How can I allow users to execute mathematical expressions in a safe way? Do I need to write a full parser?

Is there something like ast.literal_eval(), but for expres

5条回答
  •  粉色の甜心
    2020-12-01 17:00

    Few weeks ago I did similar thing, but for logical expressions (or, and, not, comparisons, parentheses etc.). I did this using Ply parser. I have created simple lexer and parser. Parser generated AST tree that was later use to perform calculations. Doing this in that way allow you to fully control what user enter, because only expressions that are compatible with grammar will be parsed.

提交回复
热议问题