I experimented with a couple things and ended up coming up with a solution based on the one linked through by learner8269. As noted in a comment on his post, on my system, Windows 10 / Current Geckodriver instances are not able to be distinguished from normal Firefox processes. As a result, I ended up wrapping the object creation with a try catch
statement & the following code:
from subprocess import check_output
from selenium import webdriver
import re
tasklist = check_output(["tasklist", "/fi", "imagename eq firefox.exe"], shell=True).decode()
currentFFIDs = re.findall(r"firefox.exe\s+(\d+)", tasklist)
try:
firefox = webdriver.Firefox()
except:
tasklist = check_output(["tasklist", "/fi", "imagename eq firefox.exe"], shell=True).decode()
firefoxIds = set(re.findall(r"firefox.exe\s+(\d+)", tasklist)).difference(currentFFIDs)
taskkill = 'taskkill /f '+''.join(["/pid "+f+" " for f in firefoxIds]).strip()
check_output(taskkill.split(), shell=True)
print("\nFirefox was force closed\n", flush=True)
What this does is:
- Get the current process IDs for running Firefox instances
- This is done via
subprocess
calling the tasklist
command in cmd
and using a regular expression to extract the process ID column
- Try and start the webdriver instance; if it succeeds, then good, otherwise run
tasklist
& get a new set of process IDs
- This will now potentially include IDs started by Selenium
- Convert the new IDs to a set & remove all the original IDs from it
- Call "taskkill" and provide any new Firefox IDs created after the first
tasklist
process; this will then terminate any headless Firefox instances.