Python compile()中的赋值

时间:2018-10-25 20:00:34

标签: python

你好,我有一个问题,但我不知道怎么回事:

我将此代码语句括在字符串中:

proccessingCode='''

if(float(sensor.value)>1):
    if(float(sensor.value)>400):
        light=True
    else:
        light=False
else:
    if(sensor.value==1):
        motion=True
    else:
        motion=False
'''

然后我将此字符串传递给此方法:

def process(self,codeToProcess):
        light=False
        motion=False
        for msg in self.protocol.messageFlow :
            time.sleep(0.175)
            sensor=self.appInterface.createSensorDataObj(msg)
            print(sensor.value)
            codeObejct = compile(codeToProcess, '', 'exec')
            exec(codeObejct)
            if (light==True or motion==True):
                print("there is someone !")
            else:
                print("Nobody in da place !")

如您所见,我使用compile()exec(),但尽管在if语句中进行了测试,light=Truemotion=False这样的字符串中的分配却无法正常工作{1}}即使传感器是一个外部变量也可以正常工作。我的问题是为什么从来没有做出过承诺?我尝试设置全局的灯光和运动变量,而不是if (float(sensor.value)>400),我尝试了light=True,但没有任何效果

如果有人可以给我提示,那就太好了!

0 个答案:

没有答案