Closing Selenium Browser that was Opened in a Child Process
<p>Here's the situation:</p>

<p>I create a child process which opens and deals with a webdriver.  The child process is finicky and might error, in which case it would close immediately, and control would be returned to the main function.  In this situation, however, the browser would still be open (as the child process never completely finished running).  How can I close a browser that is initialized in a child process?</p>

<p>Approaches I've tried so far:</p>

<p>1) Initializing the webdriver in the main function and passing it to the child process as an argument.</p>

<p>2) Passing the webdriver between the child and parent process using a queue.</p>

<p>The code:</p>

<pre><code>import multiprocessing

def foo(queue):
    driver = webdriver.Chrome()
    queue.put(driver)
    # Do some other stuff

    # If finicky stuff happens, this driver.close() will not run
    driver.close()

if __name__ == '__main__':

    queue = multiprocessing.Queue()
    p = multiprocessing.Process(target=foo, name='foo', args=(queue,))

    # Wait for process to finish

    # Try to close the browser if still open
    try:
        driver = queue.get()
        driver.close()
    except:
         pass
</code></pre>

<p>I found a solution:</p>

<p>In foo(), get the process ID of the webdriver when you open a new browser.  Add the process ID to the queue.  Then in the main function, add time.sleep(60) to wait for a minute, then get the process ID from the queue and use a try-except to try and close the particular process ID.</p>

<p>If foo() running in a separate process hangs, then the browser will be closed in the main function after one minute. </p>

python selenium webdriver queue multiprocessing