File: SafeWriteFile.py

package info (click to toggle)
mini-dinstall 0.7.3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 300 kB
  • sloc: python: 2,027; sh: 33; makefile: 8
file content (77 lines) | stat: -rwxr-xr-x 2,326 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/usr/bin/python3
# SafeWriteFile -*- mode: python; coding: utf-8 -*-
#
# This file is a writable file object.  It writes to a specified newname,
# and when closed, renames the file to the realname.  If the object is
# deleted, without being closed, this rename isn't done.  If abort() is
# called, it also disables the rename.
#
# Copyright (c) 2001 Adam Heath <doogie@debian.org>
#
# This file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

from shutil import copy2
from os import rename

class ObjectNotAllowed(Exception):
    pass

class InvalidMode(Exception):
    pass

class SafeWriteFile:
    def __init__(self, newname, realname, mode="w", bufsize=-1):

        if not isinstance(newname, str):
            raise ObjectNotAllowed(newname)
        if not isinstance(realname, str):
            raise ObjectNotAllowed(realname)

        if "r" in mode:
            raise InvalidMode(mode)
        if "a" in mode or "+" in mode:
            copy2(realname, newname)
        self.fobj=open(newname, mode, bufsize)
        self.newname=newname
        self.realname=realname
        self.__abort=False

    def close(self):
        self.fobj.close()
        if not (self.closed and self.__abort):
            rename(self.newname, self.realname)

    def abort(self):
        self.__abort=True

    def __del__(self):
        self.abort()
        del self.fobj

    def __getattr__(self, attr):
        try:
            return self.__dict__[attr]
        except:
            return eval("self.fobj." + attr)

if __name__ == "__main__":
    import time
    f=SafeWriteFile("sf.new", "sf.data")
    f.write("test\n")
    f.flush()
    time.sleep(1)
    f.close()

# vim:ts=4:sw=4:et: