Added AtomicFile.

This commit is contained in:
Jeremy Fincher 2004-07-31 09:44:03 +00:00
parent fe8a8ee8fd
commit b2a94583f2

View File

@ -47,6 +47,7 @@ import sets
import time import time
import types import types
import random import random
import shutil
import socket import socket
import string import string
import sgmllib import sgmllib
@ -673,6 +674,20 @@ def mungeEmailForWeb(s):
def stackTrace(): def stackTrace():
traceback.print_stack(sys._getframe()) traceback.print_stack(sys._getframe())
class AtomicFile(file):
"""Used for files that need to be atomically written -- i.e., if there's a
failure, the original file remains, unmodified."""
def __init__(self, filename, flags='w'):
if flags not in ('a', 'w'):
raise ValueError, 'AtomicFile should only be used for writing.'
self.filename = filename
self.tempFilename = '%s.%s' % (filename, mktemp())
super(AtomicFile, self).__init__(self.tempFilename, flags)
def close(self):
super(AtomicFile, self).close()
shutil.move(self.tempFilename, self.filename)
if __name__ == '__main__': if __name__ == '__main__':
import sys, doctest import sys, doctest
doctest.testmod(sys.modules['__main__']) doctest.testmod(sys.modules['__main__'])