1

I have an if statement in a .ini file:

critical= $TREND$>=40

In my script I replace $TREND$ by my value so I have in a variable:

critical = "10.5>=40"

I try to execute this if statement to know if it's True or False.

if critical:
   print "It's critical!"

(I know it will just check if critical is empty)

2
  • You could eval the string, but that's potentially risky - the .ini file could contain anything. Why not parse it? Commented Mar 11, 2015 at 16:19
  • i would advice you to have critical_low a critical_high in your .ini which will make your code better. eval is evil Commented Mar 11, 2015 at 16:24

2 Answers 2

2

One option is to use eval:

critical = eval("10.5>=40")

However, you must be sure that what is "eval'ed" is completely trusted, because it allows you to execute any arbitrary python code. That is, don't use this if any part of the string is passed in by an "untrusted entity" (user, external api, etc).

Another, possibly better, option might be to use a "template parser" which allows "untrusted" or "sandboxed" execution. For example, the Jinja Sandbox mode.

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

1 Comment

Indeed I know this is bad in a security perspective but this is awesome! Thanks.
0

I would urge you to change your .ini to have following:

critical_low

critical_high

this way you avoid two problems - you don't have to use eval which can be very dangerous, and you don't have logic in your .ini unless you do want logic there which still can be solved without using eval

said that eval will work fine if it's just a hacky script

2 Comments

It's just I need the operator. Sometime critical will be $VALUE$<1
fair enough :) you can always add critical_operator but it will bloat your code somehow. guess i just really don't like eval :)

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.