终止Python中的线程函数

huangapple go评论128阅读模式
英文:

terminate threaded function in python

问题

以下是代码的翻译部分:

active = True
while active:
    for i in range(COUNT):
        response = requests.Session()
        response.mount(engine, gateway)
        headers = {'Host': 'api.google.com', 'Content-type': 'application/json'}

        url = 'https://api.google.com'
        data = '{"code":"' + str("".join(random.choice('0123456789') for i in range(4))) + '"}'
        response = response.post(url, headers=headers, data=data)

        if response.status_code != 200 or response.json()['result']['displaymessage'] == 'Verification not successed.':
            proc = Thread(target=verify, args=[engine, gateway])
            usleep(10000)
            proc.start()
        else:
            gateway.shutdown()
            break
            proc.terminate()
            active = False

如果您想要在else语句中停止线程循环,请确保将proc.terminate()移到else语句块内,以便在满足条件时终止线程。

英文:
 active = True
 while active:
  for i in range(COUNT):	
   response = requests.Session()
   response.mount(engine, gateway)			
   headers = {'Host': 'api.google.com',
                 'Content-type': 'application/json'}
                
   url = 'https://api.google.com'
   data = '{"code":"'+ str("".join(random.choice('0123456789')for i in range(4)))}'
   response = response.post(url, headers=headers, data=data)			 
   if response.status_code != 200 or response.json()['result']['displaymessage'] == 'Verification not successed.':
    proc = Thread(target=verify, args=[engine,gateway])
    usleep(10000)
    proc.start()
    #print(response.text)	  
   else:  
    gateway.shutdown()
    break
    proc.terminate()
    active = False	

**i want to stop the threaded loop within else statment . the current code keeps trying without breaking **

答案1

得分: 0

你可以设置一个 flag 来终止这个进程 -

def verify(engine, gateway):
    global flag

循环内部:

for i in range(5000):
    if flag:
        break

在 else 块内部:

else: 
    terminate_flag = True
英文:

You can set a flag to terminate the process -

def verify(engine, gateway):
    global flag

Inside for loop:

for i in range(5000):
    if flag:
        break

Inside else block:

else: 
    terminate_flag = True 

huangapple
  • 本文由 发表于 2023年5月7日 10:23:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76191958.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定