我无法使用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_active
和alarm_on
在handle(msg)
方法中声明为全局变量。
当foo == 'chiuso'
时,该if中的代码不会被执行。
是使用全局变量的问题吗?
答案 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)