0

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.

2
  • Take a look at expression trees, it is what you will need to be doing here. Commented Apr 3, 2013 at 19:41
  • using the variables as string inside the expression is creating trouble :( Commented Apr 3, 2013 at 19:47

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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:

1 Comment

Pyparsing is no longer hosted on wikispaces.com. Go to github.com/pyparsing/pyparsing

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.