2015-03-30 53 views
1

我有3個功能。 listener函數每10秒鐘調用一次函數check_url。如果此功能成功檢查,則調用destroy函數。 destroy函數來完成它的工作後,我要終止的listener我試着用finish_control可變雖然真正的循環沒有結束

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 

但是這裏面listener while循環不會終止做到這一點。我也試過

while (finish_control == 0): 

還有同樣的問題。如何在destroy完成工作後停止工作?

+1

'listener()'函數不知道'finish_control'變量 – fedorqui 2015-03-30 19:32:09

回答

3

確保finish_control是全局定義,並在您destroy函數中添加以下內容:

global finish_control 
+0

哦謝謝。它解決了我的問題 – JayGatsby 2015-03-30 19:34:33

+0

隨時請標記爲答案。 – 2015-03-30 19:35:02

+1

我會在幾分鐘內標出它現在不允許我 – JayGatsby 2015-03-30 19:39:43

3

的問題是在功能上destroyfinish_control是本地功能。在listener中的finish_control不是相同的變量。造成這種情況的解決辦法是return的值作爲

  • 在你destroy方法中添加一行return 1,而不是finish_control = 1
  • 添加returndestroy(argv.location)
  • 接受它在listenerfinish_control = check_url(url)

注意 - 請勿使用global作爲它廣告到安全漏洞

+1

返回總是打敗全球 – 2015-03-30 19:35:24

+0

我知道你們是專家,但是你能解釋爲什麼語言功能存在,如果它不安全。我的意思是爲什麼globals,eval等不被認爲是安全的。我的意思是,如果一個程序員堅持他們的想法,程序中永遠不會崩潰,對吧? – 2015-03-30 19:36:24

+0

@MalikBrahimi請參閱http://stackoverflow.com/questions/19158339/python-why-are-global-variables-vil – 2015-03-30 19:38:36