driver.quit() after unhandled exception

Question:

I have a Python script that I’m using to keep another Python script running on a loop.

I basically call it like this python loop.py script.py

The script.py uses selenium and chromedriver to perform whatever it needs to do, I’m trying to keep this script running 24/7, so whenever it fails, the loop script just restarts it and opens another instance of the chromedriver, opening another chrome window.

My problem is that whenever I keep this script running for several hours, there’s a point where I have too many chrome windows opened, causing the computer to go crazy slow as you would expect.

script.py is divided into multiple functions, with one function calling some of the other functions like:

def caller_function():
  function1()
  function2()
  function3()
  function4()

I already have some of the exceptions handled so basically the scripts only stops whenever an unhandled exception occurs.

This unhandled exception can happen in any of the functions so I can’t seem to find a way around handling(?) the unhandled exception to make it do a driver.quit() so it closes the instance that failed before the loop.py calls script.py again and opens another chrome window.

I tried doing:

def caller_function():
 try:
   function1()
   function2()
   function3()
   function4()
 except:
   driver.quit()

But it didn’t work, as for some reason the driver.quit() fell into a loop and stopped loop.py from restarting script.py

Basically, I’m trying not to have 20+ chrome windows open whenever I wake up in the morning to check the progress of the script. Does anyone know a way around this?

Asked By: rekeson21

||

Answers:

use finally for that purpose:

 try:
   # your code

 finally:
   driver.quit()
Answered By: Vova