Kolay.Ne
Kolay.Ne

Reputation: 1398

How to quit a webbrowser session when Python is shutting down?

I'm writing a python code where I need selenium webbrowser inside one of my classes. I want a selenium session to finish correctly when exiting python

I save the webbrowser variable like a field of my class. To quit the session, I decided to call the quit() method of webbrowser inside the __del__() method of my class, but it didn't work:

from selenium import webdriver
from sys import stderr

class MyClass:
    def __init__(self):
        opts = webdriver.chrome.options.Options()
        opts.add_argument('--headless')
        opts.add_argument('--no-sandbox')
        opts.add_argument('--disable-dev-shm-usage')
        assert opts.headless
        self.browser = webdriver.Chrome(options=opts)

    def __del__(self):
        self.browser.quit()
        stderr.write("Browser has been closed correctly!\n")

    # Other methods of my class

if __name__ == "__main__":
    a = MyClass()

If now I call something like del a, I get the Browser has been closed correctly! message and chromedriver disappears from the list of running processes. But if I exit python, I get the error message:

Exception ignored in: <bound method MyClass.__del__ of <__main__.MyClass object at 0x7f37eb918898>>
Traceback (most recent call last):
  File "<stdin>", line 11, in __del__
  File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/chrome/webdriver.py", line 158, in quit
  File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/common/service.py", line 151, in stop
  File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/common/service.py", line 122, in send_remote_shutdown_command
ImportError: sys.meta_path is None, Python is likely shutting down

Upvotes: 0

Views: 548

Answers (1)

Brad Solomon
Brad Solomon

Reputation: 40888

A couple of other options:

  • Implement MyClass as a context manager. In its __exit__ method, quit the browser. Then use with MyClass() as mc..., wherein __exit__ will be called after the block wraps up
  • Use atexit (I would call this overkill) - register instances of MyClass to the module's scope; register an exit function that calls obj.browser.quit() for each registered instance on program exit.

Upvotes: 1

Related Questions