pythonpython-2.7twistedtwisted.internet

Stop reactor in Twisted.internet after a condition


I have a simple code in which I am testing how Twisted.internet module is working. I am trying to stop the loop when a certain condition occurs (e.g: when i equals to 5), but I couldn't get it run. I have two main errors:

1.

exceptions.UnboundLocalError: local variable 'i' referenced before assignment

2. In case I just add reactor.stop() at the end without the If Statement, the loop doesn't stop, why ?

from twisted.internet import task
from twisted.internet import reactor

time = 1.0 # one seconds
i=0
def myfunction():
    print "sth"
    i +=1
    pass

l = task.LoopingCall(myfunction)
l.start(timeout) # call every second
reactor.run()
if i==5:
    reactor.stop()

Solution

    1. i should be declared as a global variable.

      i += 1 is equivalent to i = i + 1. If you don't declare it as a global variable, it is regarded as a local variable. The right part of the assignment tried to access the undefined local variable; cause of the UnboundLocalError.

    2. The if statement will never executed until the event loop stop. You need to put it inside the callback function.


    from twisted.internet import task
    from twisted.internet import reactor
    
    time = 1.0 # one seconds
    i = 0
    def myfunction():
        global i
        print "sth"
        i += 1
        if i == 5:
            reactor.stop()
    
    timeout = 0.1
    l = task.LoopingCall(myfunction)
    l.start(timeout) # call every second
    reactor.run()