Safe way to exit infinite loop into thread pool for Python3

I am using Python3 modules:

  • requestsfor HTTP GET calls to several partial photons that are configured as simple HTTP servers

  • As a client, I use Raspberry Pi (which is also an access point) as an HTTP Client , which uses HTTP GET resquests for the above photons multiprocessing.dummy.Poolto create

The polling procedure is as follows:

def pollURL(url_of_photon):
    """
    pollURL: Obtain the IP Address and create a URL for HTTP GET Request
    @param: url_of_photon: IP address of the Photon connected to A.P.
    """
    create_request = 'http://' + url_of_photon + ':80'
    while True:
        try:
            time.sleep(0.1) # poll every 100ms
            response = requests.get(create_request)
            if response.status_code == 200:
                # if success then dump the data into a temp dump file
                with open('temp_data_dump', 'a+') as jFile:
                    json.dump(response.json(), jFile)
            else:
               # Currently just break
               break
        except KeyboardInterrupt as e:
            print('KeyboardInterrupt detected ', e)
            break

Values url_of_photonare simple IPv4 addresses obtained from a file dnsmasq.leasesavailable on the Pi.

Function main():

def main():
    # obtain the IP and MAC addresses from the Lease file
    IP_addresses = []
    MAC_addresses = []
    with open('/var/lib/misc/dnsmasq.leases', 'r') as leases_file:
        # split lines and words to obtain the useful stuff.
        for lines in leases_file:
            fields = lines.strip().split()
            # use logging in future
            print('Photon with MAC: %s has IP address: %s' %(fields[1],fields[2]))
            IP_addresses.append(fields[2])
            MAC_addresses.append(fields[1])

            # Create Thread Pool
            pool = ThreadPool(len(IP_addresses))
            results = pool.map(pollURL, IP_addresses)
            pool.close()
            pool.join()

if __name__ == '__main__':
    main()

Problem

, CTRL + C, . , - CTRL + \

pollURL , .. poll.join(), ?

KeyboardInterrupt . , CTRL + \.

+4
1

pollURL . Python . SIGINT KeyboardInterrupt .

:

Python Python, . , . .

, .

().

event = threading.Event()

def looping_function( ... ):
    while event.is_set():
        do_your_stuff()

def main():
    try:
        event.set()
        pool = ThreadPool()
        pool.map( ... )
    except KeyboardInterrupt:
        event.clear()
    finally:
        pool.close()
        pool.join()
+1

Source: https://habr.com/ru/post/1685466/


All Articles