1 | n/a | """Temporary files. |
---|
2 | n/a | |
---|
3 | n/a | This module provides generic, low- and high-level interfaces for |
---|
4 | n/a | creating temporary files and directories. All of the interfaces |
---|
5 | n/a | provided by this module can be used without fear of race conditions |
---|
6 | n/a | except for 'mktemp'. 'mktemp' is subject to race conditions and |
---|
7 | n/a | should not be used; it is provided for backward compatibility only. |
---|
8 | n/a | |
---|
9 | n/a | The default path names are returned as str. If you supply bytes as |
---|
10 | n/a | input, all return values will be in bytes. Ex: |
---|
11 | n/a | |
---|
12 | n/a | >>> tempfile.mkstemp() |
---|
13 | n/a | (4, '/tmp/tmptpu9nin8') |
---|
14 | n/a | >>> tempfile.mkdtemp(suffix=b'') |
---|
15 | n/a | b'/tmp/tmppbi8f0hy' |
---|
16 | n/a | |
---|
17 | n/a | This module also provides some data items to the user: |
---|
18 | n/a | |
---|
19 | n/a | TMP_MAX - maximum number of names that will be tried before |
---|
20 | n/a | giving up. |
---|
21 | n/a | tempdir - If this is set to a string before the first use of |
---|
22 | n/a | any routine from this module, it will be considered as |
---|
23 | n/a | another candidate location to store temporary files. |
---|
24 | n/a | """ |
---|
25 | n/a | |
---|
26 | n/a | __all__ = [ |
---|
27 | n/a | "NamedTemporaryFile", "TemporaryFile", # high level safe interfaces |
---|
28 | n/a | "SpooledTemporaryFile", "TemporaryDirectory", |
---|
29 | n/a | "mkstemp", "mkdtemp", # low level safe interfaces |
---|
30 | n/a | "mktemp", # deprecated unsafe interface |
---|
31 | n/a | "TMP_MAX", "gettempprefix", # constants |
---|
32 | n/a | "tempdir", "gettempdir", |
---|
33 | n/a | "gettempprefixb", "gettempdirb", |
---|
34 | n/a | ] |
---|
35 | n/a | |
---|
36 | n/a | |
---|
37 | n/a | # Imports. |
---|
38 | n/a | |
---|
39 | n/a | import functools as _functools |
---|
40 | n/a | import warnings as _warnings |
---|
41 | n/a | import io as _io |
---|
42 | n/a | import os as _os |
---|
43 | n/a | import shutil as _shutil |
---|
44 | n/a | import errno as _errno |
---|
45 | n/a | from random import Random as _Random |
---|
46 | n/a | import weakref as _weakref |
---|
47 | n/a | |
---|
48 | n/a | try: |
---|
49 | n/a | import _thread |
---|
50 | n/a | except ImportError: |
---|
51 | n/a | import _dummy_thread as _thread |
---|
52 | n/a | _allocate_lock = _thread.allocate_lock |
---|
53 | n/a | |
---|
54 | n/a | _text_openflags = _os.O_RDWR | _os.O_CREAT | _os.O_EXCL |
---|
55 | n/a | if hasattr(_os, 'O_NOFOLLOW'): |
---|
56 | n/a | _text_openflags |= _os.O_NOFOLLOW |
---|
57 | n/a | |
---|
58 | n/a | _bin_openflags = _text_openflags |
---|
59 | n/a | if hasattr(_os, 'O_BINARY'): |
---|
60 | n/a | _bin_openflags |= _os.O_BINARY |
---|
61 | n/a | |
---|
62 | n/a | if hasattr(_os, 'TMP_MAX'): |
---|
63 | n/a | TMP_MAX = _os.TMP_MAX |
---|
64 | n/a | else: |
---|
65 | n/a | TMP_MAX = 10000 |
---|
66 | n/a | |
---|
67 | n/a | # This variable _was_ unused for legacy reasons, see issue 10354. |
---|
68 | n/a | # But as of 3.5 we actually use it at runtime so changing it would |
---|
69 | n/a | # have a possibly desirable side effect... But we do not want to support |
---|
70 | n/a | # that as an API. It is undocumented on purpose. Do not depend on this. |
---|
71 | n/a | template = "tmp" |
---|
72 | n/a | |
---|
73 | n/a | # Internal routines. |
---|
74 | n/a | |
---|
75 | n/a | _once_lock = _allocate_lock() |
---|
76 | n/a | |
---|
77 | n/a | if hasattr(_os, "lstat"): |
---|
78 | n/a | _stat = _os.lstat |
---|
79 | n/a | elif hasattr(_os, "stat"): |
---|
80 | n/a | _stat = _os.stat |
---|
81 | n/a | else: |
---|
82 | n/a | # Fallback. All we need is something that raises OSError if the |
---|
83 | n/a | # file doesn't exist. |
---|
84 | n/a | def _stat(fn): |
---|
85 | n/a | fd = _os.open(fn, _os.O_RDONLY) |
---|
86 | n/a | _os.close(fd) |
---|
87 | n/a | |
---|
88 | n/a | def _exists(fn): |
---|
89 | n/a | try: |
---|
90 | n/a | _stat(fn) |
---|
91 | n/a | except OSError: |
---|
92 | n/a | return False |
---|
93 | n/a | else: |
---|
94 | n/a | return True |
---|
95 | n/a | |
---|
96 | n/a | |
---|
97 | n/a | def _infer_return_type(*args): |
---|
98 | n/a | """Look at the type of all args and divine their implied return type.""" |
---|
99 | n/a | return_type = None |
---|
100 | n/a | for arg in args: |
---|
101 | n/a | if arg is None: |
---|
102 | n/a | continue |
---|
103 | n/a | if isinstance(arg, bytes): |
---|
104 | n/a | if return_type is str: |
---|
105 | n/a | raise TypeError("Can't mix bytes and non-bytes in " |
---|
106 | n/a | "path components.") |
---|
107 | n/a | return_type = bytes |
---|
108 | n/a | else: |
---|
109 | n/a | if return_type is bytes: |
---|
110 | n/a | raise TypeError("Can't mix bytes and non-bytes in " |
---|
111 | n/a | "path components.") |
---|
112 | n/a | return_type = str |
---|
113 | n/a | if return_type is None: |
---|
114 | n/a | return str # tempfile APIs return a str by default. |
---|
115 | n/a | return return_type |
---|
116 | n/a | |
---|
117 | n/a | |
---|
118 | n/a | def _sanitize_params(prefix, suffix, dir): |
---|
119 | n/a | """Common parameter processing for most APIs in this module.""" |
---|
120 | n/a | output_type = _infer_return_type(prefix, suffix, dir) |
---|
121 | n/a | if suffix is None: |
---|
122 | n/a | suffix = output_type() |
---|
123 | n/a | if prefix is None: |
---|
124 | n/a | if output_type is str: |
---|
125 | n/a | prefix = template |
---|
126 | n/a | else: |
---|
127 | n/a | prefix = _os.fsencode(template) |
---|
128 | n/a | if dir is None: |
---|
129 | n/a | if output_type is str: |
---|
130 | n/a | dir = gettempdir() |
---|
131 | n/a | else: |
---|
132 | n/a | dir = gettempdirb() |
---|
133 | n/a | return prefix, suffix, dir, output_type |
---|
134 | n/a | |
---|
135 | n/a | |
---|
136 | n/a | class _RandomNameSequence: |
---|
137 | n/a | """An instance of _RandomNameSequence generates an endless |
---|
138 | n/a | sequence of unpredictable strings which can safely be incorporated |
---|
139 | n/a | into file names. Each string is six characters long. Multiple |
---|
140 | n/a | threads can safely use the same instance at the same time. |
---|
141 | n/a | |
---|
142 | n/a | _RandomNameSequence is an iterator.""" |
---|
143 | n/a | |
---|
144 | n/a | characters = "abcdefghijklmnopqrstuvwxyz0123456789_" |
---|
145 | n/a | |
---|
146 | n/a | @property |
---|
147 | n/a | def rng(self): |
---|
148 | n/a | cur_pid = _os.getpid() |
---|
149 | n/a | if cur_pid != getattr(self, '_rng_pid', None): |
---|
150 | n/a | self._rng = _Random() |
---|
151 | n/a | self._rng_pid = cur_pid |
---|
152 | n/a | return self._rng |
---|
153 | n/a | |
---|
154 | n/a | def __iter__(self): |
---|
155 | n/a | return self |
---|
156 | n/a | |
---|
157 | n/a | def __next__(self): |
---|
158 | n/a | c = self.characters |
---|
159 | n/a | choose = self.rng.choice |
---|
160 | n/a | letters = [choose(c) for dummy in range(8)] |
---|
161 | n/a | return ''.join(letters) |
---|
162 | n/a | |
---|
163 | n/a | def _candidate_tempdir_list(): |
---|
164 | n/a | """Generate a list of candidate temporary directories which |
---|
165 | n/a | _get_default_tempdir will try.""" |
---|
166 | n/a | |
---|
167 | n/a | dirlist = [] |
---|
168 | n/a | |
---|
169 | n/a | # First, try the environment. |
---|
170 | n/a | for envname in 'TMPDIR', 'TEMP', 'TMP': |
---|
171 | n/a | dirname = _os.getenv(envname) |
---|
172 | n/a | if dirname: dirlist.append(dirname) |
---|
173 | n/a | |
---|
174 | n/a | # Failing that, try OS-specific locations. |
---|
175 | n/a | if _os.name == 'nt': |
---|
176 | n/a | dirlist.extend([ r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ]) |
---|
177 | n/a | else: |
---|
178 | n/a | dirlist.extend([ '/tmp', '/var/tmp', '/usr/tmp' ]) |
---|
179 | n/a | |
---|
180 | n/a | # As a last resort, the current directory. |
---|
181 | n/a | try: |
---|
182 | n/a | dirlist.append(_os.getcwd()) |
---|
183 | n/a | except (AttributeError, OSError): |
---|
184 | n/a | dirlist.append(_os.curdir) |
---|
185 | n/a | |
---|
186 | n/a | return dirlist |
---|
187 | n/a | |
---|
188 | n/a | def _get_default_tempdir(): |
---|
189 | n/a | """Calculate the default directory to use for temporary files. |
---|
190 | n/a | This routine should be called exactly once. |
---|
191 | n/a | |
---|
192 | n/a | We determine whether or not a candidate temp dir is usable by |
---|
193 | n/a | trying to create and write to a file in that directory. If this |
---|
194 | n/a | is successful, the test file is deleted. To prevent denial of |
---|
195 | n/a | service, the name of the test file must be randomized.""" |
---|
196 | n/a | |
---|
197 | n/a | namer = _RandomNameSequence() |
---|
198 | n/a | dirlist = _candidate_tempdir_list() |
---|
199 | n/a | |
---|
200 | n/a | for dir in dirlist: |
---|
201 | n/a | if dir != _os.curdir: |
---|
202 | n/a | dir = _os.path.abspath(dir) |
---|
203 | n/a | # Try only a few names per directory. |
---|
204 | n/a | for seq in range(100): |
---|
205 | n/a | name = next(namer) |
---|
206 | n/a | filename = _os.path.join(dir, name) |
---|
207 | n/a | try: |
---|
208 | n/a | fd = _os.open(filename, _bin_openflags, 0o600) |
---|
209 | n/a | try: |
---|
210 | n/a | try: |
---|
211 | n/a | with _io.open(fd, 'wb', closefd=False) as fp: |
---|
212 | n/a | fp.write(b'blat') |
---|
213 | n/a | finally: |
---|
214 | n/a | _os.close(fd) |
---|
215 | n/a | finally: |
---|
216 | n/a | _os.unlink(filename) |
---|
217 | n/a | return dir |
---|
218 | n/a | except FileExistsError: |
---|
219 | n/a | pass |
---|
220 | n/a | except PermissionError: |
---|
221 | n/a | # This exception is thrown when a directory with the chosen name |
---|
222 | n/a | # already exists on windows. |
---|
223 | n/a | if (_os.name == 'nt' and _os.path.isdir(dir) and |
---|
224 | n/a | _os.access(dir, _os.W_OK)): |
---|
225 | n/a | continue |
---|
226 | n/a | break # no point trying more names in this directory |
---|
227 | n/a | except OSError: |
---|
228 | n/a | break # no point trying more names in this directory |
---|
229 | n/a | raise FileNotFoundError(_errno.ENOENT, |
---|
230 | n/a | "No usable temporary directory found in %s" % |
---|
231 | n/a | dirlist) |
---|
232 | n/a | |
---|
233 | n/a | _name_sequence = None |
---|
234 | n/a | |
---|
235 | n/a | def _get_candidate_names(): |
---|
236 | n/a | """Common setup sequence for all user-callable interfaces.""" |
---|
237 | n/a | |
---|
238 | n/a | global _name_sequence |
---|
239 | n/a | if _name_sequence is None: |
---|
240 | n/a | _once_lock.acquire() |
---|
241 | n/a | try: |
---|
242 | n/a | if _name_sequence is None: |
---|
243 | n/a | _name_sequence = _RandomNameSequence() |
---|
244 | n/a | finally: |
---|
245 | n/a | _once_lock.release() |
---|
246 | n/a | return _name_sequence |
---|
247 | n/a | |
---|
248 | n/a | |
---|
249 | n/a | def _mkstemp_inner(dir, pre, suf, flags, output_type): |
---|
250 | n/a | """Code common to mkstemp, TemporaryFile, and NamedTemporaryFile.""" |
---|
251 | n/a | |
---|
252 | n/a | names = _get_candidate_names() |
---|
253 | n/a | if output_type is bytes: |
---|
254 | n/a | names = map(_os.fsencode, names) |
---|
255 | n/a | |
---|
256 | n/a | for seq in range(TMP_MAX): |
---|
257 | n/a | name = next(names) |
---|
258 | n/a | file = _os.path.join(dir, pre + name + suf) |
---|
259 | n/a | try: |
---|
260 | n/a | fd = _os.open(file, flags, 0o600) |
---|
261 | n/a | except FileExistsError: |
---|
262 | n/a | continue # try again |
---|
263 | n/a | except PermissionError: |
---|
264 | n/a | # This exception is thrown when a directory with the chosen name |
---|
265 | n/a | # already exists on windows. |
---|
266 | n/a | if (_os.name == 'nt' and _os.path.isdir(dir) and |
---|
267 | n/a | _os.access(dir, _os.W_OK)): |
---|
268 | n/a | continue |
---|
269 | n/a | else: |
---|
270 | n/a | raise |
---|
271 | n/a | return (fd, _os.path.abspath(file)) |
---|
272 | n/a | |
---|
273 | n/a | raise FileExistsError(_errno.EEXIST, |
---|
274 | n/a | "No usable temporary file name found") |
---|
275 | n/a | |
---|
276 | n/a | |
---|
277 | n/a | # User visible interfaces. |
---|
278 | n/a | |
---|
279 | n/a | def gettempprefix(): |
---|
280 | n/a | """The default prefix for temporary directories.""" |
---|
281 | n/a | return template |
---|
282 | n/a | |
---|
283 | n/a | def gettempprefixb(): |
---|
284 | n/a | """The default prefix for temporary directories as bytes.""" |
---|
285 | n/a | return _os.fsencode(gettempprefix()) |
---|
286 | n/a | |
---|
287 | n/a | tempdir = None |
---|
288 | n/a | |
---|
289 | n/a | def gettempdir(): |
---|
290 | n/a | """Accessor for tempfile.tempdir.""" |
---|
291 | n/a | global tempdir |
---|
292 | n/a | if tempdir is None: |
---|
293 | n/a | _once_lock.acquire() |
---|
294 | n/a | try: |
---|
295 | n/a | if tempdir is None: |
---|
296 | n/a | tempdir = _get_default_tempdir() |
---|
297 | n/a | finally: |
---|
298 | n/a | _once_lock.release() |
---|
299 | n/a | return tempdir |
---|
300 | n/a | |
---|
301 | n/a | def gettempdirb(): |
---|
302 | n/a | """A bytes version of tempfile.gettempdir().""" |
---|
303 | n/a | return _os.fsencode(gettempdir()) |
---|
304 | n/a | |
---|
305 | n/a | def mkstemp(suffix=None, prefix=None, dir=None, text=False): |
---|
306 | n/a | """User-callable function to create and return a unique temporary |
---|
307 | n/a | file. The return value is a pair (fd, name) where fd is the |
---|
308 | n/a | file descriptor returned by os.open, and name is the filename. |
---|
309 | n/a | |
---|
310 | n/a | If 'suffix' is not None, the file name will end with that suffix, |
---|
311 | n/a | otherwise there will be no suffix. |
---|
312 | n/a | |
---|
313 | n/a | If 'prefix' is not None, the file name will begin with that prefix, |
---|
314 | n/a | otherwise a default prefix is used. |
---|
315 | n/a | |
---|
316 | n/a | If 'dir' is not None, the file will be created in that directory, |
---|
317 | n/a | otherwise a default directory is used. |
---|
318 | n/a | |
---|
319 | n/a | If 'text' is specified and true, the file is opened in text |
---|
320 | n/a | mode. Else (the default) the file is opened in binary mode. On |
---|
321 | n/a | some operating systems, this makes no difference. |
---|
322 | n/a | |
---|
323 | n/a | If any of 'suffix', 'prefix' and 'dir' are not None, they must be the |
---|
324 | n/a | same type. If they are bytes, the returned name will be bytes; str |
---|
325 | n/a | otherwise. |
---|
326 | n/a | |
---|
327 | n/a | The file is readable and writable only by the creating user ID. |
---|
328 | n/a | If the operating system uses permission bits to indicate whether a |
---|
329 | n/a | file is executable, the file is executable by no one. The file |
---|
330 | n/a | descriptor is not inherited by children of this process. |
---|
331 | n/a | |
---|
332 | n/a | Caller is responsible for deleting the file when done with it. |
---|
333 | n/a | """ |
---|
334 | n/a | |
---|
335 | n/a | prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir) |
---|
336 | n/a | |
---|
337 | n/a | if text: |
---|
338 | n/a | flags = _text_openflags |
---|
339 | n/a | else: |
---|
340 | n/a | flags = _bin_openflags |
---|
341 | n/a | |
---|
342 | n/a | return _mkstemp_inner(dir, prefix, suffix, flags, output_type) |
---|
343 | n/a | |
---|
344 | n/a | |
---|
345 | n/a | def mkdtemp(suffix=None, prefix=None, dir=None): |
---|
346 | n/a | """User-callable function to create and return a unique temporary |
---|
347 | n/a | directory. The return value is the pathname of the directory. |
---|
348 | n/a | |
---|
349 | n/a | Arguments are as for mkstemp, except that the 'text' argument is |
---|
350 | n/a | not accepted. |
---|
351 | n/a | |
---|
352 | n/a | The directory is readable, writable, and searchable only by the |
---|
353 | n/a | creating user. |
---|
354 | n/a | |
---|
355 | n/a | Caller is responsible for deleting the directory when done with it. |
---|
356 | n/a | """ |
---|
357 | n/a | |
---|
358 | n/a | prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir) |
---|
359 | n/a | |
---|
360 | n/a | names = _get_candidate_names() |
---|
361 | n/a | if output_type is bytes: |
---|
362 | n/a | names = map(_os.fsencode, names) |
---|
363 | n/a | |
---|
364 | n/a | for seq in range(TMP_MAX): |
---|
365 | n/a | name = next(names) |
---|
366 | n/a | file = _os.path.join(dir, prefix + name + suffix) |
---|
367 | n/a | try: |
---|
368 | n/a | _os.mkdir(file, 0o700) |
---|
369 | n/a | except FileExistsError: |
---|
370 | n/a | continue # try again |
---|
371 | n/a | except PermissionError: |
---|
372 | n/a | # This exception is thrown when a directory with the chosen name |
---|
373 | n/a | # already exists on windows. |
---|
374 | n/a | if (_os.name == 'nt' and _os.path.isdir(dir) and |
---|
375 | n/a | _os.access(dir, _os.W_OK)): |
---|
376 | n/a | continue |
---|
377 | n/a | else: |
---|
378 | n/a | raise |
---|
379 | n/a | return file |
---|
380 | n/a | |
---|
381 | n/a | raise FileExistsError(_errno.EEXIST, |
---|
382 | n/a | "No usable temporary directory name found") |
---|
383 | n/a | |
---|
384 | n/a | def mktemp(suffix="", prefix=template, dir=None): |
---|
385 | n/a | """User-callable function to return a unique temporary file name. The |
---|
386 | n/a | file is not created. |
---|
387 | n/a | |
---|
388 | n/a | Arguments are similar to mkstemp, except that the 'text' argument is |
---|
389 | n/a | not accepted, and suffix=None, prefix=None and bytes file names are not |
---|
390 | n/a | supported. |
---|
391 | n/a | |
---|
392 | n/a | THIS FUNCTION IS UNSAFE AND SHOULD NOT BE USED. The file name may |
---|
393 | n/a | refer to a file that did not exist at some point, but by the time |
---|
394 | n/a | you get around to creating it, someone else may have beaten you to |
---|
395 | n/a | the punch. |
---|
396 | n/a | """ |
---|
397 | n/a | |
---|
398 | n/a | ## from warnings import warn as _warn |
---|
399 | n/a | ## _warn("mktemp is a potential security risk to your program", |
---|
400 | n/a | ## RuntimeWarning, stacklevel=2) |
---|
401 | n/a | |
---|
402 | n/a | if dir is None: |
---|
403 | n/a | dir = gettempdir() |
---|
404 | n/a | |
---|
405 | n/a | names = _get_candidate_names() |
---|
406 | n/a | for seq in range(TMP_MAX): |
---|
407 | n/a | name = next(names) |
---|
408 | n/a | file = _os.path.join(dir, prefix + name + suffix) |
---|
409 | n/a | if not _exists(file): |
---|
410 | n/a | return file |
---|
411 | n/a | |
---|
412 | n/a | raise FileExistsError(_errno.EEXIST, |
---|
413 | n/a | "No usable temporary filename found") |
---|
414 | n/a | |
---|
415 | n/a | |
---|
416 | n/a | class _TemporaryFileCloser: |
---|
417 | n/a | """A separate object allowing proper closing of a temporary file's |
---|
418 | n/a | underlying file object, without adding a __del__ method to the |
---|
419 | n/a | temporary file.""" |
---|
420 | n/a | |
---|
421 | n/a | file = None # Set here since __del__ checks it |
---|
422 | n/a | close_called = False |
---|
423 | n/a | |
---|
424 | n/a | def __init__(self, file, name, delete=True): |
---|
425 | n/a | self.file = file |
---|
426 | n/a | self.name = name |
---|
427 | n/a | self.delete = delete |
---|
428 | n/a | |
---|
429 | n/a | # NT provides delete-on-close as a primitive, so we don't need |
---|
430 | n/a | # the wrapper to do anything special. We still use it so that |
---|
431 | n/a | # file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile. |
---|
432 | n/a | if _os.name != 'nt': |
---|
433 | n/a | # Cache the unlinker so we don't get spurious errors at |
---|
434 | n/a | # shutdown when the module-level "os" is None'd out. Note |
---|
435 | n/a | # that this must be referenced as self.unlink, because the |
---|
436 | n/a | # name TemporaryFileWrapper may also get None'd out before |
---|
437 | n/a | # __del__ is called. |
---|
438 | n/a | |
---|
439 | n/a | def close(self, unlink=_os.unlink): |
---|
440 | n/a | if not self.close_called and self.file is not None: |
---|
441 | n/a | self.close_called = True |
---|
442 | n/a | try: |
---|
443 | n/a | self.file.close() |
---|
444 | n/a | finally: |
---|
445 | n/a | if self.delete: |
---|
446 | n/a | unlink(self.name) |
---|
447 | n/a | |
---|
448 | n/a | # Need to ensure the file is deleted on __del__ |
---|
449 | n/a | def __del__(self): |
---|
450 | n/a | self.close() |
---|
451 | n/a | |
---|
452 | n/a | else: |
---|
453 | n/a | def close(self): |
---|
454 | n/a | if not self.close_called: |
---|
455 | n/a | self.close_called = True |
---|
456 | n/a | self.file.close() |
---|
457 | n/a | |
---|
458 | n/a | |
---|
459 | n/a | class _TemporaryFileWrapper: |
---|
460 | n/a | """Temporary file wrapper |
---|
461 | n/a | |
---|
462 | n/a | This class provides a wrapper around files opened for |
---|
463 | n/a | temporary use. In particular, it seeks to automatically |
---|
464 | n/a | remove the file when it is no longer needed. |
---|
465 | n/a | """ |
---|
466 | n/a | |
---|
467 | n/a | def __init__(self, file, name, delete=True): |
---|
468 | n/a | self.file = file |
---|
469 | n/a | self.name = name |
---|
470 | n/a | self.delete = delete |
---|
471 | n/a | self._closer = _TemporaryFileCloser(file, name, delete) |
---|
472 | n/a | |
---|
473 | n/a | def __getattr__(self, name): |
---|
474 | n/a | # Attribute lookups are delegated to the underlying file |
---|
475 | n/a | # and cached for non-numeric results |
---|
476 | n/a | # (i.e. methods are cached, closed and friends are not) |
---|
477 | n/a | file = self.__dict__['file'] |
---|
478 | n/a | a = getattr(file, name) |
---|
479 | n/a | if hasattr(a, '__call__'): |
---|
480 | n/a | func = a |
---|
481 | n/a | @_functools.wraps(func) |
---|
482 | n/a | def func_wrapper(*args, **kwargs): |
---|
483 | n/a | return func(*args, **kwargs) |
---|
484 | n/a | # Avoid closing the file as long as the wrapper is alive, |
---|
485 | n/a | # see issue #18879. |
---|
486 | n/a | func_wrapper._closer = self._closer |
---|
487 | n/a | a = func_wrapper |
---|
488 | n/a | if not isinstance(a, int): |
---|
489 | n/a | setattr(self, name, a) |
---|
490 | n/a | return a |
---|
491 | n/a | |
---|
492 | n/a | # The underlying __enter__ method returns the wrong object |
---|
493 | n/a | # (self.file) so override it to return the wrapper |
---|
494 | n/a | def __enter__(self): |
---|
495 | n/a | self.file.__enter__() |
---|
496 | n/a | return self |
---|
497 | n/a | |
---|
498 | n/a | # Need to trap __exit__ as well to ensure the file gets |
---|
499 | n/a | # deleted when used in a with statement |
---|
500 | n/a | def __exit__(self, exc, value, tb): |
---|
501 | n/a | result = self.file.__exit__(exc, value, tb) |
---|
502 | n/a | self.close() |
---|
503 | n/a | return result |
---|
504 | n/a | |
---|
505 | n/a | def close(self): |
---|
506 | n/a | """ |
---|
507 | n/a | Close the temporary file, possibly deleting it. |
---|
508 | n/a | """ |
---|
509 | n/a | self._closer.close() |
---|
510 | n/a | |
---|
511 | n/a | # iter() doesn't use __getattr__ to find the __iter__ method |
---|
512 | n/a | def __iter__(self): |
---|
513 | n/a | # Don't return iter(self.file), but yield from it to avoid closing |
---|
514 | n/a | # file as long as it's being used as iterator (see issue #23700). We |
---|
515 | n/a | # can't use 'yield from' here because iter(file) returns the file |
---|
516 | n/a | # object itself, which has a close method, and thus the file would get |
---|
517 | n/a | # closed when the generator is finalized, due to PEP380 semantics. |
---|
518 | n/a | for line in self.file: |
---|
519 | n/a | yield line |
---|
520 | n/a | |
---|
521 | n/a | |
---|
522 | n/a | def NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None, |
---|
523 | n/a | newline=None, suffix=None, prefix=None, |
---|
524 | n/a | dir=None, delete=True): |
---|
525 | n/a | """Create and return a temporary file. |
---|
526 | n/a | Arguments: |
---|
527 | n/a | 'prefix', 'suffix', 'dir' -- as for mkstemp. |
---|
528 | n/a | 'mode' -- the mode argument to io.open (default "w+b"). |
---|
529 | n/a | 'buffering' -- the buffer size argument to io.open (default -1). |
---|
530 | n/a | 'encoding' -- the encoding argument to io.open (default None) |
---|
531 | n/a | 'newline' -- the newline argument to io.open (default None) |
---|
532 | n/a | 'delete' -- whether the file is deleted on close (default True). |
---|
533 | n/a | The file is created as mkstemp() would do it. |
---|
534 | n/a | |
---|
535 | n/a | Returns an object with a file-like interface; the name of the file |
---|
536 | n/a | is accessible as its 'name' attribute. The file will be automatically |
---|
537 | n/a | deleted when it is closed unless the 'delete' argument is set to False. |
---|
538 | n/a | """ |
---|
539 | n/a | |
---|
540 | n/a | prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir) |
---|
541 | n/a | |
---|
542 | n/a | flags = _bin_openflags |
---|
543 | n/a | |
---|
544 | n/a | # Setting O_TEMPORARY in the flags causes the OS to delete |
---|
545 | n/a | # the file when it is closed. This is only supported by Windows. |
---|
546 | n/a | if _os.name == 'nt' and delete: |
---|
547 | n/a | flags |= _os.O_TEMPORARY |
---|
548 | n/a | |
---|
549 | n/a | (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags, output_type) |
---|
550 | n/a | try: |
---|
551 | n/a | file = _io.open(fd, mode, buffering=buffering, |
---|
552 | n/a | newline=newline, encoding=encoding) |
---|
553 | n/a | |
---|
554 | n/a | return _TemporaryFileWrapper(file, name, delete) |
---|
555 | n/a | except BaseException: |
---|
556 | n/a | _os.unlink(name) |
---|
557 | n/a | _os.close(fd) |
---|
558 | n/a | raise |
---|
559 | n/a | |
---|
560 | n/a | if _os.name != 'posix' or _os.sys.platform == 'cygwin': |
---|
561 | n/a | # On non-POSIX and Cygwin systems, assume that we cannot unlink a file |
---|
562 | n/a | # while it is open. |
---|
563 | n/a | TemporaryFile = NamedTemporaryFile |
---|
564 | n/a | |
---|
565 | n/a | else: |
---|
566 | n/a | # Is the O_TMPFILE flag available and does it work? |
---|
567 | n/a | # The flag is set to False if os.open(dir, os.O_TMPFILE) raises an |
---|
568 | n/a | # IsADirectoryError exception |
---|
569 | n/a | _O_TMPFILE_WORKS = hasattr(_os, 'O_TMPFILE') |
---|
570 | n/a | |
---|
571 | n/a | def TemporaryFile(mode='w+b', buffering=-1, encoding=None, |
---|
572 | n/a | newline=None, suffix=None, prefix=None, |
---|
573 | n/a | dir=None): |
---|
574 | n/a | """Create and return a temporary file. |
---|
575 | n/a | Arguments: |
---|
576 | n/a | 'prefix', 'suffix', 'dir' -- as for mkstemp. |
---|
577 | n/a | 'mode' -- the mode argument to io.open (default "w+b"). |
---|
578 | n/a | 'buffering' -- the buffer size argument to io.open (default -1). |
---|
579 | n/a | 'encoding' -- the encoding argument to io.open (default None) |
---|
580 | n/a | 'newline' -- the newline argument to io.open (default None) |
---|
581 | n/a | The file is created as mkstemp() would do it. |
---|
582 | n/a | |
---|
583 | n/a | Returns an object with a file-like interface. The file has no |
---|
584 | n/a | name, and will cease to exist when it is closed. |
---|
585 | n/a | """ |
---|
586 | n/a | global _O_TMPFILE_WORKS |
---|
587 | n/a | |
---|
588 | n/a | prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir) |
---|
589 | n/a | |
---|
590 | n/a | flags = _bin_openflags |
---|
591 | n/a | if _O_TMPFILE_WORKS: |
---|
592 | n/a | try: |
---|
593 | n/a | flags2 = (flags | _os.O_TMPFILE) & ~_os.O_CREAT |
---|
594 | n/a | fd = _os.open(dir, flags2, 0o600) |
---|
595 | n/a | except IsADirectoryError: |
---|
596 | n/a | # Linux kernel older than 3.11 ignores the O_TMPFILE flag: |
---|
597 | n/a | # O_TMPFILE is read as O_DIRECTORY. Trying to open a directory |
---|
598 | n/a | # with O_RDWR|O_DIRECTORY fails with IsADirectoryError, a |
---|
599 | n/a | # directory cannot be open to write. Set flag to False to not |
---|
600 | n/a | # try again. |
---|
601 | n/a | _O_TMPFILE_WORKS = False |
---|
602 | n/a | except OSError: |
---|
603 | n/a | # The filesystem of the directory does not support O_TMPFILE. |
---|
604 | n/a | # For example, OSError(95, 'Operation not supported'). |
---|
605 | n/a | # |
---|
606 | n/a | # On Linux kernel older than 3.11, trying to open a regular |
---|
607 | n/a | # file (or a symbolic link to a regular file) with O_TMPFILE |
---|
608 | n/a | # fails with NotADirectoryError, because O_TMPFILE is read as |
---|
609 | n/a | # O_DIRECTORY. |
---|
610 | n/a | pass |
---|
611 | n/a | else: |
---|
612 | n/a | try: |
---|
613 | n/a | return _io.open(fd, mode, buffering=buffering, |
---|
614 | n/a | newline=newline, encoding=encoding) |
---|
615 | n/a | except: |
---|
616 | n/a | _os.close(fd) |
---|
617 | n/a | raise |
---|
618 | n/a | # Fallback to _mkstemp_inner(). |
---|
619 | n/a | |
---|
620 | n/a | (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags, output_type) |
---|
621 | n/a | try: |
---|
622 | n/a | _os.unlink(name) |
---|
623 | n/a | return _io.open(fd, mode, buffering=buffering, |
---|
624 | n/a | newline=newline, encoding=encoding) |
---|
625 | n/a | except: |
---|
626 | n/a | _os.close(fd) |
---|
627 | n/a | raise |
---|
628 | n/a | |
---|
629 | n/a | class SpooledTemporaryFile: |
---|
630 | n/a | """Temporary file wrapper, specialized to switch from BytesIO |
---|
631 | n/a | or StringIO to a real file when it exceeds a certain size or |
---|
632 | n/a | when a fileno is needed. |
---|
633 | n/a | """ |
---|
634 | n/a | _rolled = False |
---|
635 | n/a | |
---|
636 | n/a | def __init__(self, max_size=0, mode='w+b', buffering=-1, |
---|
637 | n/a | encoding=None, newline=None, |
---|
638 | n/a | suffix=None, prefix=None, dir=None): |
---|
639 | n/a | if 'b' in mode: |
---|
640 | n/a | self._file = _io.BytesIO() |
---|
641 | n/a | else: |
---|
642 | n/a | # Setting newline="\n" avoids newline translation; |
---|
643 | n/a | # this is important because otherwise on Windows we'd |
---|
644 | n/a | # get double newline translation upon rollover(). |
---|
645 | n/a | self._file = _io.StringIO(newline="\n") |
---|
646 | n/a | self._max_size = max_size |
---|
647 | n/a | self._rolled = False |
---|
648 | n/a | self._TemporaryFileArgs = {'mode': mode, 'buffering': buffering, |
---|
649 | n/a | 'suffix': suffix, 'prefix': prefix, |
---|
650 | n/a | 'encoding': encoding, 'newline': newline, |
---|
651 | n/a | 'dir': dir} |
---|
652 | n/a | |
---|
653 | n/a | def _check(self, file): |
---|
654 | n/a | if self._rolled: return |
---|
655 | n/a | max_size = self._max_size |
---|
656 | n/a | if max_size and file.tell() > max_size: |
---|
657 | n/a | self.rollover() |
---|
658 | n/a | |
---|
659 | n/a | def rollover(self): |
---|
660 | n/a | if self._rolled: return |
---|
661 | n/a | file = self._file |
---|
662 | n/a | newfile = self._file = TemporaryFile(**self._TemporaryFileArgs) |
---|
663 | n/a | del self._TemporaryFileArgs |
---|
664 | n/a | |
---|
665 | n/a | newfile.write(file.getvalue()) |
---|
666 | n/a | newfile.seek(file.tell(), 0) |
---|
667 | n/a | |
---|
668 | n/a | self._rolled = True |
---|
669 | n/a | |
---|
670 | n/a | # The method caching trick from NamedTemporaryFile |
---|
671 | n/a | # won't work here, because _file may change from a |
---|
672 | n/a | # BytesIO/StringIO instance to a real file. So we list |
---|
673 | n/a | # all the methods directly. |
---|
674 | n/a | |
---|
675 | n/a | # Context management protocol |
---|
676 | n/a | def __enter__(self): |
---|
677 | n/a | if self._file.closed: |
---|
678 | n/a | raise ValueError("Cannot enter context with closed file") |
---|
679 | n/a | return self |
---|
680 | n/a | |
---|
681 | n/a | def __exit__(self, exc, value, tb): |
---|
682 | n/a | self._file.close() |
---|
683 | n/a | |
---|
684 | n/a | # file protocol |
---|
685 | n/a | def __iter__(self): |
---|
686 | n/a | return self._file.__iter__() |
---|
687 | n/a | |
---|
688 | n/a | def close(self): |
---|
689 | n/a | self._file.close() |
---|
690 | n/a | |
---|
691 | n/a | @property |
---|
692 | n/a | def closed(self): |
---|
693 | n/a | return self._file.closed |
---|
694 | n/a | |
---|
695 | n/a | @property |
---|
696 | n/a | def encoding(self): |
---|
697 | n/a | try: |
---|
698 | n/a | return self._file.encoding |
---|
699 | n/a | except AttributeError: |
---|
700 | n/a | if 'b' in self._TemporaryFileArgs['mode']: |
---|
701 | n/a | raise |
---|
702 | n/a | return self._TemporaryFileArgs['encoding'] |
---|
703 | n/a | |
---|
704 | n/a | def fileno(self): |
---|
705 | n/a | self.rollover() |
---|
706 | n/a | return self._file.fileno() |
---|
707 | n/a | |
---|
708 | n/a | def flush(self): |
---|
709 | n/a | self._file.flush() |
---|
710 | n/a | |
---|
711 | n/a | def isatty(self): |
---|
712 | n/a | return self._file.isatty() |
---|
713 | n/a | |
---|
714 | n/a | @property |
---|
715 | n/a | def mode(self): |
---|
716 | n/a | try: |
---|
717 | n/a | return self._file.mode |
---|
718 | n/a | except AttributeError: |
---|
719 | n/a | return self._TemporaryFileArgs['mode'] |
---|
720 | n/a | |
---|
721 | n/a | @property |
---|
722 | n/a | def name(self): |
---|
723 | n/a | try: |
---|
724 | n/a | return self._file.name |
---|
725 | n/a | except AttributeError: |
---|
726 | n/a | return None |
---|
727 | n/a | |
---|
728 | n/a | @property |
---|
729 | n/a | def newlines(self): |
---|
730 | n/a | try: |
---|
731 | n/a | return self._file.newlines |
---|
732 | n/a | except AttributeError: |
---|
733 | n/a | if 'b' in self._TemporaryFileArgs['mode']: |
---|
734 | n/a | raise |
---|
735 | n/a | return self._TemporaryFileArgs['newline'] |
---|
736 | n/a | |
---|
737 | n/a | def read(self, *args): |
---|
738 | n/a | return self._file.read(*args) |
---|
739 | n/a | |
---|
740 | n/a | def readline(self, *args): |
---|
741 | n/a | return self._file.readline(*args) |
---|
742 | n/a | |
---|
743 | n/a | def readlines(self, *args): |
---|
744 | n/a | return self._file.readlines(*args) |
---|
745 | n/a | |
---|
746 | n/a | def seek(self, *args): |
---|
747 | n/a | self._file.seek(*args) |
---|
748 | n/a | |
---|
749 | n/a | @property |
---|
750 | n/a | def softspace(self): |
---|
751 | n/a | return self._file.softspace |
---|
752 | n/a | |
---|
753 | n/a | def tell(self): |
---|
754 | n/a | return self._file.tell() |
---|
755 | n/a | |
---|
756 | n/a | def truncate(self, size=None): |
---|
757 | n/a | if size is None: |
---|
758 | n/a | self._file.truncate() |
---|
759 | n/a | else: |
---|
760 | n/a | if size > self._max_size: |
---|
761 | n/a | self.rollover() |
---|
762 | n/a | self._file.truncate(size) |
---|
763 | n/a | |
---|
764 | n/a | def write(self, s): |
---|
765 | n/a | file = self._file |
---|
766 | n/a | rv = file.write(s) |
---|
767 | n/a | self._check(file) |
---|
768 | n/a | return rv |
---|
769 | n/a | |
---|
770 | n/a | def writelines(self, iterable): |
---|
771 | n/a | file = self._file |
---|
772 | n/a | rv = file.writelines(iterable) |
---|
773 | n/a | self._check(file) |
---|
774 | n/a | return rv |
---|
775 | n/a | |
---|
776 | n/a | |
---|
777 | n/a | class TemporaryDirectory(object): |
---|
778 | n/a | """Create and return a temporary directory. This has the same |
---|
779 | n/a | behavior as mkdtemp but can be used as a context manager. For |
---|
780 | n/a | example: |
---|
781 | n/a | |
---|
782 | n/a | with TemporaryDirectory() as tmpdir: |
---|
783 | n/a | ... |
---|
784 | n/a | |
---|
785 | n/a | Upon exiting the context, the directory and everything contained |
---|
786 | n/a | in it are removed. |
---|
787 | n/a | """ |
---|
788 | n/a | |
---|
789 | n/a | def __init__(self, suffix=None, prefix=None, dir=None): |
---|
790 | n/a | self.name = mkdtemp(suffix, prefix, dir) |
---|
791 | n/a | self._finalizer = _weakref.finalize( |
---|
792 | n/a | self, self._cleanup, self.name, |
---|
793 | n/a | warn_message="Implicitly cleaning up {!r}".format(self)) |
---|
794 | n/a | |
---|
795 | n/a | @classmethod |
---|
796 | n/a | def _cleanup(cls, name, warn_message): |
---|
797 | n/a | _shutil.rmtree(name) |
---|
798 | n/a | _warnings.warn(warn_message, ResourceWarning) |
---|
799 | n/a | |
---|
800 | n/a | def __repr__(self): |
---|
801 | n/a | return "<{} {!r}>".format(self.__class__.__name__, self.name) |
---|
802 | n/a | |
---|
803 | n/a | def __enter__(self): |
---|
804 | n/a | return self.name |
---|
805 | n/a | |
---|
806 | n/a | def __exit__(self, exc, value, tb): |
---|
807 | n/a | self.cleanup() |
---|
808 | n/a | |
---|
809 | n/a | def cleanup(self): |
---|
810 | n/a | if self._finalizer.detach(): |
---|
811 | n/a | _shutil.rmtree(self.name) |
---|