From d23f8bc3a3530bd3df6c21ff288d5b3b28d1f219 Mon Sep 17 00:00:00 2001 From: Marc Hartmayer Date: Wed, 16 May 2018 10:24:36 +0200 Subject: Allow virConnect to be used as a context manager The libvirt python bindings are now more 'pythonic' as virConnect can now be used as a context manager. For example, it's possible to write the following code: with libvirt.open() as conn: # do something with the connection... print(conn.listAllDomains()) At the end of this with-block the connection will be closed automatically. Signed-off-by: Marc Hartmayer Reviewed-by: Bjoern Walk Reviewed-by: Boris Fiuczynski --- libvirt-override-virConnect.py | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'libvirt-override-virConnect.py') diff --git a/libvirt-override-virConnect.py b/libvirt-override-virConnect.py index f26e65a..a24eae7 100644 --- a/libvirt-override-virConnect.py +++ b/libvirt-override-virConnect.py @@ -11,6 +11,12 @@ libvirtmod.virConnectClose(self._o) self._o = None + def __enter__(self): + return self + + def __exit__(self, exc_type_, exc_value_, traceback_): + self.close() + def domainEventDeregister(self, cb): """Removes a Domain Event Callback. De-registering for a domain callback will disable delivery of this event type """ -- cgit v1.2.1