Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
746 views
in Technique[技术] by (71.8m points)

parsing - Safe expression parser in Python

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 expressions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The Pyparsing examples page lists several expression parsers:

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 - 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 - A pair of examples recasting fourFn.py using operatorPrecedence. The first just parses and returns a parse tree, the second adds evaluation logic.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...