[PATCH python 5/5] Allow virConnect to be used as a context manager

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



From: Marc Hartmayer <mhartmay@xxxxxxxxxxxxxxxxxx>

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 <mhartmay@xxxxxxxxxxxxxxxxxx>
Reviewed-by: Bjoern Walk <bwalk@xxxxxxxxxxxxxxxxxx>
Reviewed-by: Boris Fiuczynski <fiuczy@xxxxxxxxxxxxxxxxxx>
---
 libvirt-override-virConnect.py | 6 ++++++
 1 file changed, 6 insertions(+)

diff --git a/libvirt-override-virConnect.py b/libvirt-override-virConnect.py
index f26e65a99ee1..a24eae72d6d6 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 """
-- 
2.13.4

--
libvir-list mailing list
libvir-list@xxxxxxxxxx
https://www.redhat.com/mailman/listinfo/libvir-list



[Index of Archives]     [Virt Tools]     [Libvirt Users]     [Lib OS Info]     [Fedora Users]     [Fedora Desktop]     [Fedora SELinux]     [Big List of Linux Books]     [Yosemite News]     [KDE Users]     [Fedora Tools]

  Powered by Linux