Beautiful way to interrupt a loop in Python

时间:2018-02-26 17:40:01

标签: python

Let's say that we have the following code:

import time

class Foo(object):

    def __init__(self):
        pass

    def main_loop(self):
        while True:
            print('STAGE 1')
            time.sleep(1)

            print('STAGE 2')
            time.sleep(0.5)

            for i in range(20):
                print('.')
                time.sleep(0.1)

f = Foo()
f.main_loop()

And that we want to pause and resume the main_loop somehow. One of the most straightforward way to achieve it would be adding a kind of flag that determines the loop state, for instance:

import time

class Foo(object):

    def __init__(self):
        self.is_paused = False

    def main_loop(self):
        while True:
            print('STAGE 1')
            time.sleep(1)

            print('STAGE 2')
            time.sleep(0.5)

            for i in range(20):
                while self.is_paused:
                    time.sleep(0.01)
                print('.')
                time.sleep(0.1)

f = Foo()
f.main_loop()

Currently, we can pause the loop when it reachs the for, but not at the stages 1 and 2. Thus, we should copy and paste the following lines to almost every single line inside the while loop...

while self.is_paused:
    time.sleep(0.01)

So, my question is, there is a most correct/beatiful way to set up a pause/resume toggle for a loop?

And, in particular, there is another way to constantly check the state of a flag?

0 个答案:

没有答案