2016-10-11 5 views
1

저는 실시간으로 IP 카메라의 스트림을 기록하는 스크립트를 파이썬으로 작성하려고합니다. 동일한 파일을 계속 덮어 쓰면서 약 1 분 분량의 기록 만 유지합니다. 외부 센서가 트리거 될 때마다 센서를 트리거 한 후 기록을 추가 30 초로 병합하는 변수 (이벤트 변수)를 설정해야합니다. 결합 된 90 초는 이후 검토를 위해 날짜와 시간으로 저장됩니다.두 개의 무한 루프를 동시에 실행하는 동시에 변수를 변경하는 방법은 무엇입니까?

아이디어는 2 개의 무기한 while 루프를 가지며 첫 번째 루프는 실시간 기록과 이벤트를 모두 포함합니다. 두 번째는 지속적으로 입력을 읽고 '이벤트'기능을 활성화합니다. 처음에는 하드웨어 인터럽트 소프트웨어 버전을 사용할 수 있었지만 일부 연구를 거친 후에는 예외 사항 만있는 것으로 보였습니다. 현재 키 누르기로 외부 입력을 시뮬레이트하는 TkInter를 사용하고 있습니다.

입력을 시도해도 이벤트가 트리거되지 않습니다. 그래서 제 질문은 : 어떻게 '이벤트'가 실제로 실시간으로 발생할 수 있도록 입력 루프가 메인 루프에서 변수를 변경하는 동시에 두 개의 무한 루프를 동시에 실행합니까?

스트림을 기록하기 위해 ffmpeg를 사용하기 때문에 일단 명령을 호출하면 기록을 중지 할 수 없지만 최대한 빨리 이벤트 변수를 변경하고 싶습니다.

다중 루프와 관련하여 몇 가지 유사한 질문을 살펴본 결과 멀티 프로세싱을 시도했지만 (성능은 중요하지 않지만 여기서는 중요하지 않음) 두 개의 개별 파일을 만들었는지 모르지만 함께) 그리고 마지막으로, 스레드. 이들 중 아무 것도 내가 원하는 방식으로 실행시킬 수 없기 때문에 내 상황에서 작동하는 것 같습니다.

i = 0 
event = False 
aboutToQuit = False 
someVar = 'Event Deactivated' 
lastVar = False 

def process(frame): 
    print "Thread" 
    i = 0  
    frame = frame 
    frame.bind("<space>", switch) 
    frame.bind("<Escape>", exit) 
    frame.pack() 
    frame.focus_set() 

def switch(eventl): 
    print(['Activating','Deactivating'][event]) 
    event = eventl 
    event = not(event) 

def exit(eventl): 
    print'Exiting Application' 
    global aboutToQuit 
    #aboutToQuit = True 
    root.destroy() 

print("the imported file is", tkinter.__file__) 
def GetTime(): #function opens a script which saves the final merged file as date and time. 
    time = datetime.datetime.now() 
    subprocess.call("./GetTime.sh", shell = True) 
    return (time) 

def main(root): 
    global event, aboutToQuit, someVar,lastVar  
    while (not aboutToQuit): 
     root.update() # always process new events 

     if event == False: 
      someVar = 'Event Deactivated' 
      subprocess.call(Last30S_Command) #records last 30 seconds overwriting itself. 
      print "Merge now" 
      subprocess.call(Merge_Command) #merges last 30 seconds with the old 30 seconds  
      print "Shift now" 
      subprocess.call(Shift_Command) #copies the last30s recording to the old 30 seconds, overwriting it. 
      if lastVar == True: #Triggers only when lastVar state changes 
       print someVar 
       lastVar = False 
      time.sleep(.1) 

     if event == True: 
      someVar = 'Event Activated' 
      print"Record Event" 
      subprocess.call(EventRecord_Command) #records 30 seconds after event is triggered. 
      print"EventMerge Now" 
      subprocess.call(EventMerge_Command) # merges the 1 minute recording of Merge_Command with 30 seconds of EventRecord_Command 
      if lastVar == False: 
       print someVar 
       lastVar = True 
      time.sleep(.1) 
      GetTime() #Saves 90 seconds of EventMerge_Command as date and time. 
      subprocess.call(EventShift_Command) #Copies EventRecord file to the old 30 second recording, overwriting it 

     if aboutToQuit: 
      break 


if __name__ == "__main__": 
    root = Tk() 
    frame = Frame(root, width=100, height=100) 
# maintthread = threading.Thread(target=main(root)) 
# inputthread = threading.Thread(target=process(frame)) 
# inputthread.daemon = True 
# inputthread.start() 
# maintthread.daemon = True 
# maintthread.start() 
# maintthread.join() 
    Process(target=process(frame)).start() 
    Process(target=main(root)).start() 
    print "MainLoop" 
+0

파이썬에서 스레딩을 살펴보십시오. 또한 변수가 변경되거나 서로 영향을 주어야하는 경우 잠금을 고려하십시오. – rocksteady

답변

0

두 프로세스가 데이터를 공유하지 않으므로 각 프로세스가 당신을 위해 작동하지 않습니다 그 전역 변수의 복사본을 포함합니다 :

여기 스레드를 사용하여 내 최신 시도이다.

가장 좋은 방법은 스레딩 또는 공동 루틴 (gevent)입니다. 나는 당신의 논리가 있다고 가정하고 -> 30 초를 기록하고, 사건이 일어나면 30 초를 더 병합하여 병합합니다. 즉, 사건이 발생하자마자 녹음을 중단 할 필요가 없다고 가정합니다.

관련 문제