我试图在Python中编写一个实时记录IP摄像头流的脚本。它只保留大约一分钟的录音,不断覆盖相同的文件。每当触发外部传感器时,我想要设置一个变量(事件变量),该变量将记录与传感器触发后记录的额外30秒合并。然后将合并后的90秒保存为日期和时间以供日后查看。
这个想法是有2个无限期的循环,第一个包含实时录音和事件。第二个将不断读取输入并激活“事件”。功能。最初我虽然我可以拥有之前已经学过的硬件中断的软件版本,但经过一些研究后似乎只能用于例外。我目前正在使用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 :(得分:0)
两个进程不会共享数据,因此每个进程都将包含这些全局变量的副本,这些副本对您无效。
最好的选择是线程或共同例程(gevent)。我假设您的逻辑是 - &gt;记录30秒,检查事件是否被触发,如果是,则记录另外30秒并合并。即我假设您不需要在事件触发后立即停止记录。