Doing something before program exit in Python

Viewed 88

Good evening, after several hours looking for a solution, I still can't find any way to solve this :

I'm currently working on a Selenium script that creates X threads, each thread run a Firefox instance that makes test on a website. The thing is, when I'm using Ctrl C or leaving the executable with the cross at top-right, every Mozilla instances created keep living.

I assumed this is caused by the fact that sub-threads created in the main thread are not stopped due to these processes that are still running so I decided to make a function that takes a list of drivers will close EVERY drivers in the list, and these drivers are added to the list when they are created.

The issue happens when I'm running it as an executable, the "Stop" function for my IDE (PyCharm) has no issue with it.

What I've tried :

  • using atexit module to shutdown every drivers (Firefox instances) on exit with a clean_threads function -> It doesn't work because it looks like atexit is running once every threads are shutdown, so in my case, the function was never called

  • Running my main function in a "try - finally" structure with the clean_threads function called in the finally -> doesn't work as well, I might have used it the wrong way but it did not worked as well.

  • Running my main function in a "try - except (KeyboardInterrupt, SystemExit)", didn't managed to make it work aswell, for some unknown reason it just made Ctrl C being not able to

I'd love to have some advice on the procedure to follow, I admit going in circles and not finding a solution to the problem..

Any help will be appreciated, thanks in advance :) And if there is a need for more clarification, snippets or whatever, please do not hesitate.

Code of my main function :

def main():
    global THREADS
    load_settings()
    try :
        # TODO clean firefox instances
        # TODO proper switch
        THREADS = [Thread(target=automation, args=(i, HEADLESS)) for i in
                   range(FIRST_ACC, ACCOUNT_NUMBER + FIRST_ACC, 1)]
        for thread in THREADS:
            thread.start()
            time.sleep(30)

        for thread in THREADS:
            thread.join()

    except (KeyboardInterrupt, SystemExit):
        print("Exception catchée")
        clean_threads(DRIVER_LIST)

The clean_threads function :

def clean_threads(driver_list):
    discard_list = []
    print("Test")
    for each in driver_list:
        each.exit()
        discard_list.append(each)
    print(len(discard_list))

0 Answers
Related