A Python program drives Firefox via Selenium WebDriver. The code is embedded in a try
/except
block like this:
session = selenium.webdriver.Firefox(firefox_profile)
try:
# do stuff
except (Exception, KeyboardInterrupt) as exception:
logging.info("Caught exception.")
traceback.print_exc(file=sys.stdout)
If the program aborts because of an error, the WebDriver session is not closed and hence the Firefox window is left open. But if the program aborts with a KeyboardInterrupt
exception, the Firefox window gets closed (I suppose because the WebDriver sessions are released, too) and I would like to avoid this.
I know that both exceptions go through the same handler because I see the "Caught exception"
message in both cases.
How could I avoid the closing of the Firefox window with KeyboardInterrupt
?
I was inspired by @User9123's answer, and have cleaned it up a bit:
I've only tried this on Ubuntu so far, but it does exactly what I wanted!