Somesh
Somesh

Reputation: 1295

evaluate string arithmetic expression using python

How can I evaluate following:

a=b=c=d=e=0  # initially

if user enters:

"a=b=4" as a string, it should modify the existing value.

So result would be something like a=4, b=4 if user enters:

"a=(c=4)*2", it should evaluate as expression and update the values.

so result would be something like a=8, c=4

The brackets can be nested further.

Any help would be really appreciated. I am using python.

Upvotes: 0

Views: 556

Answers (2)

Paulo Scardine
Paulo Scardine

Reputation: 77241

Probably the best way is writing a parser for this particular grammar (the worst is something involving eval/exec - submitting user-provided content to these functions is a security can of worms).

Take a look at this example:

Upvotes: 1

Michael Pratt
Michael Pratt

Reputation: 3496

If this is a trivial console script where security is absolutely no concern, you can use exec() to execute mathematical statements. However, python does not support code such as a=(c=4)*2, so it won't be possible to do natively.

However, exec() is a gaping security hole if this is running on, say, a web server. If this is expected to be something where untrusted and potentially malicious users can submit commands, you should look into either sanitizing it and parsing it yourself, or implementing sandboxing.

TL;DR Since you're working on custom commands not supported, you should write your own parser to handle and execute these without worrying about executing untrusted code.

Upvotes: 3

Related Questions