如何同时运行两个无限循环,同时还要更改其中的变量?
问题描述:
我想在Python中编写一个脚本,实时记录IP摄像头的流。它只保留大约一分钟的记录,不断覆盖相同的文件。每当外部传感器被触发时,我想要设置一个变量(事件变量),该变量将传感器被触发后记录的额外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"
答
两个进程将无法共享数据,所以每个过程将包含这些全局变量,这会不会为你工作的一个副本。
最好的选择是线程或co-routines(gevent)。我假设你的逻辑是 - >记录30秒,检查事件是否被触发,如果是,记录另外30秒并合并,即假设你不需要在事件触发时立即停止记录。
看看python中的线程。同样考虑锁定,如果变量变化应该是相同的或者以某种方式相互影响。 – rocksteady