2

I have a simple script that runs on Selenium. I made an .exe file out of it and it works perfectly fine but there is one problem I have noticed. The .exe opens a console as intended but if I manually close the console while the script is running, it leaves firefox.exe opened in Processes tab.

zombie processes after manually closing .exe

My question is: how do I make Python close these processes in case if the script's execution has been interrupted manually?

I'm guessing I need to catch the exception, but what exception does Python throw in case if we manually stop the program?

zealous
  • 6,861
  • 3
  • 10
  • 30

2 Answers2

0

Ideally, invoking quit() deletes the current instance of WebDriver variant and the current Browsing Context.

However, if you are manually interupting the script's execution by closing the console, the Browsing Context gets closed visually but numerous browser processes would still continue to consume CPU and memory


Solution

In those cases, you have to explicitly kill the Browser process and the WebDriver instances using either of the following solutions:

  • Java Solution(Windows):

    import java.io.IOException;
    
    public class Kill_ChromeDriver_GeckoDriver_IEDriverserver 
    {
        public static void main(String[] args) throws Exception 
        {
            Runtime.getRuntime().exec("taskkill /F /IM geckodriver.exe /T");
            Runtime.getRuntime().exec("taskkill /F /IM chromedriver.exe /T");
            Runtime.getRuntime().exec("taskkill /F /IM IEDriverServer.exe /T");
        }
    }
    
  • Python Solution (Windows):

    import os
    os.system("taskkill /f /im geckodriver.exe /T")
    os.system("taskkill /f /im chromedriver.exe /T")
    os.system("taskkill /f /im IEDriverServer.exe /T")
    
  • Python Solution(Cross Platform):

    import os
    import psutil
    
    PROCNAME = "geckodriver" # or chromedriver or IEDriverServer
    for proc in psutil.process_iter():
        # check whether the process name matches
        if proc.name() == PROCNAME:
            proc.kill()
    

References

You can find a couple of detailed discussions in:

DebanjanB
  • 118,661
  • 30
  • 168
  • 217
0

You could use atexit module to quit the webdriver automatically before the script stopped.

import atexit
from selenium import webdriver

def exit_handler(): # when exit, execute this function
    driver.quit()

atexit.register(exit_handler)

driver = webdriver.Firefox() 
# Your work
jizhihaoSAMA
  • 10,685
  • 9
  • 18
  • 36