19
from warnings import warn
20
from osutils import rename
22
class AtomicFile(object):
23
20
"""A file that does an atomic-rename to move into place.
25
22
This also causes hardlinks to break when it's written out.
27
24
Open this as for a regular file, then use commit() to move into
28
25
place or abort() to cancel.
30
An encoding can be specified; otherwise the default is ascii.
27
You may wish to wrap this in a codecs.EncodedFile to do unicode
33
def __init__(self, filename, mode='wb', encoding=None):
31
def __init__(self, filename, mode='wb'):
34
32
if mode != 'wb' and mode != 'wt':
35
33
raise ValueError("invalid AtomicFile mode %r" % mode)
38
self.tmpfilename = '%s.%d.%s.tmp' % (filename, os.getpid(),
36
self.tmpfilename = '%s.tmp.%d.%s' % (filename, os.getpid(),
39
37
socket.gethostname())
40
38
self.realfilename = filename
44
self.f = codecs.open(self.tmpfilename, mode, encoding)
46
self.f = open(self.tmpfilename, mode)
40
self.f = open(self.tmpfilename, mode)
48
41
self.write = self.f.write
53
return '%s(%r)' % (self.__class__.__name__,
42
self.closed = property(f.closed)
58
"""Close the file and move to final name."""
62
raise Exception('%r is already closed' % self)
68
rename(self.tmpfilename, self.realfilename)
48
if sys.platform == 'win32':
49
os.remove(self.realfilename)
50
os.rename(self.tmpfilename, self.realfilename)
72
"""Discard temporary file without committing changes."""
76
raise Exception('%r is already closed' % self)
81
55
os.remove(self.tmpfilename)
85
"""Discard the file unless already committed."""
91
if hasattr(self, 'closed') and not self.closed:
92
warn("%r leaked" % self)