Now that we're using Python 2.5, we can actually write with statements
[invirt/packages/invirt-base.git] / files / usr / share / python-support / sipb-xen-base / invirt / common.py
index 250078e..77770a6 100644 (file)
@@ -1,10 +1,15 @@
+from __future__ import with_statement
+
 import unittest
+from fcntl import flock, LOCK_EX, LOCK_SH, LOCK_UN
+import contextlib as clib
 
 class struct(object):
     'A simple namespace object.'
-    def __init__(self, d = {}):
+    def __init__(self, d = {}, **kwargs):
         'd is the dictionary to update my __dict__ with.'
         self.__dict__.update(d)
+        self.__dict__.update(kwargs)
 
 def dicts2struct(x):
     """
@@ -18,10 +23,22 @@ def dicts2struct(x):
     else:
         return x
 
-def wrap(rsrc, func):
-    "Utility to that emulates with Python 2.5's `with closing(rsrc)`."
-    try: return func(rsrc)
-    finally: rsrc.close()
+@clib.contextmanager
+def lock_file(path, exclusive = True):
+    with clib.closing(file(path, 'w')) as f:
+        if exclusive:
+            locktype = LOCK_EX
+        else:
+            locktype = LOCK_SH
+        flock(f, locktype)
+        try:
+            yield
+        finally:
+            flock(f, LOCK_UN)
+
+#
+# Tests.
+#
 
 class common_tests(unittest.TestCase):
     def test_dicts2structs(self):