终止Python中的线程函数

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

terminate threaded function in python

问题

以下是代码的翻译部分:

  1. active = True
  2. while active:
  3. for i in range(COUNT):
  4. response = requests.Session()
  5. response.mount(engine, gateway)
  6. headers = {'Host': 'api.google.com', 'Content-type': 'application/json'}
  7. url = 'https://api.google.com'
  8. data = '{"code":"' + str("".join(random.choice('0123456789') for i in range(4))) + '"}'
  9. response = response.post(url, headers=headers, data=data)
  10. if response.status_code != 200 or response.json()['result']['displaymessage'] == 'Verification not successed.':
  11. proc = Thread(target=verify, args=[engine, gateway])
  12. usleep(10000)
  13. proc.start()
  14. else:
  15. gateway.shutdown()
  16. break
  17. proc.terminate()
  18. active = False

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

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

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

答案1

得分: 0

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

  1. def verify(engine, gateway):
  2. global flag

循环内部:

  1. for i in range(5000):
  2. if flag:
  3. break

在 else 块内部:

  1. else:
  2. terminate_flag = True
英文:

You can set a flag to terminate the process -

  1. def verify(engine, gateway):
  2. global flag

Inside for loop:

  1. for i in range(5000):
  2. if flag:
  3. break

Inside else block:

  1. else:
  2. 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:

确定