2 Futz with files like a pro.
5 import sys, exceptions, os, stat, tempfile, time, binascii
7 from twisted.python import log
9 from pycryptopp.cipher.aes import AES
12 def rename(src, dst, tries=4, basedelay=0.1):
13 """ Here is a superkludge to workaround the fact that occasionally on
14 Windows some other process (e.g. an anti-virus scanner, a local search
15 engine, etc.) is looking at your file when you want to delete or move it,
16 and hence you can't. The horrible workaround is to sit and spin, trying
17 to delete it, for a short time and then give up.
19 With the default values of tries and basedelay this can block for less
22 @param tries: number of tries -- each time after the first we wait twice
23 as long as the previous wait
24 @param basedelay: how long to wait before the second try
26 for i in range(tries-1):
28 return os.rename(src, dst)
29 except EnvironmentError, le:
30 # XXX Tighten this to check if this is a permission denied error (possibly due to another Windows process having the file open and execute the superkludge only in this case.
31 log.msg("XXX KLUDGE Attempting to move file %s => %s; got %s; sleeping %s seconds" % (src, dst, le, basedelay,))
34 return os.rename(src, dst) # The last try.
36 def remove(f, tries=4, basedelay=0.1):
37 """ Here is a superkludge to workaround the fact that occasionally on
38 Windows some other process (e.g. an anti-virus scanner, a local search
39 engine, etc.) is looking at your file when you want to delete or move it,
40 and hence you can't. The horrible workaround is to sit and spin, trying
41 to delete it, for a short time and then give up.
43 With the default values of tries and basedelay this can block for less
46 @param tries: number of tries -- each time after the first we wait twice
47 as long as the previous wait
48 @param basedelay: how long to wait before the second try
51 os.chmod(f, stat.S_IWRITE | stat.S_IEXEC | stat.S_IREAD)
54 for i in range(tries-1):
57 except EnvironmentError, le:
58 # XXX Tighten this to check if this is a permission denied error (possibly due to another Windows process having the file open and execute the superkludge only in this case.
59 if not os.path.exists(f):
61 log.msg("XXX KLUDGE Attempting to remove file %s; got %s; sleeping %s seconds" % (f, le, basedelay,))
64 return os.remove(f) # The last try.
66 class ReopenableNamedTemporaryFile:
68 This uses tempfile.mkstemp() to generate a secure temp file. It then closes
69 the file, leaving a zero-length file as a placeholder. You can get the
70 filename with ReopenableNamedTemporaryFile.name. When the
71 ReopenableNamedTemporaryFile instance is garbage collected or its shutdown()
72 method is called, it deletes the file.
74 def __init__(self, *args, **kwargs):
75 fd, self.name = tempfile.mkstemp(*args, **kwargs)
79 return "<%s instance at %x %s>" % (self.__class__.__name__, id(self), self.name)
82 return self.__repr__()
90 class NamedTemporaryDirectory:
92 This calls tempfile.mkdtemp(), stores the name of the dir in
93 self.name, and rmrf's the dir when it gets garbage collected or
96 def __init__(self, cleanup=True, *args, **kwargs):
97 """ If cleanup, then the directory will be rmrf'ed when the object is shutdown. """
98 self.cleanup = cleanup
99 self.name = tempfile.mkdtemp(*args, **kwargs)
102 return "<%s instance at %x %s>" % (self.__class__.__name__, id(self), self.name)
105 return self.__repr__()
112 traceback.print_exc()
115 if self.cleanup and hasattr(self, 'name'):
118 class EncryptedTemporaryFile:
119 # not implemented: next, readline, readlines, xreadlines, writelines
122 self.file = tempfile.TemporaryFile()
123 self.key = os.urandom(16) # AES-128
125 def _crypt(self, offset, data):
126 offset_big = offset // 16
127 offset_small = offset % 16
128 iv = binascii.unhexlify("%032x" % offset_big)
129 cipher = AES(self.key, iv=iv)
130 cipher.process("\x00"*offset_small)
131 return cipher.process(data)
139 def seek(self, offset, whence=0): # 0 = SEEK_SET
140 self.file.seek(offset, whence)
143 offset = self.file.tell()
146 def read(self, size=-1):
147 index = self.file.tell()
148 ciphertext = self.file.read(size)
149 plaintext = self._crypt(index, ciphertext)
152 def write(self, plaintext):
153 index = self.file.tell()
154 ciphertext = self._crypt(index, plaintext)
155 self.file.write(ciphertext)
157 def truncate(self, newsize):
158 self.file.truncate(newsize)
161 def make_dirs(dirname, mode=0777):
163 An idempotent version of os.makedirs(). If the dir already exists, do
164 nothing and return without raising an exception. If this call creates the
165 dir, return without raising an exception. If there is an error that
166 prevents creation or if the directory gets deleted after make_dirs() creates
167 it and before make_dirs() checks that it exists, raise an exception.
171 os.makedirs(dirname, mode)
175 if not os.path.isdir(dirname):
178 raise exceptions.IOError, "unknown error prevented creation of directory, or deleted the directory immediately after creation: %s" % dirname # careful not to construct an IOError with a 2-tuple, as that has a special meaning...
182 A threadsafe and idempotent version of shutil.rmtree(). If the dir is
183 already gone, do nothing and return without raising an exception. If this
184 call removes the dir, return without raising an exception. If there is an
185 error that prevents deletion or if the directory gets created again after
186 rm_dir() deletes it and before rm_dir() checks that it is gone, raise an
191 os.chmod(dirname, stat.S_IWRITE | stat.S_IEXEC | stat.S_IREAD)
192 for f in os.listdir(dirname):
193 fullname = os.path.join(dirname, f)
194 if os.path.isdir(fullname):
199 except Exception, le:
200 # Ignore "No such file or directory"
201 if (not isinstance(le, OSError)) or le.args[0] != 2:
204 # Okay, now we've recursively removed everything, ignoring any "No
205 # such file or directory" errors, and collecting any other errors.
207 if os.path.exists(dirname):
211 raise OSError, "Failed to remove dir for unknown reason."
215 def remove_if_possible(f):
221 def open_or_create(fname, binarymode=True):
223 return open(fname, binarymode and "r+b" or "r+")
224 except EnvironmentError:
225 return open(fname, binarymode and "w+b" or "w+")
230 for root, dirs, files in os.walk(basedir):
232 fn = os.path.join(root, f)
233 size += os.path.getsize(fn)
237 def move_into_place(source, dest):
238 """Atomically replace a file, or as near to it as the platform allows.
239 The dest file may or may not exist."""
240 if "win32" in sys.platform.lower():
241 remove_if_possible(dest)
242 os.rename(source, dest)
244 def write(path, data):
245 wf = open(path, "wb")
252 rf = open(path, "rb")
258 def put_file(pathname, inf):
259 # TODO: create temporary file and move into place?
260 outf = open(os.path.expanduser(pathname), "wb")
263 data = inf.read(32768)