How to write a python script using declarative logic -
this complex question (at least me) , hope there's book/website/blog can point me to give me start. can tell me can find info write script in python reads bunch of logic statements , applies logic bunch of data being read in? can in non-declarative manner means time there's new logic statement, i'd need write new code handle it. if can write generic script can interpret logic statement, won't need keep writing code keep new logic statements.
what i'm trying have 3 files script read. 2 files of equal length contain values 2 metrics. third file logic statements. want script read in logic statements , apply statements numbers , write messages if fulfills statements.
for example, file 1 contain:
1 2 3 4 5 6
file 2 contain:
2 4 6 8 10 3
file 3, contain:
m1 >=3 && (m1 + m2) >= 11
if run script, want output says
m1 = 4 , m2 = 8 fulfills condition m1 >= 3 && (m1 + m2) >= 11 m1 = 5 , m2 = 10 fulfills condition m1 >= 3 && (m1 + m2) >= 11
i use eval function.
>>> m1 = 10 >>> m2 = 30 >>> statement = 'm1 < m2 , m2 == 30' >>> eval(statement) true
warning eval()
executes python code, if user can input statements, can run anything. dangerous on website. can parse statement before evaluation.
example safety check:
def parse(statement, m1, m2): statement = statement.replace('&&', ' , ') statement = statement.replace('||', ' or ') if is_safe(statement): eval(statement) def is_safe(to_test): safe_tags = ('m1', 'm2','>=', '<=', '>', '<', '==', '+', '-', '*', '/', '(', ')', 'and', 'or', '.') max_number_length = 20 tag in safe_tags: to_test = to_test.replace(tag, ' ') other in to_test.split(' '): if other == '': continue if other.isdigit() == false or len(other) > max_number_length: return false return true parse('m1 >=3 && (m1 + m2) >= 11', 10, 20)
use allowed tags (white list). propably need add samo more tags safe_tags
Comments
Post a Comment