Skip to main content
 首页 » 编程设计

python之虽然真正的循环没有结束

2025年05月04日16artech

我有 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 完成它的工作后停止?

请您参考如下方法:

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

global finish_control