简体   繁体   English

如何同时运行两个不定循环,同时还要更改其中的变量?

[英]How do I run two indefinite loops simultaneously, while also changing variables within them?

I'm trying to write a script in Python that records a stream of an IP camera in realtime. 我正在尝试用Python编写一个脚本,实时记录IP摄像机的流。 It only keeps about a minute worth of recording, constantly overwriting the same files. 它只保留大约一分钟的录音,不断覆盖相同的文件。 Whenever an external sensor is triggered I want a variable to be set (event variable) which merges the recording with an extra 30 seconds it records after the sensor is triggered. 每当触发外部传感器时,我想要设置一个变量(事件变量),该变量将记录与传感器触发后记录的额外30秒合并。 The combined 90 seconds are then saved as the date and time for later review. 然后将组合的90秒保存为日期和时间以供稍后查看。

The idea was to have 2 indefinite while loops, the first containing both the real time recording and the event. 这个想法是有两个不定时的循环,第一个包含实时记录和事件。 The second one would constantly read input and activate the 'event' function. 第二个将不断读取输入并激活“事件”功能。 Initially I though I could just have a software version of the hardware interrupt I've learned before, though after some research it seems that's only for exceptions. 最初我虽然我可能只有一个我以前学过的硬件中断的软件版本,但经过一些研究后似乎只是例外。 I'm currently using TkInter, simulating the external input with keypresses. 我目前正在使用TkInter,用按键模拟外部输入。

When I tried it out the input wouldn't cause the event to be triggered. 当我尝试输出时,输入不会导致事件被触发。 So my question is: How do I run the two indefinite loops simultaneously, while also having the input loop change variables in the main loop so that the 'event' can actually occur in real-time? 所以我的问题是:如何同时运行两个不定循环,同时在主循环中输入循环更改变量,以便'事件'实际上可以实时发生?

Since I'm using ffmpeg to record the stream, once the command is called to record it can't be stopped, but I want the event variable to be changed as soon as possible. 由于我使用ffmpeg来记录流,一旦调用该命令进行记录就无法停止,但我希望尽快更改事件变量。

I've looked at several similar questions regarding multiple loops, and have tried multiprocessing(though this only seems to be used for performance, which is not that important here), making two separate files(not sure how to have them work together) and lastly, threads. 我已经看过几个关于多循环的类似问题,并尝试过多处理(虽然这似乎只用于性能,这在这里并不重要),制作两个单独的文件(不确定如何让它们一起工作)和最后,线程。 None of these seem to work in my situation as I can't get them running in the way that I want. 这些似乎都不适用于我的情况,因为我不能让它们以我想要的方式运行。

Here is my latest attempt, using threads: 这是我最近的尝试,使用线程:

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"

Two processes won't share data, so each process will contain a copy of those global variables, which won't work for you. 两个进程不会共享数据,因此每个进程都将包含这些全局变量的副本,这些变量对您无效。

The best bet is either threading or co-routines(gevent). 最好的选择是线程或共同例程(gevent)。 I"m assuming your logic is -> record 30 seconds, check if event triggered, if so, record another 30 seconds and merge. ie I"m assuming you don't need to stop recording as soon as the event is triggered. 我假设您的逻辑是 - >记录30秒,检查事件是否被触发,如果是,则记录另外30秒并合并。即我假设您不需要在事件触发后立即停止记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM