Ignore:
Timestamp:
Oct 24, 2008, 3:35:21 AM (16 years ago)
Author:
broder
Message:

Now that we're using Python 2.5, we can actually write with statements

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/packages/sipb-xen-base/files/usr/share/python-support/sipb-xen-base/invirt/common.py

    r795 r1197  
     1from __future__ import with_statement
     2
    13import unittest
    24from fcntl import flock, LOCK_EX, LOCK_SH, LOCK_UN
     5import contextlib as clib
    36
    47class struct(object):
     
    2124        return x
    2225
    23 #
    24 # Hacks to work around lack of Python 2.5's `with` statement.
    25 #
    26 
    27 def with_closing(rsrc):
    28     """
    29     Utility to emulate Python 2.5's `with closing(rsrc)` context manager.
    30 
    31     E.g.,
    32     @with_closing(file('/tmp/foo'))
    33     def contents(f):
    34         return f.read()
    35     # now 'contents' is the contents of /tmp/foo
    36     """
    37     def wrapper(func):
    38         try: return func(rsrc)
    39         finally: rsrc.close()
    40     return wrapper
    41 
    42 def with_lock_file(path, exclusive = True):
    43     """
    44     Context manager for lock files.  Example:
    45 
    46     @with_lock_file('/tmp/mylock')
    47     def input():
    48         print 'locked'
    49         return raw_input()
    50     # prints 'locked'
    51     print input # prints what raw_input() returned
    52     """
    53     def wrapper(func):
    54         @with_closing(file(path, 'w'))
    55         def g(f):
    56             if exclusive: locktype = LOCK_EX
    57             else:         locktype = LOCK_SH
    58             flock(f, locktype)
    59             try: return func()
    60             finally: flock(f, LOCK_UN)
    61         return g
    62     return wrapper
     26@clib.contextmanager
     27def lock_file(path, exclusive = True):
     28    with clib.closing(file(path, 'w')) as f:
     29        if exclusive:
     30            locktype = LOCK_EX
     31        else:
     32            locktype = LOCK_SH
     33        flock(f, locktype)
     34        try:
     35            yield
     36        finally:
     37            flock(f, LOCK_UN)
    6338
    6439#
Note: See TracChangeset for help on using the changeset viewer.