Python exit from all running threads in true mode

I use streams to check the header status code from the API URL. How can I stop the loop / stop all other threads if the condition is true. Please check the following code.

import logging, time, threading, requests

#: Log items
logging.basicConfig(format='%(asctime)s %(levelname)s : %(message)s', level=logging.INFO)

class EppThread(threading.Thread):
    def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None):
        threading.Thread.__init__(self, group=group, target=target, name=name, verbose=verbose)
        self.args = args

    def run(self):
        startTime = time.time()
        url = self.args[0]
        limit = self.args[1]

        for i in range(limit):
            response = requests.get(url)
            if response.status_code != 200:
                break
                #Exit other similar threads (with same url)
            else:
                print('Thread {0} - success'.format(thread.getName()))

         print('process completed')
         # Send Email


number_of_threads = 5
number_of_requests = 100

urls = ['https://v1.api.com/example', 'https://v2.api.com/example']

if __name__ == '__main__':
    startTime = time.time()

    for url in urls:
        threads = []
        for i in range(number_of_threads):
            et = EppThread(name = "{0}-Thread-{1}".format(name, i + 1), args=(url, number_of_requests))
            threads.append(et)
            et.start()

    # Check if execution time is not greater than 1 minute  
    while len(threads) > 0 and (time.time() - startTime) < 60:
        time.sleep(0.5)
        for thread in threads:
            if not thread.isAlive():
                threads.remove(thread)
                print('Thread {0} terminated'.format(thread.getName()))

    os._exit(1)

Please suggest several ways that stop code execution if the condition becomes true in any running thread.

Thank you for your help.

+6
source share
3 answers

, run a Thread , Thread . , boolean, . , ; , , :

import logging, time, threading, requests

#: Log items
logging.basicConfig(format='%(asctime)s %(levelname)s : %(message)s', level=logging.INFO)


class EppThread(threading.Thread):
    kill = False  # new Boolean class variable
    url = 'https://v1.api.com/example'  # keep this in mind for later

    def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None):
        threading.Thread.__init__(self, group=group, target=target, name=name, verbose=verbose)
        self.args = args

    def run(self):
        limit = self.args[0]

        for i in range(limit):
            response = requests.get(self.url)
            if response.status_code != 200:
                self.kill = True  # ends this loop on all Threads since it changing a class variable

            else:
                print('Thread {0} - success'.format(self.getName()))  # changed to self.getName()

            if self.kill:  # if kill is True, break the loop, send the email, and finish the Thread
                break

        print('process completed')
        # Send Email


number_of_threads = 5
number_of_requests = 100

if __name__ == '__main__':
    startTime = time.time()

    threads = []
    for i in range(number_of_threads):
        et = EppThread(name="{0}-Thread-{1}".format(name, i + 1), args=(number_of_requests))
        threads.append(et)
        et.start()

    # Check if execution time is not greater than 1 minute
    while threads and time.time() - startTime < 60:  # removed len() due to implicit Falsiness of empty containers in Python
        time.sleep(0.5)
        for thread in threads:
            if not thread.isAlive():
                threads.remove(thread)
                print('Thread {0} terminated'.format(thread.getName()))

    EppThread.kill = True

, - EppThreads , True, EppThread . EppThread.kill = True , , 1 .

, url. , URL- , . , , - EppThread kill url.

class EppThread2(EppThread):
    kill = False
    url = 'https://v2.example.com/api?$awesome=True'

EppThread2 threads, , .

+6

, , URL-. ​​, . . , , .

.

import logging, time, threading, requests

#: Log items
logging.basicConfig(format='%(asctime)s %(levelname)s : %(message)s', level=logging.INFO)

class EppThread(threading.Thread):
    def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None, bad_status=None):
        threading.Thread.__init__(self, group=group, target=target, name=name, verbose=verbose)
        self.args = args
        self.bad_status = bad_status

    def run(self):
        startTime = time.time()
        url = self.args[0]
        limit = self.args[1]

        for i in range(limit):
            if self.bad_status.is_set():
                # break the loop on errors in any thread.
                break
            response = requests.get(url)
            if response.status_code != 200:
                # Set the event when an error occurs
                self.bad_status.set()
                break
                #Exit other similar threads (with same url)
            else:
                print('Thread {0} - success'.format(thread.getName()))

         print('process completed')
         # Send Email


number_of_threads = 5
number_of_requests = 100

urls = ['https://v1.api.com/example', 'https://v2.api.com/example']

if __name__ == '__main__':
    startTime = time.time()

    threads = []
    for url in urls:
        # Create an event for each URL
        bad_status = threading.Event()
        for i in range(number_of_threads):
            et = EppThread(name = "{0}-Thread-{1}".format(name, i + 1), args=(url, number_of_requests), bad_status=bad_status)
            threads.append(et)
            et.start()

    # Check if execution time is not greater than 1 minute
    while len(threads) > 0 and (time.time() - startTime) < 60:
        time.sleep(0.5)
        for thread in threads:
            if not thread.isAlive():
                threads.remove(thread)
                print('Thread {0} terminated'.format(thread.getName()))

os._exit(1)

threading.Event , . , - , " ".

+5

Import sys

Here is an example:

import sys

list = []
if len(list) < 1:
     sys.exit("You don\'t have any items in your list")
+1
source

All Articles