我是 python 新手,我需要简化这个检查器。我该如何改变:
...
if c == '>' and ( prevTime > currentTime ):
c2 = True
elif c == '>=' and ( prevTime >= currentTime ):
c2 = True
...
类似于:
if prevTime | condition | currentTime:
doSomething()
我尝试使用evaluate或compile,但在创建字符串期间,日期时间对象与字符串之间存在转换(日期时间对象上的str)。例如:
>>> 'result = %s %s %s' % (datetime.now(), '>', datetime.utcfromtimestamp(41))
'result = 2011-04-07 14:13:34.819317 > 1970-01-01 00:00:41'
并且无法比较。
有人可以帮我弄这个吗?下面的工作示例:
def checkEvent( prevEvent, currentEvent, prevTime, currentTime ):
def checkCondition( condition ):
#condition format
#tuple ( (oldEvent, newEvent), time, ip)
# eg: (('co', 'co'), '>=', '!=')
c1 = c2 = False
#check Event
if prevEvent == condition[0][0] and currentEvent == condition[0][1]:
c1 = True
else:
return False
#check time
if condition[1]:
c = condition[1]
if c == '>' and ( prevTime > currentTime ):
c2 = True
elif c == '>=' and ( prevTime >= currentTime ):
c2 = True
elif c == '<' and ( prevTime < currentTime ):
c2 = True
elif c == '<=' and ( prevTime <= currentTime ):
c2 = True
elif c == '==' and ( prevTime == currentTime ):
c2 = True
else:
c2 = True
return c1 and c2
def add():
print 'add'
def changeState():
print 'changeState'
def finish():
print 'finish'
def update():
print 'update'
conditions = (\
( ( ( 're', 'co' ), None ), ( add, changeState ) ),
( ( ( 'ex', 'co' ), None ), ( add, changeState ) ),
( ( ( 'co', 'co' ), '<' ), ( add, changeState ) ),
( ( ( 'co', 'co' ), '>=' ), ( add, changeState, finish ) ),
( ( ( 'co', 'co' ), '>=' ), ( update, ) ),
( ( ( 'co', 're' ), '>=' ), ( changeState, finish ) ),
( ( ( 'co', 'ex' ), '>=' ), ( changeState, finish ) )
)
for condition in conditions:
if checkCondition( condition[0] ):
for cmd in condition[1]:
cmd()
from datetime import datetime
checkEvent( 'co', 'co', datetime.utcfromtimestamp(41), datetime.now() )
checkEvent( 'ex', 'co', datetime.utcfromtimestamp(41), datetime.now() )
checkEvent( 'co', 'co', datetime.utcfromtimestamp(41), datetime.utcfromtimestamp(40) )