Python selenium CTRL+C closes chromedriver

2.6k views Asked by At

How can I catch CTRL+C (a KeyboardInterrupt) without causing the chromedriver to close. It closes the chromedriver when I run my script.py through cmd.

driver = webdriver.Chrome()
try:
    while True:
        #do stuff with chromedriver
except KeyboardInterrupt:
    print "User pressed CTRL + C"
    #do other stuff with chromedriver

It does catch the KeyboardInterrupt in my script, thus my script continues but the chromedriver also gets it and close itself.

EDIT 1:
The solution here doesn't work when you run the script through CMD or when you freeze the script with Pyinstaller and run it (IOError: [Errno 4] Interrupted function call)

EDIT 2:
I also tried by making the script ignore the Errno 4 (using try and except Exception) but still has the same result (chromedriver closes) so in short, this solution does not help at all.

3

There are 3 answers

2
Krmit On

You can also just disable SIGINT handling while starting the driver. Like so:

import signal 

...

ps = signal.getsignal(signal.SIGINT) # backup signal handler 
signal.signal(signal.SIGINT, signal.SIG_IGN) # ignore signal temporarily

... = webdriver.Chrome(...) 

signal.signal(signal.SIGINT, ps) # restore original handler
0
Ned Konz On

I just tried @Krmit 's answer, with Selenium 4.8.2, python 3.11, and Geckodriver and it worked fine for what I wanted (to be able to cancel a sleep).

    options=Options()
    # options.profile = FirefoxProfile()
    ps = signal.getsignal(signal.SIGINT)
    signal.signal(signal.SIGINT, signal.SIG_IGN)
    driver = webdriver.Firefox(service=FirefoxService(GeckoDriverManager().install()), options=options)
    signal.signal(signal.SIGINT, ps)
3
smudi On

Consider using the webdriver.Remote flavor. This option does not spawn a local version of the webdriver inside the interpreter, which should free you from the SIGINT hassle.

Initiate the webdriver in another shell - (chromedriver for Chrome, geckodriver for Firefox, etc.) Take note of the listening port. I will use the defaults here: 9515 for chromedriver and 4444 for geckodriver.

In your python script:

Chrome:

driver=webdriver.Remote("http://127.0.0.1:9515",desired_capabilities=webdriver.DesiredCapabilities.CHROME)

Firerox:

driver=webdriver.Remote("http://127.0.0.1:4444",desired_capabilities=webdriver.DesiredCapabilities.FIREFOX)