简体   繁体   English

虽然真实循环没有结束

[英]While true loop not ending

I have 3 functions. 我有3个功能。 listener function calls check_url function in every 10 seconds. listener函数每10秒调用一次check_url函数。 If this function success on checking, it calls destroy function. 如果此函数检查成功,它将调用destroy函数。 After destroy function done it's job, i want to terminate the listener I tried to do it with finish_control variable destroy功能完成工作后,我想终止我尝试使用finish_control变量执行的listener

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. 但是, listener器中的while循环不会终止。 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? destroy完成后,如何使它停止?

确保finish_control是全局定义的,并在您的destroy函数中添加以下内容:

global finish_control

The problem is finish_control in function destroy is local to the function. 问题是finish_control在函数destroy是该函数的局部函数。 The finish_control in listener is not the same variable. listener器中的finish_control是不同的变量。 The work around for this is to return the values as in 解决的方法是return值,如

  • In your destroy method add a line return 1 instead of finish_control = 1 在您的destroy方法中,添加一行return 1而不是finish_control = 1
  • add a return before destroy(argv.location) destroy(argv.location)之前添加return
  • accept it in listener ie finish_control = check_url(url) listener接受它,即finish_control = check_url(url)

Note - Do not use global as it leads to security vulnerabilities 注意 -请勿使用global因为它会导致安全漏洞

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM