1

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?

JayGatsby
  • 1,541
  • 6
  • 21
  • 41

2 Answers2

3

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

global finish_control
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70
3

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

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
  • 1
    returning always beats global – Padraic Cunningham Mar 30 '15 at 19:35
  • I know you guys are the experts, but could you explain why the language feature exists if it is not secure. I mean why are globals, eval, etc. not considered safe. I mean if a programmer adheres to what they have in mind there should never be a crash in the program, right? – Malik Brahimi Mar 30 '15 at 19:36
  • @MalikBrahimi Refer http://stackoverflow.com/questions/19158339/python-why-are-global-variables-evil – Bhargav Rao Mar 30 '15 at 19:38