2017-05-04 1 views
0

해당 if 문 내의 코드를 사용하여 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_onalarm_activehandle(msg)있어서 내의 글로벌 선언된다. foo == 'chiuso' 인 경우 해당 코드는 실행되지 않습니다. 전역 변수를 사용하는 데 문제가 있습니까?

+0

제대로 while 루프를 들여되지 않은 : 그래서이 코드를 사용해보십시오. 또한 왜 'while while : while while : 1 :'을하고 있습니까? – snb

+1

'check_output'이 정확히 "chiuso"를 반환하는지 확인하십시오. "chiuso \ n"? 너 해봤 어? –

+0

@snb 동일하지만, 당신 말이 맞습니다. True는 더 읽기 쉽습니다. 감사합니다 안톤, 문제는 내가 깜빡했다. \ n :) – Caosman

답변

1
  • alarm_active은 코드 스 니펫에 따라 절대로 true이되지 않습니다.
  • alarm_active=true으로 설정한다고 가정하면 python one_sensor_alarm.py이 문자열 끝 부분에 \n을 반환하면 if foo == "chiuso":이 작동하지 않습니다. 당신의 while 루프는 즉시 실행하고 핸들 기간 사용되지 않습니다 ...
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) 
+0

'alarm_active가 True이면'또는 'if alarm_active == True' 중 하나를 만들 필요가 없습니다 .alarm_active가 부울이기 때문에 그냥 사용하십시오 'if alarm_active :'와 같습니다. –

+0

@derkan alarm_active handle (msg)을 실행 한 후 True가됩니다. – Caosman

관련 문제