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