I am wondering if I can run a while loop inside a method of a Python class that can be stopped from another method.
For example, something like this:
from time import sleep
class example():
global recording
def __init__(self):
pass
def start(self):
global recording
recording = True
while recording:
print(1)
def stop(self):
global recording
recording = False
print("SLEEEPINGGGGGGGGGGG")
a = example()
a.start()
sleep(0.5)
a.stop()
But, it does not work, the loop does not stop.
EDIT Since I do not want to create a Thread outside the class, I just tried this, but it doesn't work either.
from time import sleep
import threading
class example():
def __init__(self):
self.is_running = False
def start(self):
self.is_running = True
self.loop_thread = threading.Thread(target=self.main_loop)
def main_loop(self):
while self.is_running:
sleep(0.5)
print(1)
def stop(self):
self.is_running = False
print("SLEEEPINGGGGGGGGGGG")
a = example()
a.start()
sleep(3)
a.stop()