0

I working on python based project where formula's are stored in dB. My script will read the formula's from a particular column and stored in list . For Eg

formula[0] = "round(float(latitude[:2]) + (float(latitude[2:]) / 60)"
formula[1] = "round(float(longitude[:3]) + float(longitude[3:]) / 60),6)"
formula[3] = "int(float(speed)*1.852)"

Through TCP socket comma separated values will be coming like

"imei:1234467454545,ac alarm,160302150105,,F,094605.000,A,1301.9905,N,08014.0746,E,0.19,298.01,,0,,,,;" 

by coding I have split the comma-separated values and stored in list. From the stream "1301.9905 " is latitude, "08014.0746" is longitude and "0.19" is speed value.

How can I apply the value in the formulas and store in some variable? I have tried this method

latitude = "1301.9905"
latitude = round(float(latitude[:2]) + (float(latitude[2:]) / 60),6)
print latitude
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Pradeep kumark
  • 39
  • 4
  • 13

1 Answers1

-1

you can store the formula in the as a python template and then use eval to execute it.

from string import Template

formula = "round((float($latitude) + float($latitude))/60)"
template = Template(formula)
out = template.substitute(latitude="1301.995")
eval(out)

here i am using eval method to execute the function.

for more info on templates check here

GIRISH RAMNANI
  • 614
  • 6
  • 18
  • This won't *execute* the formula. – Martijn Pieters Apr 06 '16 at 07:17
  • the `eval`at the end will – GIRISH RAMNANI Apr 06 '16 at 07:25
  • In many conditions, `eval` is considered evil. OP says the function string will be stored in the database, so it is possibly reachable by some other people too `eval`uating something without being sure what it could be is possibly dangerous – Mp0int Apr 06 '16 at 07:34
  • I'd strongly advice against using `eval()`; if there is any injection path to the database, you can get Python to execute arbitrary code this way. Use `asteval` instead. – Martijn Pieters Apr 06 '16 at 07:34
  • Besides, if you are going to interpret the string as a Python expression, you may as well use `exec()` so you can just pass in `locals()` to use in the expression without any substitutions. – Martijn Pieters Apr 06 '16 at 07:36
  • but the user requires this sort of functionality. also the user can add a sensitization step before passing it to the eval. – GIRISH RAMNANI Apr 06 '16 at 07:42
  • The highest voted answer in the duplicate question have many good examples of *how eval could be evil* . Using eval may look prettier and easier to use, but it have many side effects so any use should avoid using it if they are not 100% sure what will be evaluated. [This is better for explaination](http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html) . So it is not easy to make controls to check whether ou are evaluating something good or not. Use `literal_eval` instead – Mp0int Apr 06 '16 at 08:00