ponty / PyVirtualDisplay

Python wrapper for Xvfb, Xephyr and Xvnc
BSD 2-Clause "Simplified" License
709 stars 78 forks source link

Make Display support the context manager protocol #1

Closed thobe closed 13 years ago

thobe commented 13 years ago

A common way to use pyvirtualdisplay is to start up a display, do some things with applications in that display, then stop it. It would be nice if the with statement could be used to control the lifecycle of the display in such scenarios. For example:

with Display(visible=0, size=(800, 600)):
    browser = webdriver.Firefox()
    browser.get('http://www.google.com')
    browser.save_screenshot('screenshot_of_google_in_firefox.png')
    browser.quit()

To support this, the Display class (or one of its super classes) would have to support the context manager protocol, the implementation would probably look something like this:

class AbstractDisplay(EasyProcess):
    # ... all existing code still remains as is, but this is added:
    def __enter__(self):
        self.start()
        return self
    def __exit__(self, *exc_info):
        self.stop()
ponty commented 13 years ago

I added your code to easyprocess, you should only update this module with easy_install.

Thanks for the contribution.

thobe commented 13 years ago

Yeah, I was wondering if that could have been a good place for it to go, but since I had not used easyprocess directly, only through pyvirtualdisplay, I didn't know if it would be useful there as well. From the examples you added in documentation and the test cases, it looks useful in that scenario.