Breaking a while loop defined in a method, calling the break condition from another method

Viewed 21

I defined a class with two methods: StartRecording and StopRecording. The former implements a while loop for data recording in real-time, the latter breaks the recording. The while loop works until the elapsed time exceed a constant value. Let's say 3000ms. Here is the Python code.

class MyClass():
    def StartRecording(self):
        ...
        while elapsedTime < 3000:
        #do something
    
    def StopRecording(self):
        ...
        #do something

I would like to transform the break condition of the while loop. So I decided to use a boolean variable declared in the init and to modify its value in the StopRecording function.

class MyClass():
    def __init__(self):
        self.m_lock = Lock()
        self.isRecording = None

    def StartRecording(self):
        ...
        self.isRecording = True
        while self.isRecording:
           #do something
    
    def StopRecording(self):
        ...
        self.isRecording = False
        #do something

The class is defined in a module which is called from another script

import MyClassFile as mcf
import time

device = mcf.MyClass()
device.StartRecording()
time.sleep(3)
device.StopRecording()

Unfortunately, the recording doesn't stop! How can I modify it properly?

1 Answers

Following your example:

import MyClass as mc
import time

mc.StartRecording()
time.sleep(3)
mc.StopRecording()

You should create an instance of the class and then use that to start and stop the recording:

import MyClass as mc
import time

recorder_instance = mc()
recorder_instance.StartRecording()
time.sleep(3)
recorder_instance.StopRecording()
Related