无法从if语句中更改变量状态

时间:2017-05-04 14:41:52

标签: python if-statement while-loop global-variables

我无法使用if语句中的代码更改if语句之外的变量值。

#import lines here

alarm_active=False
alarm_on=False

def handle(msg):
    global alarm_active
    global alarm_on
    #other lines of code

while 1:
    print 'while works'
    if alarm_active==True:
        print 'alarm works'
        foo = subprocess.check_output("python one_sensor_alarm.py", shell=True)
        print foo
        if foo == 'chiuso':
            print "intrusion"
            alarm_on=True
            alarm_active=False
    time.sleep(1)

两个变量alarm_activealarm_onhandle(msg)方法中声明为全局变量。 当foo == 'chiuso'时,该if中的代码不会被执行。 是使用全局变量的问题吗?

1 个答案:

答案 0 :(得分:1)

    根据您的代码段,
  • alarm_active永远不会是true
  • 如果我们假设设置了alarm_active=true,那么if foo == "chiuso":如果python one_sensor_alarm.py在字符串末尾返回\n则无效。所以试试这段代码:
import subprocess
import time

alarm_active = True
alarm_on = False


def handle(msg):
    global alarm_active
    global alarm_on
    # other lines of code


while 1:
    print('while works')
    if alarm_active is True:
        print('alarm works')
        foo = subprocess.check_output("python one_sensor_alarm.py", shell=True)
        print("foo %s" % repr(foo))
        if foo.strip() == "chiuso":
            print("intrusion")
            alarm_on = True
            alarm_active = False
    time.sleep(1)