2014-04-03 2 views
0

적외선 센서가 달린 나무 딸기 파이가 있습니다. 내 파이썬 스크립트에는 imap 서버를 청취하는 스레딩 클래스가 있습니다 (START 또는 STOP과 같은 명령을 catch합니다). 내 아이디어는 이제 전자 메일을 통해 명령을 보내고 스크립트가 명령을 받자 마자 새 명령을받을 때까지 일부 기능을 사용하지 않아야합니다. 하지만 주요 쟁점은 이제 어떻게 구현해야할지 모르겠다는 것입니다. 유용하고 유용한 아이디어에 감사드립니다.Python : 함수를 사용하거나 사용하지 않도록 설정하는 방법은 무엇입니까?

def take_picture(): 
    ... 

def take_video(): 
    ... 

class EmailThread(threading.Thread): 

    def __init__(self): 
     threading.Thread.__init__(self) 

    def run(self): 
     while True: 
     .... 
       if get_mail == 1: 
        if var_subject == 'STOP': 
         #TODO: stop take_picture(), take_video() 
         pass 

        elif var_subject == 'START': 
        #TODO: start take_picture(), take_video() 
         pass 
        else: 
         print u'Wrong command' 

     time.sleep(600) #google doesn't like many connections within 10min 

def main(): 
    # Start eMail Thread 
    email = EmailThread() 
    email.start() 
    try: 
     print "Waiting for PIR to settle ..." 
     # Loop until PIR output is 0 
     while GPIO.input(GPIO_PIR) == 1: 
      Current_State = 0 
     print "Ready" 
     # Loop until threadingusers quits with CTRL-C 
     while True : 
      # Read PIR state 
      Current_State = GPIO.input(GPIO_PIR) 
      if Current_State == 1 and Previous_State == 0: 
       counter = counter + 1 
       # PIR is triggered 
       start_time = time.time() 

       log_to_file('Motion Nr. %s detected!' % counter) 
       take_picture() 

       # Record previous state 
       Previous_State = 1 

      elif Current_State == 0 and Previous_State == 1: 
       # PIR has returned to ready state 
       stop_time=time.time() 
       print " Ready ", 
       elapsed_time=int(stop_time-start_time) 
       print " (Elapsed time : " + str(elapsed_time) + " secs)" 
       Previous_State = 0 

    except KeyboardInterrupt: 
     print "Quit " 
     # Reset GPIO settings 
     GPIO.cleanup() 

if __name__ == '__main__': 
    main() 
+0

'python2'를 사용해야하는 구체적인 이유가 없다면'python3'을 사용하여 sugest합니다. 'python2'를 사용하기로 결정했다 할지라도'print'를 함수로 사용하는 것이 좋습니다. –

+0

일부 모듈은 picamera와 같이 python2에서만 실행되기 때문에 python2.7을 사용하고 있습니다 – Seppo

+0

멋진 아키텍처를 찾으십니까? 나는 전자 메일 스레드에 bool 플래그를 설정하고 메인 루프에'if email.enable_picture :'를 넣을 것이다. – dornhege

답변

1

귀하의 질문 제목을 잘못 선택했다고 생각합니다. 제 생각에는 기능을 실행중인 스레드 스레드를 시작/중지하는 것입니다. 쓰래드를 시작하는 것은 쉽지만, 멈추는 것은 약간 어렵고 내부적으로 어떤 일을하는지에 달려 있습니다.

스레드 간 통신 방법, 특히 condition variables을 조사해야합니다. 일반적으로 스레드는 조건 변수를 사용하는 경우처럼 정상적으로 만 중지 할 수 있습니다.

실제로 스레드를 사용하지 않으려면

, 대신 주기적으로은 현재 활성 기능을 실행하려면, 당신은 스케줄러 구현해야 - 가장 쉬운 경우를, 스케줄러 것의 목록을 단순히 반복 루프 활성 함수를 호출하고 호출합니다.

스레드는 대부분 불필요한 복잡성과 오류 소스를 도입하기 때문에 후자를 권하고 싶습니다.하지만 질문에서 당신은 처음에 그렇게하기로 결정한 것처럼 들립니다.

1

는 초기화에, 당신은 너무

class ClassWithTheFunctions: 
    def __init__(self): 
     import types 
     #... 
     self.funcMap = {} 
     for o in self.__dict__: 
      if type(self.__dict__[o]) == types.FunctionType or type(self.__dict__[o]) == types.MethodType: 
       self.funcMap[self.__dict__[o]] = True 

당신이 함수를 호출 할 때, 당신은 첫

if instanceOfTheClassWithTheFunctions.funcMap[funcIWantToCall] : 
    funcIWantToCall() 

당신이 원하는 경우 확인 같은 논리 값에 기능 심판의지도를 추가 할 수 있습니다

instanceOfTheClassWithTheFunctions.funcMap[funcIWantToCall] = False 

또는 활성화 : 기능을 사용하지

instanceOfTheClassWithTheFunctions.funcMap[funcIWantToCall] = True 
관련 문제