X-Git-Url: http://xvm.mit.edu/gitweb/invirt/packages/invirt-base.git/blobdiff_plain/8bfea358c4a93a7c46efbefe0694036f38f390c4..e2cb1724053e67a4bb14b0b2c9d848e771d53a7e:/files/usr/share/python-support/sipb-xen-base/invirt/common.py diff --git a/files/usr/share/python-support/sipb-xen-base/invirt/common.py b/files/usr/share/python-support/sipb-xen-base/invirt/common.py index 250078e..77770a6 100644 --- a/files/usr/share/python-support/sipb-xen-base/invirt/common.py +++ b/files/usr/share/python-support/sipb-xen-base/invirt/common.py @@ -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):