英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论