Permalink
Browse files

Add ability to remove mmstats files

  • Loading branch information...
schmichael committed Sep 29, 2011
1 parent f4c223e commit e4b21878e9451e1bf824d642d3b762efde48484a
Showing with 32 additions and 0 deletions.
  1. +16 −0 mmstats.py
  2. +16 −0 tests/test_mmap.py
View
@@ -331,6 +331,9 @@ class BaseMmStats(object):
"""Stats models should inherit from this"""
def __init__(self, filename=None, label_prefix=None):
"""\
Optionally given a filename or label_prefix, create an MmStats instance
"""
# Setup label prefix
self._label_prefix = '' if label_prefix is None else label_prefix
@@ -380,6 +383,19 @@ def label_prefix(self):
def size(self):
return self._mmap.size()
def flush(self):
"""Flush mmapped file to disk"""
#TODO Handle Windows return values:
# http://docs.python.org/library/mmap#mmap.flush
self._mmap.flush()
def remove(self):
"""Close and remove mmap file - No further stats updates will work"""
self.flush()
self._mmap.close()
os.remove(self.filename)
# Remove fields to prevent segfaults
self._fields = {}
class MmStats(BaseMmStats):
pid = StaticUIntField(label="sys.pid", value=os.getpid)
View
@@ -51,3 +51,19 @@ def test_truncate(self):
reopened_file = open(fn)
self.assertEqual(reopened_file.read(1), 'X')
self.assertEqual(reopened_file.read(1), '\x00')
def test_remove(self):
"""Calling remove() on an MmStat instance should remove the file"""
class TestStat(mmstats.MmStats):
b = mmstats.BoolField()
fn = os.path.join(self.path, 'mmstats-test_remove')
ts = TestStat(filename=fn)
ts.b = True
self.assertTrue(ts.b)
self.assertTrue(os.path.exists(fn))
ts.remove()
self.assertFalse(os.path.exists(fn))
# Trying to access the mmap after it's been removed should raise an
# exception but *not* segault
self.assertRaises(Exception, getattr, ts, 'b')

0 comments on commit e4b2187

Please sign in to comment.