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've got a solution, but it's pretty ugly.
When Ctrl+C is pressed, python receives a Interrupt Signal (SIGINT), which is propagated throughout your process tree. Python also generates a KeyboardInterrupt, so you can try to handle something that is bound to the logic of your process, but logic that is coupled to child processes cannot be influenced.
To influence which signals are passed on to your child processes, you'd have to specify how signals should be handled, before the process is spawned through
subprocess.Popen.There are various options, this one is taken from another answer:
Problem is, you're not the one calling
Popen, that is delegated to selenium. There are various discussions on SO. From what I've gathered other solutions that try to influence signal masking are prone to failure when the masking is not executed right before the call toPopen.Also keep in mind, there is a big fat warning regarding the use of preexec_fn in the python documentation, so use that at your own discretion.
"Luckily" python allows to override functions at runtime, so we could do this:
with monkey.py as follows:
the code for start is from selenium, with the added line as highlighted. It's a crude hack, it might as well bite you. Good luck :D