[PATCH 1/4] Add a contextmanager to create and remove sparse tempfiles.

David Lehman dlehman at redhat.com
Wed Jul 23 21:04:25 UTC 2014


with sparsetmpfile("mytest", Size("100 MiB")) as path:
  do_stuff(fn=path)

It creates a sparse temporary file with the specified size and yields its
full path on __enter__, then unlinks the file on __exit__.
---
 blivet/util.py | 16 ++++++++++++++++
 1 file changed, 16 insertions(+)

diff --git a/blivet/util.py b/blivet/util.py
index 1e28ddc..a15bb4a 100644
--- a/blivet/util.py
+++ b/blivet/util.py
@@ -9,6 +9,7 @@ import re
 import sys
 import tempfile
 from decimal import Decimal
+from contextlib import contextmanager
 
 import six
 
@@ -402,6 +403,21 @@ def create_sparse_file(path, size):
     os.ftruncate(fd, size)
     os.close(fd)
 
+ at contextmanager
+def sparsetmpfile(name, size):
+    """ Context manager that creates a sparse tempfile and then unlinks it.
+
+        :param str name: suffix for filename
+        :param :class:`~.size.Size` size: the file size
+
+        Yields the path to the newly created file on __enter__.
+    """
+    path = create_sparse_tempfile(name, size)
+    try:
+        yield path
+    finally:
+        os.unlink(path)
+
 def variable_copy(obj, memo, omit=None, shallow=None, duplicate=None):
     """ A configurable copy function. Any attributes not specified in omit,
         shallow, or duplicate are copied using copy.deepcopy().
-- 
1.9.3



More information about the anaconda-patches mailing list