crankshaft
crankshaft

Reputation: 2677

python cleanly exiting a class loop

I have a python CLASS that I am unable to exit cleanly from by calling the stop method.

I have a small delay in a loop so that I can catch the stop request as soon as possible:

from time import sleep
more imports...

class XXX:
    def __init__():
        self.enable = True
        more code...

    def stop(self):
      self.enable = False

    def loop(self):
      do something....   

    def run(self):
      while self.enable:    
        self.loop()
        for i in range(15):
          if(not self.enable):
            break
          else:
            sleep(1)

The loop runs fine until I call the stop() method and it crashes with:

NameError: name 'sleep' is not defined

How can I exit this cleanly ??

Upvotes: 0

Views: 199

Answers (1)

Israel Unterman
Israel Unterman

Reputation: 13510

sleep belongs to the time module. So just add at the top:

from time import sleep

or

import time

and then call sleep:

time.sleep(1)

Upvotes: 1

Related Questions