Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 1 | """Temporary files. |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 2 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 3 | This module provides generic, low- and high-level interfaces for |
Yury Selivanov | 3e67d58 | 2014-09-26 17:08:02 -0400 | [diff] [blame] | 4 | creating temporary files and directories. All of the interfaces |
| 5 | provided by this module can be used without fear of race conditions |
| 6 | except for 'mktemp'. 'mktemp' is subject to race conditions and |
| 7 | should not be used; it is provided for backward compatibility only. |
Guido van Rossum | eee9498 | 1991-11-12 15:38:08 +0000 | [diff] [blame] | 8 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 9 | This module also provides some data items to the user: |
Guido van Rossum | eee9498 | 1991-11-12 15:38:08 +0000 | [diff] [blame] | 10 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 11 | TMP_MAX - maximum number of names that will be tried before |
| 12 | giving up. |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 13 | tempdir - If this is set to a string before the first use of |
| 14 | any routine from this module, it will be considered as |
| 15 | another candidate location to store temporary files. |
| 16 | """ |
Skip Montanaro | 40fc160 | 2001-03-01 04:27:19 +0000 | [diff] [blame] | 17 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 18 | __all__ = [ |
| 19 | "NamedTemporaryFile", "TemporaryFile", # high level safe interfaces |
Nick Coghlan | 543af75 | 2010-10-24 11:23:25 +0000 | [diff] [blame] | 20 | "SpooledTemporaryFile", "TemporaryDirectory", |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 21 | "mkstemp", "mkdtemp", # low level safe interfaces |
| 22 | "mktemp", # deprecated unsafe interface |
| 23 | "TMP_MAX", "gettempprefix", # constants |
| 24 | "tempdir", "gettempdir" |
| 25 | ] |
Guido van Rossum | 41f9503 | 1992-03-31 19:02:01 +0000 | [diff] [blame] | 26 | |
Tim Peters | 4fd5a06 | 2002-01-28 23:11:23 +0000 | [diff] [blame] | 27 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 28 | # Imports. |
Tim Peters | 4fd5a06 | 2002-01-28 23:11:23 +0000 | [diff] [blame] | 29 | |
Antoine Pitrou | 17c9326 | 2013-12-21 22:14:56 +0100 | [diff] [blame] | 30 | import functools as _functools |
Nick Coghlan | 6b22f3f | 2010-12-12 15:24:21 +0000 | [diff] [blame] | 31 | import warnings as _warnings |
Guido van Rossum | 9a63470 | 2007-07-09 10:24:45 +0000 | [diff] [blame] | 32 | import io as _io |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 33 | import os as _os |
Serhiy Storchaka | 99e033b | 2014-01-27 11:18:27 +0200 | [diff] [blame] | 34 | import shutil as _shutil |
Serhiy Storchaka | 7451a72 | 2013-02-09 22:25:49 +0200 | [diff] [blame] | 35 | import errno as _errno |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 36 | from random import Random as _Random |
Serhiy Storchaka | a28632b | 2014-01-27 11:21:54 +0200 | [diff] [blame] | 37 | import weakref as _weakref |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 38 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 39 | try: |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 40 | import _thread |
Brett Cannon | cd171c8 | 2013-07-04 17:43:24 -0400 | [diff] [blame] | 41 | except ImportError: |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 42 | import _dummy_thread as _thread |
Guido van Rossum | a093424 | 2002-12-30 22:36:09 +0000 | [diff] [blame] | 43 | _allocate_lock = _thread.allocate_lock |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 44 | |
| 45 | _text_openflags = _os.O_RDWR | _os.O_CREAT | _os.O_EXCL |
Tim Peters | a0d55de | 2002-08-09 18:01:01 +0000 | [diff] [blame] | 46 | if hasattr(_os, 'O_NOFOLLOW'): |
| 47 | _text_openflags |= _os.O_NOFOLLOW |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 48 | |
| 49 | _bin_openflags = _text_openflags |
Tim Peters | a0d55de | 2002-08-09 18:01:01 +0000 | [diff] [blame] | 50 | if hasattr(_os, 'O_BINARY'): |
| 51 | _bin_openflags |= _os.O_BINARY |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 52 | |
| 53 | if hasattr(_os, 'TMP_MAX'): |
| 54 | TMP_MAX = _os.TMP_MAX |
| 55 | else: |
| 56 | TMP_MAX = 10000 |
| 57 | |
R David Murray | 3a420c7 | 2011-06-22 21:01:13 -0400 | [diff] [blame] | 58 | # Although it does not have an underscore for historical reasons, this |
| 59 | # variable is an internal implementation detail (see issue 10354). |
Tim Peters | bd7b4c7 | 2002-08-13 23:33:56 +0000 | [diff] [blame] | 60 | template = "tmp" |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 61 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 62 | # Internal routines. |
| 63 | |
| 64 | _once_lock = _allocate_lock() |
| 65 | |
Guido van Rossum | b25615939 | 2003-11-10 02:16:36 +0000 | [diff] [blame] | 66 | if hasattr(_os, "lstat"): |
| 67 | _stat = _os.lstat |
| 68 | elif hasattr(_os, "stat"): |
| 69 | _stat = _os.stat |
| 70 | else: |
Florent Xicluna | 68f71a3 | 2011-10-28 16:06:23 +0200 | [diff] [blame] | 71 | # Fallback. All we need is something that raises OSError if the |
Guido van Rossum | b25615939 | 2003-11-10 02:16:36 +0000 | [diff] [blame] | 72 | # file doesn't exist. |
| 73 | def _stat(fn): |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 74 | fd = _os.open(fn, _os.O_RDONLY) |
Victor Stinner | 69b1e26 | 2014-03-20 08:50:52 +0100 | [diff] [blame] | 75 | _os.close(fd) |
Guido van Rossum | b25615939 | 2003-11-10 02:16:36 +0000 | [diff] [blame] | 76 | |
| 77 | def _exists(fn): |
| 78 | try: |
| 79 | _stat(fn) |
Florent Xicluna | 68f71a3 | 2011-10-28 16:06:23 +0200 | [diff] [blame] | 80 | except OSError: |
Guido van Rossum | b25615939 | 2003-11-10 02:16:36 +0000 | [diff] [blame] | 81 | return False |
| 82 | else: |
| 83 | return True |
| 84 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 85 | class _RandomNameSequence: |
| 86 | """An instance of _RandomNameSequence generates an endless |
| 87 | sequence of unpredictable strings which can safely be incorporated |
| 88 | into file names. Each string is six characters long. Multiple |
| 89 | threads can safely use the same instance at the same time. |
| 90 | |
| 91 | _RandomNameSequence is an iterator.""" |
| 92 | |
Raymond Hettinger | 572895b | 2010-11-09 03:43:58 +0000 | [diff] [blame] | 93 | characters = "abcdefghijklmnopqrstuvwxyz0123456789_" |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 94 | |
Antoine Pitrou | 4558bad | 2011-11-25 21:28:15 +0100 | [diff] [blame] | 95 | @property |
| 96 | def rng(self): |
| 97 | cur_pid = _os.getpid() |
| 98 | if cur_pid != getattr(self, '_rng_pid', None): |
| 99 | self._rng = _Random() |
| 100 | self._rng_pid = cur_pid |
| 101 | return self._rng |
Tim Peters | 97701b5 | 2002-11-21 15:59:59 +0000 | [diff] [blame] | 102 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 103 | def __iter__(self): |
| 104 | return self |
| 105 | |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 106 | def __next__(self): |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 107 | c = self.characters |
Tim Peters | 97701b5 | 2002-11-21 15:59:59 +0000 | [diff] [blame] | 108 | choose = self.rng.choice |
Victor Stinner | 9786910 | 2013-08-14 01:28:28 +0200 | [diff] [blame] | 109 | letters = [choose(c) for dummy in range(8)] |
Raymond Hettinger | 572895b | 2010-11-09 03:43:58 +0000 | [diff] [blame] | 110 | return ''.join(letters) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 111 | |
| 112 | def _candidate_tempdir_list(): |
| 113 | """Generate a list of candidate temporary directories which |
| 114 | _get_default_tempdir will try.""" |
| 115 | |
| 116 | dirlist = [] |
| 117 | |
| 118 | # First, try the environment. |
| 119 | for envname in 'TMPDIR', 'TEMP', 'TMP': |
| 120 | dirname = _os.getenv(envname) |
| 121 | if dirname: dirlist.append(dirname) |
| 122 | |
| 123 | # Failing that, try OS-specific locations. |
Alexandre Vassalotti | eca20b6 | 2008-05-16 02:54:33 +0000 | [diff] [blame] | 124 | if _os.name == 'nt': |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 125 | dirlist.extend([ r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ]) |
| 126 | else: |
| 127 | dirlist.extend([ '/tmp', '/var/tmp', '/usr/tmp' ]) |
| 128 | |
| 129 | # As a last resort, the current directory. |
| 130 | try: |
| 131 | dirlist.append(_os.getcwd()) |
Florent Xicluna | 68f71a3 | 2011-10-28 16:06:23 +0200 | [diff] [blame] | 132 | except (AttributeError, OSError): |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 133 | dirlist.append(_os.curdir) |
| 134 | |
| 135 | return dirlist |
Tim Peters | a0d55de | 2002-08-09 18:01:01 +0000 | [diff] [blame] | 136 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 137 | def _get_default_tempdir(): |
| 138 | """Calculate the default directory to use for temporary files. |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 139 | This routine should be called exactly once. |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 140 | |
| 141 | We determine whether or not a candidate temp dir is usable by |
| 142 | trying to create and write to a file in that directory. If this |
| 143 | is successful, the test file is deleted. To prevent denial of |
| 144 | service, the name of the test file must be randomized.""" |
| 145 | |
| 146 | namer = _RandomNameSequence() |
| 147 | dirlist = _candidate_tempdir_list() |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 148 | |
| 149 | for dir in dirlist: |
| 150 | if dir != _os.curdir: |
Tim Golden | 6d09f09 | 2013-10-25 18:38:16 +0100 | [diff] [blame] | 151 | dir = _os.path.abspath(dir) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 152 | # Try only a few names per directory. |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 153 | for seq in range(100): |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 154 | name = next(namer) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 155 | filename = _os.path.join(dir, name) |
| 156 | try: |
Amaury Forgeot d'Arc | 7d0bddd | 2009-11-30 00:08:56 +0000 | [diff] [blame] | 157 | fd = _os.open(filename, _bin_openflags, 0o600) |
Serhiy Storchaka | f6b361e | 2013-02-13 00:35:30 +0200 | [diff] [blame] | 158 | try: |
| 159 | try: |
Serhiy Storchaka | 76a2ed1 | 2013-02-13 00:59:26 +0200 | [diff] [blame] | 160 | with _io.open(fd, 'wb', closefd=False) as fp: |
| 161 | fp.write(b'blat') |
Serhiy Storchaka | f6b361e | 2013-02-13 00:35:30 +0200 | [diff] [blame] | 162 | finally: |
| 163 | _os.close(fd) |
| 164 | finally: |
| 165 | _os.unlink(filename) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 166 | return dir |
Florent Xicluna | 68f71a3 | 2011-10-28 16:06:23 +0200 | [diff] [blame] | 167 | except FileExistsError: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 168 | pass |
Serhiy Storchaka | 5d6b7b1 | 2015-05-20 00:11:48 +0300 | [diff] [blame] | 169 | except PermissionError: |
| 170 | # This exception is thrown when a directory with the chosen name |
| 171 | # already exists on windows. |
| 172 | if (_os.name == 'nt' and _os.path.isdir(dir) and |
| 173 | _os.access(dir, _os.W_OK)): |
| 174 | continue |
| 175 | break # no point trying more names in this directory |
Florent Xicluna | 68f71a3 | 2011-10-28 16:06:23 +0200 | [diff] [blame] | 176 | except OSError: |
| 177 | break # no point trying more names in this directory |
Serhiy Storchaka | 7451a72 | 2013-02-09 22:25:49 +0200 | [diff] [blame] | 178 | raise FileNotFoundError(_errno.ENOENT, |
| 179 | "No usable temporary directory found in %s" % |
| 180 | dirlist) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 181 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 182 | _name_sequence = None |
| 183 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 184 | def _get_candidate_names(): |
| 185 | """Common setup sequence for all user-callable interfaces.""" |
| 186 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 187 | global _name_sequence |
| 188 | if _name_sequence is None: |
| 189 | _once_lock.acquire() |
| 190 | try: |
| 191 | if _name_sequence is None: |
| 192 | _name_sequence = _RandomNameSequence() |
| 193 | finally: |
| 194 | _once_lock.release() |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 195 | return _name_sequence |
Guido van Rossum | 41f9503 | 1992-03-31 19:02:01 +0000 | [diff] [blame] | 196 | |
| 197 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 198 | def _mkstemp_inner(dir, pre, suf, flags): |
| 199 | """Code common to mkstemp, TemporaryFile, and NamedTemporaryFile.""" |
Tim Peters | 9fadfb0 | 2001-01-13 03:04:02 +0000 | [diff] [blame] | 200 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 201 | names = _get_candidate_names() |
| 202 | |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 203 | for seq in range(TMP_MAX): |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 204 | name = next(names) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 205 | file = _os.path.join(dir, pre + name + suf) |
| 206 | try: |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 207 | fd = _os.open(file, flags, 0o600) |
Martin v. Löwis | d662548 | 2003-10-12 17:37:01 +0000 | [diff] [blame] | 208 | return (fd, _os.path.abspath(file)) |
Florent Xicluna | 68f71a3 | 2011-10-28 16:06:23 +0200 | [diff] [blame] | 209 | except FileExistsError: |
| 210 | continue # try again |
Eli Bendersky | f315df3 | 2013-09-06 06:11:19 -0700 | [diff] [blame] | 211 | except PermissionError: |
| 212 | # This exception is thrown when a directory with the chosen name |
| 213 | # already exists on windows. |
Serhiy Storchaka | 5d6b7b1 | 2015-05-20 00:11:48 +0300 | [diff] [blame] | 214 | if (_os.name == 'nt' and _os.path.isdir(dir) and |
| 215 | _os.access(dir, _os.W_OK)): |
Eli Bendersky | f315df3 | 2013-09-06 06:11:19 -0700 | [diff] [blame] | 216 | continue |
| 217 | else: |
| 218 | raise |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 219 | |
Serhiy Storchaka | 7451a72 | 2013-02-09 22:25:49 +0200 | [diff] [blame] | 220 | raise FileExistsError(_errno.EEXIST, |
| 221 | "No usable temporary file name found") |
Tim Peters | a0d55de | 2002-08-09 18:01:01 +0000 | [diff] [blame] | 222 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 223 | |
| 224 | # User visible interfaces. |
Guido van Rossum | b0e5718 | 1998-10-14 20:27:05 +0000 | [diff] [blame] | 225 | |
Guido van Rossum | 41f9503 | 1992-03-31 19:02:01 +0000 | [diff] [blame] | 226 | def gettempprefix(): |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 227 | """Accessor for tempdir.template.""" |
| 228 | return template |
Tim Peters | 9fadfb0 | 2001-01-13 03:04:02 +0000 | [diff] [blame] | 229 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 230 | tempdir = None |
| 231 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 232 | def gettempdir(): |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 233 | """Accessor for tempfile.tempdir.""" |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 234 | global tempdir |
| 235 | if tempdir is None: |
| 236 | _once_lock.acquire() |
| 237 | try: |
| 238 | if tempdir is None: |
| 239 | tempdir = _get_default_tempdir() |
| 240 | finally: |
| 241 | _once_lock.release() |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 242 | return tempdir |
| 243 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 244 | def mkstemp(suffix="", prefix=template, dir=None, text=False): |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 245 | """User-callable function to create and return a unique temporary |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 246 | file. The return value is a pair (fd, name) where fd is the |
| 247 | file descriptor returned by os.open, and name is the filename. |
| 248 | |
| 249 | If 'suffix' is specified, the file name will end with that suffix, |
| 250 | otherwise there will be no suffix. |
| 251 | |
| 252 | If 'prefix' is specified, the file name will begin with that prefix, |
| 253 | otherwise a default prefix is used. |
| 254 | |
| 255 | If 'dir' is specified, the file will be created in that directory, |
| 256 | otherwise a default directory is used. |
| 257 | |
Tim Peters | 04490bf | 2002-08-14 15:41:26 +0000 | [diff] [blame] | 258 | If 'text' is specified and true, the file is opened in text |
| 259 | mode. Else (the default) the file is opened in binary mode. On |
| 260 | some operating systems, this makes no difference. |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 261 | |
| 262 | The file is readable and writable only by the creating user ID. |
| 263 | If the operating system uses permission bits to indicate whether a |
| 264 | file is executable, the file is executable by no one. The file |
| 265 | descriptor is not inherited by children of this process. |
| 266 | |
| 267 | Caller is responsible for deleting the file when done with it. |
Tim Peters | 9fadfb0 | 2001-01-13 03:04:02 +0000 | [diff] [blame] | 268 | """ |
| 269 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 270 | if dir is None: |
| 271 | dir = gettempdir() |
| 272 | |
Tim Peters | 04490bf | 2002-08-14 15:41:26 +0000 | [diff] [blame] | 273 | if text: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 274 | flags = _text_openflags |
Tim Peters | 04490bf | 2002-08-14 15:41:26 +0000 | [diff] [blame] | 275 | else: |
| 276 | flags = _bin_openflags |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 277 | |
| 278 | return _mkstemp_inner(dir, prefix, suffix, flags) |
Guido van Rossum | cff3454 | 1992-01-14 18:31:56 +0000 | [diff] [blame] | 279 | |
Guido van Rossum | eee9498 | 1991-11-12 15:38:08 +0000 | [diff] [blame] | 280 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 281 | def mkdtemp(suffix="", prefix=template, dir=None): |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 282 | """User-callable function to create and return a unique temporary |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 283 | directory. The return value is the pathname of the directory. |
| 284 | |
Tim Peters | 04490bf | 2002-08-14 15:41:26 +0000 | [diff] [blame] | 285 | Arguments are as for mkstemp, except that the 'text' argument is |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 286 | not accepted. |
| 287 | |
| 288 | The directory is readable, writable, and searchable only by the |
| 289 | creating user. |
| 290 | |
| 291 | Caller is responsible for deleting the directory when done with it. |
| 292 | """ |
| 293 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 294 | if dir is None: |
| 295 | dir = gettempdir() |
| 296 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 297 | names = _get_candidate_names() |
Tim Peters | a0d55de | 2002-08-09 18:01:01 +0000 | [diff] [blame] | 298 | |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 299 | for seq in range(TMP_MAX): |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 300 | name = next(names) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 301 | file = _os.path.join(dir, prefix + name + suffix) |
| 302 | try: |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 303 | _os.mkdir(file, 0o700) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 304 | return file |
Florent Xicluna | 68f71a3 | 2011-10-28 16:06:23 +0200 | [diff] [blame] | 305 | except FileExistsError: |
| 306 | continue # try again |
Serhiy Storchaka | 5d6b7b1 | 2015-05-20 00:11:48 +0300 | [diff] [blame] | 307 | except PermissionError: |
| 308 | # This exception is thrown when a directory with the chosen name |
| 309 | # already exists on windows. |
| 310 | if (_os.name == 'nt' and _os.path.isdir(dir) and |
| 311 | _os.access(dir, _os.W_OK)): |
| 312 | continue |
| 313 | else: |
| 314 | raise |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 315 | |
Serhiy Storchaka | 7451a72 | 2013-02-09 22:25:49 +0200 | [diff] [blame] | 316 | raise FileExistsError(_errno.EEXIST, |
| 317 | "No usable temporary directory name found") |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 318 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 319 | def mktemp(suffix="", prefix=template, dir=None): |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 320 | """User-callable function to return a unique temporary file name. The |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 321 | file is not created. |
| 322 | |
Tim Peters | 04490bf | 2002-08-14 15:41:26 +0000 | [diff] [blame] | 323 | Arguments are as for mkstemp, except that the 'text' argument is |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 324 | not accepted. |
| 325 | |
| 326 | This function is unsafe and should not be used. The file name |
| 327 | refers to a file that did not exist at some point, but by the time |
| 328 | you get around to creating it, someone else may have beaten you to |
| 329 | the punch. |
| 330 | """ |
| 331 | |
Guido van Rossum | 44f602d | 2002-11-22 15:56:29 +0000 | [diff] [blame] | 332 | ## from warnings import warn as _warn |
| 333 | ## _warn("mktemp is a potential security risk to your program", |
| 334 | ## RuntimeWarning, stacklevel=2) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 335 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 336 | if dir is None: |
| 337 | dir = gettempdir() |
| 338 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 339 | names = _get_candidate_names() |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 340 | for seq in range(TMP_MAX): |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 341 | name = next(names) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 342 | file = _os.path.join(dir, prefix + name + suffix) |
Guido van Rossum | b25615939 | 2003-11-10 02:16:36 +0000 | [diff] [blame] | 343 | if not _exists(file): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 344 | return file |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 345 | |
Serhiy Storchaka | 7451a72 | 2013-02-09 22:25:49 +0200 | [diff] [blame] | 346 | raise FileExistsError(_errno.EEXIST, |
| 347 | "No usable temporary filename found") |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 348 | |
Christian Heimes | 3ecfea71 | 2008-02-09 20:51:34 +0000 | [diff] [blame] | 349 | |
Antoine Pitrou | 17c9326 | 2013-12-21 22:14:56 +0100 | [diff] [blame] | 350 | class _TemporaryFileCloser: |
| 351 | """A separate object allowing proper closing of a temporary file's |
| 352 | underlying file object, without adding a __del__ method to the |
| 353 | temporary file.""" |
Tim Peters | a255a72 | 2001-12-18 22:32:40 +0000 | [diff] [blame] | 354 | |
Serhiy Storchaka | a28632b | 2014-01-27 11:21:54 +0200 | [diff] [blame] | 355 | file = None # Set here since __del__ checks it |
Serhiy Storchaka | 99e033b | 2014-01-27 11:18:27 +0200 | [diff] [blame] | 356 | close_called = False |
| 357 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 358 | def __init__(self, file, name, delete=True): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 359 | self.file = file |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 360 | self.name = name |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 361 | self.delete = delete |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 362 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 363 | # NT provides delete-on-close as a primitive, so we don't need |
| 364 | # the wrapper to do anything special. We still use it so that |
| 365 | # file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile. |
| 366 | if _os.name != 'nt': |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 367 | # Cache the unlinker so we don't get spurious errors at |
| 368 | # shutdown when the module-level "os" is None'd out. Note |
| 369 | # that this must be referenced as self.unlink, because the |
| 370 | # name TemporaryFileWrapper may also get None'd out before |
| 371 | # __del__ is called. |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 372 | |
Serhiy Storchaka | 99e033b | 2014-01-27 11:18:27 +0200 | [diff] [blame] | 373 | def close(self, unlink=_os.unlink): |
| 374 | if not self.close_called and self.file is not None: |
Tim Peters | 6ef966e | 2002-11-21 15:48:33 +0000 | [diff] [blame] | 375 | self.close_called = True |
Serhiy Storchaka | 7e7a3db | 2015-04-10 13:24:41 +0300 | [diff] [blame] | 376 | try: |
| 377 | self.file.close() |
| 378 | finally: |
| 379 | if self.delete: |
| 380 | unlink(self.name) |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 381 | |
Antoine Pitrou | 17c9326 | 2013-12-21 22:14:56 +0100 | [diff] [blame] | 382 | # Need to ensure the file is deleted on __del__ |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 383 | def __del__(self): |
| 384 | self.close() |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 385 | |
Benjamin Peterson | 98d23f2 | 2009-06-30 22:27:25 +0000 | [diff] [blame] | 386 | else: |
Antoine Pitrou | 17c9326 | 2013-12-21 22:14:56 +0100 | [diff] [blame] | 387 | def close(self): |
| 388 | if not self.close_called: |
| 389 | self.close_called = True |
| 390 | self.file.close() |
| 391 | |
| 392 | |
| 393 | class _TemporaryFileWrapper: |
| 394 | """Temporary file wrapper |
| 395 | |
| 396 | This class provides a wrapper around files opened for |
| 397 | temporary use. In particular, it seeks to automatically |
| 398 | remove the file when it is no longer needed. |
| 399 | """ |
| 400 | |
| 401 | def __init__(self, file, name, delete=True): |
| 402 | self.file = file |
| 403 | self.name = name |
| 404 | self.delete = delete |
| 405 | self._closer = _TemporaryFileCloser(file, name, delete) |
| 406 | |
| 407 | def __getattr__(self, name): |
| 408 | # Attribute lookups are delegated to the underlying file |
| 409 | # and cached for non-numeric results |
| 410 | # (i.e. methods are cached, closed and friends are not) |
| 411 | file = self.__dict__['file'] |
| 412 | a = getattr(file, name) |
| 413 | if hasattr(a, '__call__'): |
| 414 | func = a |
| 415 | @_functools.wraps(func) |
| 416 | def func_wrapper(*args, **kwargs): |
| 417 | return func(*args, **kwargs) |
| 418 | # Avoid closing the file as long as the wrapper is alive, |
| 419 | # see issue #18879. |
| 420 | func_wrapper._closer = self._closer |
| 421 | a = func_wrapper |
| 422 | if not isinstance(a, int): |
| 423 | setattr(self, name, a) |
| 424 | return a |
| 425 | |
| 426 | # The underlying __enter__ method returns the wrong object |
| 427 | # (self.file) so override it to return the wrapper |
| 428 | def __enter__(self): |
| 429 | self.file.__enter__() |
| 430 | return self |
| 431 | |
| 432 | # Need to trap __exit__ as well to ensure the file gets |
| 433 | # deleted when used in a with statement |
| 434 | def __exit__(self, exc, value, tb): |
| 435 | result = self.file.__exit__(exc, value, tb) |
| 436 | self.close() |
| 437 | return result |
| 438 | |
| 439 | def close(self): |
| 440 | """ |
| 441 | Close the temporary file, possibly deleting it. |
| 442 | """ |
| 443 | self._closer.close() |
| 444 | |
| 445 | # iter() doesn't use __getattr__ to find the __iter__ method |
| 446 | def __iter__(self): |
Serhiy Storchaka | d83b7c2 | 2015-03-20 16:11:20 +0200 | [diff] [blame] | 447 | # Don't return iter(self.file), but yield from it to avoid closing |
R David Murray | 75ed90a | 2015-03-22 12:33:46 -0400 | [diff] [blame] | 448 | # file as long as it's being used as iterator (see issue #23700). We |
| 449 | # can't use 'yield from' here because iter(file) returns the file |
| 450 | # object itself, which has a close method, and thus the file would get |
| 451 | # closed when the generator is finalized, due to PEP380 semantics. |
Serhiy Storchaka | d83b7c2 | 2015-03-20 16:11:20 +0200 | [diff] [blame] | 452 | for line in self.file: |
| 453 | yield line |
Christian Heimes | 3ecfea71 | 2008-02-09 20:51:34 +0000 | [diff] [blame] | 454 | |
| 455 | |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 456 | def NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None, |
| 457 | newline=None, suffix="", prefix=template, |
| 458 | dir=None, delete=True): |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 459 | """Create and return a temporary file. |
| 460 | Arguments: |
| 461 | 'prefix', 'suffix', 'dir' -- as for mkstemp. |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 462 | 'mode' -- the mode argument to io.open (default "w+b"). |
| 463 | 'buffering' -- the buffer size argument to io.open (default -1). |
| 464 | 'encoding' -- the encoding argument to io.open (default None) |
| 465 | 'newline' -- the newline argument to io.open (default None) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 466 | 'delete' -- whether the file is deleted on close (default True). |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 467 | The file is created as mkstemp() would do it. |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 468 | |
Raymond Hettinger | faa10eb | 2005-01-11 15:33:03 +0000 | [diff] [blame] | 469 | Returns an object with a file-like interface; the name of the file |
| 470 | is accessible as file.name. The file will be automatically deleted |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 471 | when it is closed unless the 'delete' argument is set to False. |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 472 | """ |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 473 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 474 | if dir is None: |
| 475 | dir = gettempdir() |
| 476 | |
Amaury Forgeot d'Arc | 7d0bddd | 2009-11-30 00:08:56 +0000 | [diff] [blame] | 477 | flags = _bin_openflags |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 478 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 479 | # Setting O_TEMPORARY in the flags causes the OS to delete |
| 480 | # the file when it is closed. This is only supported by Windows. |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 481 | if _os.name == 'nt' and delete: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 482 | flags |= _os.O_TEMPORARY |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 483 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 484 | (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags) |
Victor Stinner | 1f99f9d | 2014-03-25 09:18:04 +0100 | [diff] [blame] | 485 | try: |
| 486 | file = _io.open(fd, mode, buffering=buffering, |
| 487 | newline=newline, encoding=encoding) |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 488 | |
Victor Stinner | 1f99f9d | 2014-03-25 09:18:04 +0100 | [diff] [blame] | 489 | return _TemporaryFileWrapper(file, name, delete) |
| 490 | except Exception: |
| 491 | _os.close(fd) |
| 492 | raise |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 493 | |
Jason Tishler | 80c02af | 2002-08-14 15:10:09 +0000 | [diff] [blame] | 494 | if _os.name != 'posix' or _os.sys.platform == 'cygwin': |
| 495 | # On non-POSIX and Cygwin systems, assume that we cannot unlink a file |
| 496 | # while it is open. |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 497 | TemporaryFile = NamedTemporaryFile |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 498 | |
| 499 | else: |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 500 | def TemporaryFile(mode='w+b', buffering=-1, encoding=None, |
| 501 | newline=None, suffix="", prefix=template, |
| 502 | dir=None): |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 503 | """Create and return a temporary file. |
| 504 | Arguments: |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 505 | 'prefix', 'suffix', 'dir' -- as for mkstemp. |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 506 | 'mode' -- the mode argument to io.open (default "w+b"). |
| 507 | 'buffering' -- the buffer size argument to io.open (default -1). |
| 508 | 'encoding' -- the encoding argument to io.open (default None) |
| 509 | 'newline' -- the newline argument to io.open (default None) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 510 | The file is created as mkstemp() would do it. |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 511 | |
Raymond Hettinger | faa10eb | 2005-01-11 15:33:03 +0000 | [diff] [blame] | 512 | Returns an object with a file-like interface. The file has no |
| 513 | name, and will cease to exist when it is closed. |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 514 | """ |
| 515 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 516 | if dir is None: |
| 517 | dir = gettempdir() |
| 518 | |
Amaury Forgeot d'Arc | 7d0bddd | 2009-11-30 00:08:56 +0000 | [diff] [blame] | 519 | flags = _bin_openflags |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 520 | |
| 521 | (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags) |
| 522 | try: |
| 523 | _os.unlink(name) |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 524 | return _io.open(fd, mode, buffering=buffering, |
| 525 | newline=newline, encoding=encoding) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 526 | except: |
| 527 | _os.close(fd) |
| 528 | raise |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 529 | |
| 530 | class SpooledTemporaryFile: |
Serhiy Storchaka | 4f169a7 | 2013-02-09 11:46:42 +0200 | [diff] [blame] | 531 | """Temporary file wrapper, specialized to switch from BytesIO |
| 532 | or StringIO to a real file when it exceeds a certain size or |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 533 | when a fileno is needed. |
| 534 | """ |
| 535 | _rolled = False |
| 536 | |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 537 | def __init__(self, max_size=0, mode='w+b', buffering=-1, |
| 538 | encoding=None, newline=None, |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 539 | suffix="", prefix=template, dir=None): |
Guido van Rossum | 9a63470 | 2007-07-09 10:24:45 +0000 | [diff] [blame] | 540 | if 'b' in mode: |
| 541 | self._file = _io.BytesIO() |
| 542 | else: |
Guido van Rossum | 5d21255 | 2007-10-29 16:42:51 +0000 | [diff] [blame] | 543 | # Setting newline="\n" avoids newline translation; |
| 544 | # this is important because otherwise on Windows we'd |
Yury Selivanov | 3e67d58 | 2014-09-26 17:08:02 -0400 | [diff] [blame] | 545 | # get double newline translation upon rollover(). |
Alexandre Vassalotti | 3ade6f9 | 2008-06-12 01:13:54 +0000 | [diff] [blame] | 546 | self._file = _io.StringIO(newline="\n") |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 547 | self._max_size = max_size |
| 548 | self._rolled = False |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 549 | self._TemporaryFileArgs = {'mode': mode, 'buffering': buffering, |
| 550 | 'suffix': suffix, 'prefix': prefix, |
| 551 | 'encoding': encoding, 'newline': newline, |
| 552 | 'dir': dir} |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 553 | |
| 554 | def _check(self, file): |
| 555 | if self._rolled: return |
| 556 | max_size = self._max_size |
| 557 | if max_size and file.tell() > max_size: |
| 558 | self.rollover() |
| 559 | |
| 560 | def rollover(self): |
| 561 | if self._rolled: return |
| 562 | file = self._file |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 563 | newfile = self._file = TemporaryFile(**self._TemporaryFileArgs) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 564 | del self._TemporaryFileArgs |
| 565 | |
| 566 | newfile.write(file.getvalue()) |
| 567 | newfile.seek(file.tell(), 0) |
| 568 | |
| 569 | self._rolled = True |
| 570 | |
Christian Heimes | 3ecfea71 | 2008-02-09 20:51:34 +0000 | [diff] [blame] | 571 | # The method caching trick from NamedTemporaryFile |
| 572 | # won't work here, because _file may change from a |
Serhiy Storchaka | 50254c5 | 2013-08-29 11:35:43 +0300 | [diff] [blame] | 573 | # BytesIO/StringIO instance to a real file. So we list |
Christian Heimes | 3ecfea71 | 2008-02-09 20:51:34 +0000 | [diff] [blame] | 574 | # all the methods directly. |
| 575 | |
| 576 | # Context management protocol |
| 577 | def __enter__(self): |
| 578 | if self._file.closed: |
| 579 | raise ValueError("Cannot enter context with closed file") |
| 580 | return self |
| 581 | |
| 582 | def __exit__(self, exc, value, tb): |
| 583 | self._file.close() |
| 584 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 585 | # file protocol |
| 586 | def __iter__(self): |
| 587 | return self._file.__iter__() |
| 588 | |
| 589 | def close(self): |
| 590 | self._file.close() |
| 591 | |
| 592 | @property |
| 593 | def closed(self): |
| 594 | return self._file.closed |
| 595 | |
| 596 | @property |
| 597 | def encoding(self): |
Serhiy Storchaka | bbbbe8e | 2013-02-09 12:21:14 +0200 | [diff] [blame] | 598 | try: |
| 599 | return self._file.encoding |
| 600 | except AttributeError: |
| 601 | if 'b' in self._TemporaryFileArgs['mode']: |
| 602 | raise |
| 603 | return self._TemporaryFileArgs['encoding'] |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 604 | |
| 605 | def fileno(self): |
| 606 | self.rollover() |
| 607 | return self._file.fileno() |
| 608 | |
| 609 | def flush(self): |
| 610 | self._file.flush() |
| 611 | |
| 612 | def isatty(self): |
| 613 | return self._file.isatty() |
| 614 | |
| 615 | @property |
| 616 | def mode(self): |
Serhiy Storchaka | bbbbe8e | 2013-02-09 12:21:14 +0200 | [diff] [blame] | 617 | try: |
| 618 | return self._file.mode |
| 619 | except AttributeError: |
| 620 | return self._TemporaryFileArgs['mode'] |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 621 | |
| 622 | @property |
| 623 | def name(self): |
Serhiy Storchaka | bbbbe8e | 2013-02-09 12:21:14 +0200 | [diff] [blame] | 624 | try: |
| 625 | return self._file.name |
| 626 | except AttributeError: |
| 627 | return None |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 628 | |
| 629 | @property |
| 630 | def newlines(self): |
Serhiy Storchaka | bbbbe8e | 2013-02-09 12:21:14 +0200 | [diff] [blame] | 631 | try: |
| 632 | return self._file.newlines |
| 633 | except AttributeError: |
| 634 | if 'b' in self._TemporaryFileArgs['mode']: |
| 635 | raise |
| 636 | return self._TemporaryFileArgs['newline'] |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 637 | |
| 638 | def read(self, *args): |
| 639 | return self._file.read(*args) |
| 640 | |
| 641 | def readline(self, *args): |
| 642 | return self._file.readline(*args) |
| 643 | |
| 644 | def readlines(self, *args): |
| 645 | return self._file.readlines(*args) |
| 646 | |
| 647 | def seek(self, *args): |
| 648 | self._file.seek(*args) |
| 649 | |
| 650 | @property |
| 651 | def softspace(self): |
| 652 | return self._file.softspace |
| 653 | |
| 654 | def tell(self): |
| 655 | return self._file.tell() |
| 656 | |
Antoine Pitrou | 0e86a58 | 2011-11-25 18:03:09 +0100 | [diff] [blame] | 657 | def truncate(self, size=None): |
| 658 | if size is None: |
| 659 | self._file.truncate() |
| 660 | else: |
| 661 | if size > self._max_size: |
| 662 | self.rollover() |
| 663 | self._file.truncate(size) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 664 | |
| 665 | def write(self, s): |
| 666 | file = self._file |
| 667 | rv = file.write(s) |
| 668 | self._check(file) |
| 669 | return rv |
| 670 | |
| 671 | def writelines(self, iterable): |
| 672 | file = self._file |
| 673 | rv = file.writelines(iterable) |
| 674 | self._check(file) |
| 675 | return rv |
| 676 | |
Nick Coghlan | 543af75 | 2010-10-24 11:23:25 +0000 | [diff] [blame] | 677 | |
| 678 | class TemporaryDirectory(object): |
| 679 | """Create and return a temporary directory. This has the same |
| 680 | behavior as mkdtemp but can be used as a context manager. For |
| 681 | example: |
| 682 | |
| 683 | with TemporaryDirectory() as tmpdir: |
| 684 | ... |
| 685 | |
Ezio Melotti | 30b9d5d | 2013-08-17 15:50:46 +0300 | [diff] [blame] | 686 | Upon exiting the context, the directory and everything contained |
Nick Coghlan | 543af75 | 2010-10-24 11:23:25 +0000 | [diff] [blame] | 687 | in it are removed. |
| 688 | """ |
| 689 | |
| 690 | def __init__(self, suffix="", prefix=template, dir=None): |
Nick Coghlan | 6b22f3f | 2010-12-12 15:24:21 +0000 | [diff] [blame] | 691 | self.name = mkdtemp(suffix, prefix, dir) |
Serhiy Storchaka | a28632b | 2014-01-27 11:21:54 +0200 | [diff] [blame] | 692 | self._finalizer = _weakref.finalize( |
| 693 | self, self._cleanup, self.name, |
| 694 | warn_message="Implicitly cleaning up {!r}".format(self)) |
| 695 | |
| 696 | @classmethod |
Serhiy Storchaka | 5e193ac | 2014-09-24 13:26:25 +0300 | [diff] [blame] | 697 | def _cleanup(cls, name, warn_message): |
Serhiy Storchaka | a28632b | 2014-01-27 11:21:54 +0200 | [diff] [blame] | 698 | _shutil.rmtree(name) |
Serhiy Storchaka | 5e193ac | 2014-09-24 13:26:25 +0300 | [diff] [blame] | 699 | _warnings.warn(warn_message, ResourceWarning) |
Serhiy Storchaka | a28632b | 2014-01-27 11:21:54 +0200 | [diff] [blame] | 700 | |
Nick Coghlan | 6b22f3f | 2010-12-12 15:24:21 +0000 | [diff] [blame] | 701 | |
| 702 | def __repr__(self): |
| 703 | return "<{} {!r}>".format(self.__class__.__name__, self.name) |
Nick Coghlan | 543af75 | 2010-10-24 11:23:25 +0000 | [diff] [blame] | 704 | |
| 705 | def __enter__(self): |
| 706 | return self.name |
| 707 | |
Nick Coghlan | 543af75 | 2010-10-24 11:23:25 +0000 | [diff] [blame] | 708 | def __exit__(self, exc, value, tb): |
| 709 | self.cleanup() |
| 710 | |
Serhiy Storchaka | a28632b | 2014-01-27 11:21:54 +0200 | [diff] [blame] | 711 | def cleanup(self): |
Serhiy Storchaka | 5e193ac | 2014-09-24 13:26:25 +0300 | [diff] [blame] | 712 | if self._finalizer.detach(): |
Serhiy Storchaka | a28632b | 2014-01-27 11:21:54 +0200 | [diff] [blame] | 713 | _shutil.rmtree(self.name) |