JayGatsby
JayGatsby

Reputation: 1621

While true loop not ending

I have 3 functions. listener function calls check_url function in every 10 seconds. If this function success on checking, it calls destroy function. After destroy function done it's job, i want to terminate the listener I tried to do it with finish_control variable

def listener(url):
    while True:
        if finish_control == 1:
            break
        check_url(url)
        sleep(10)

def check_url(url):
    print ("Status: Listening")
    response = urllib.request.urlopen(url)
    data = response.read()
    text = data.decode('utf-8')
    if text == '1':
        print("--Action Started!--")
        destroy(argv.location)

def destroy(location):
    #some work
    print("---Action completed!---")
    finish_control = 1

But the while loop inside listener doesn't terminate. I also tried with

while (finish_control == 0):

There is also same problem. How can I make it stop after destroy finishes it's job?

Upvotes: 1

Views: 87

Answers (2)

Bhargav Rao
Bhargav Rao

Reputation: 52071

The problem is finish_control in function destroy is local to the function. The finish_control in listener is not the same variable. The work around for this is to return the values as in

  • In your destroy method add a line return 1 instead of finish_control = 1
  • add a return before destroy(argv.location)
  • accept it in listener i.e. finish_control = check_url(url)

Note - Do not use global as it leads to security vulnerabilities

Upvotes: 3

Malik Brahimi
Malik Brahimi

Reputation: 16711

Make sure finish_control is defined globally and in your destroy function add the following:

global finish_control

Upvotes: 3

Related Questions