[英]How do I run two indefinite loops simultaneously, while also changing variables within them?
我正在嘗試用Python編寫一個腳本,實時記錄IP攝像機的流。 它只保留大約一分鍾的錄音,不斷覆蓋相同的文件。 每當觸發外部傳感器時,我想要設置一個變量(事件變量),該變量將記錄與傳感器觸發后記錄的額外30秒合並。 然后將組合的90秒保存為日期和時間以供稍后查看。
這個想法是有兩個不定時的循環,第一個包含實時記錄和事件。 第二個將不斷讀取輸入並激活“事件”功能。 最初我雖然我可能只有一個我以前學過的硬件中斷的軟件版本,但經過一些研究后似乎只是例外。 我目前正在使用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"
兩個進程不會共享數據,因此每個進程都將包含這些全局變量的副本,這些變量對您無效。
最好的選擇是線程或共同例程(gevent)。 我假設您的邏輯是 - >記錄30秒,檢查事件是否被觸發,如果是,則記錄另外30秒並合並。即我假設您不需要在事件觸發后立即停止記錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.