[2] | 1 | :mod:`tempfile` --- Generate temporary files and directories
|
---|
| 2 | ============================================================
|
---|
| 3 |
|
---|
| 4 | .. sectionauthor:: Zack Weinberg <zack@codesourcery.com>
|
---|
| 5 |
|
---|
| 6 |
|
---|
| 7 | .. module:: tempfile
|
---|
| 8 | :synopsis: Generate temporary files and directories.
|
---|
| 9 |
|
---|
| 10 |
|
---|
| 11 | .. index::
|
---|
| 12 | pair: temporary; file name
|
---|
| 13 | pair: temporary; file
|
---|
| 14 |
|
---|
[391] | 15 | **Source code:** :source:`Lib/tempfile.py`
|
---|
| 16 |
|
---|
| 17 | --------------
|
---|
| 18 |
|
---|
[2] | 19 | This module generates temporary files and directories. It works on all
|
---|
| 20 | supported platforms.
|
---|
| 21 |
|
---|
| 22 | In version 2.3 of Python, this module was overhauled for enhanced security. It
|
---|
| 23 | now provides three new functions, :func:`NamedTemporaryFile`, :func:`mkstemp`,
|
---|
| 24 | and :func:`mkdtemp`, which should eliminate all remaining need to use the
|
---|
| 25 | insecure :func:`mktemp` function. Temporary file names created by this module
|
---|
| 26 | no longer contain the process ID; instead a string of six random characters is
|
---|
| 27 | used.
|
---|
| 28 |
|
---|
| 29 | Also, all the user-callable functions now take additional arguments which
|
---|
| 30 | allow direct control over the location and name of temporary files. It is
|
---|
| 31 | no longer necessary to use the global *tempdir* and *template* variables.
|
---|
| 32 | To maintain backward compatibility, the argument order is somewhat odd; it
|
---|
| 33 | is recommended to use keyword arguments for clarity.
|
---|
| 34 |
|
---|
| 35 | The module defines the following user-callable functions:
|
---|
| 36 |
|
---|
| 37 |
|
---|
| 38 | .. function:: TemporaryFile([mode='w+b'[, bufsize=-1[, suffix=''[, prefix='tmp'[, dir=None]]]]])
|
---|
| 39 |
|
---|
| 40 | Return a file-like object that can be used as a temporary storage area.
|
---|
| 41 | The file is created using :func:`mkstemp`. It will be destroyed as soon
|
---|
| 42 | as it is closed (including an implicit close when the object is garbage
|
---|
| 43 | collected). Under Unix, the directory entry for the file is removed
|
---|
| 44 | immediately after the file is created. Other platforms do not support
|
---|
| 45 | this; your code should not rely on a temporary file created using this
|
---|
| 46 | function having or not having a visible name in the file system.
|
---|
| 47 |
|
---|
| 48 | The *mode* parameter defaults to ``'w+b'`` so that the file created can
|
---|
| 49 | be read and written without being closed. Binary mode is used so that it
|
---|
| 50 | behaves consistently on all platforms without regard for the data that is
|
---|
| 51 | stored. *bufsize* defaults to ``-1``, meaning that the operating system
|
---|
| 52 | default is used.
|
---|
| 53 |
|
---|
| 54 | The *dir*, *prefix* and *suffix* parameters are passed to :func:`mkstemp`.
|
---|
| 55 |
|
---|
| 56 | The returned object is a true file object on POSIX platforms. On other
|
---|
| 57 | platforms, it is a file-like object whose :attr:`!file` attribute is the
|
---|
| 58 | underlying true file object. This file-like object can be used in a
|
---|
| 59 | :keyword:`with` statement, just like a normal file.
|
---|
| 60 |
|
---|
| 61 |
|
---|
| 62 | .. function:: NamedTemporaryFile([mode='w+b'[, bufsize=-1[, suffix=''[, prefix='tmp'[, dir=None[, delete=True]]]]]])
|
---|
| 63 |
|
---|
| 64 | This function operates exactly as :func:`TemporaryFile` does, except that
|
---|
| 65 | the file is guaranteed to have a visible name in the file system (on
|
---|
| 66 | Unix, the directory entry is not unlinked). That name can be retrieved
|
---|
[391] | 67 | from the :attr:`name` attribute of the file object. Whether the name can be
|
---|
[2] | 68 | used to open the file a second time, while the named temporary file is
|
---|
| 69 | still open, varies across platforms (it can be so used on Unix; it cannot
|
---|
| 70 | on Windows NT or later). If *delete* is true (the default), the file is
|
---|
| 71 | deleted as soon as it is closed.
|
---|
| 72 |
|
---|
| 73 | The returned object is always a file-like object whose :attr:`!file`
|
---|
| 74 | attribute is the underlying true file object. This file-like object can
|
---|
| 75 | be used in a :keyword:`with` statement, just like a normal file.
|
---|
| 76 |
|
---|
| 77 | .. versionadded:: 2.3
|
---|
| 78 |
|
---|
| 79 | .. versionadded:: 2.6
|
---|
| 80 | The *delete* parameter.
|
---|
| 81 |
|
---|
| 82 |
|
---|
| 83 | .. function:: SpooledTemporaryFile([max_size=0, [mode='w+b'[, bufsize=-1[, suffix=''[, prefix='tmp'[, dir=None]]]]]])
|
---|
| 84 |
|
---|
| 85 | This function operates exactly as :func:`TemporaryFile` does, except that
|
---|
| 86 | data is spooled in memory until the file size exceeds *max_size*, or
|
---|
| 87 | until the file's :func:`fileno` method is called, at which point the
|
---|
| 88 | contents are written to disk and operation proceeds as with
|
---|
[391] | 89 | :func:`TemporaryFile`. Also, it's ``truncate`` method does not
|
---|
| 90 | accept a ``size`` argument.
|
---|
[2] | 91 |
|
---|
| 92 | The resulting file has one additional method, :func:`rollover`, which
|
---|
| 93 | causes the file to roll over to an on-disk file regardless of its size.
|
---|
| 94 |
|
---|
| 95 | The returned object is a file-like object whose :attr:`_file` attribute
|
---|
[391] | 96 | is either a :class:`~StringIO.StringIO` object or a true file object, depending on
|
---|
[2] | 97 | whether :func:`rollover` has been called. This file-like object can be
|
---|
| 98 | used in a :keyword:`with` statement, just like a normal file.
|
---|
| 99 |
|
---|
| 100 | .. versionadded:: 2.6
|
---|
| 101 |
|
---|
| 102 |
|
---|
| 103 | .. function:: mkstemp([suffix=''[, prefix='tmp'[, dir=None[, text=False]]]])
|
---|
| 104 |
|
---|
| 105 | Creates a temporary file in the most secure manner possible. There are
|
---|
| 106 | no race conditions in the file's creation, assuming that the platform
|
---|
| 107 | properly implements the :const:`os.O_EXCL` flag for :func:`os.open`. The
|
---|
| 108 | file is readable and writable only by the creating user ID. If the
|
---|
| 109 | platform uses permission bits to indicate whether a file is executable,
|
---|
| 110 | the file is executable by no one. The file descriptor is not inherited
|
---|
| 111 | by child processes.
|
---|
| 112 |
|
---|
| 113 | Unlike :func:`TemporaryFile`, the user of :func:`mkstemp` is responsible
|
---|
| 114 | for deleting the temporary file when done with it.
|
---|
| 115 |
|
---|
| 116 | If *suffix* is specified, the file name will end with that suffix,
|
---|
| 117 | otherwise there will be no suffix. :func:`mkstemp` does not put a dot
|
---|
| 118 | between the file name and the suffix; if you need one, put it at the
|
---|
| 119 | beginning of *suffix*.
|
---|
| 120 |
|
---|
| 121 | If *prefix* is specified, the file name will begin with that prefix;
|
---|
| 122 | otherwise, a default prefix is used.
|
---|
| 123 |
|
---|
| 124 | If *dir* is specified, the file will be created in that directory;
|
---|
| 125 | otherwise, a default directory is used. The default directory is chosen
|
---|
| 126 | from a platform-dependent list, but the user of the application can
|
---|
| 127 | control the directory location by setting the *TMPDIR*, *TEMP* or *TMP*
|
---|
| 128 | environment variables. There is thus no guarantee that the generated
|
---|
| 129 | filename will have any nice properties, such as not requiring quoting
|
---|
| 130 | when passed to external commands via ``os.popen()``.
|
---|
| 131 |
|
---|
| 132 | If *text* is specified, it indicates whether to open the file in binary
|
---|
| 133 | mode (the default) or text mode. On some platforms, this makes no
|
---|
| 134 | difference.
|
---|
| 135 |
|
---|
| 136 | :func:`mkstemp` returns a tuple containing an OS-level handle to an open
|
---|
| 137 | file (as would be returned by :func:`os.open`) and the absolute pathname
|
---|
| 138 | of that file, in that order.
|
---|
| 139 |
|
---|
| 140 | .. versionadded:: 2.3
|
---|
| 141 |
|
---|
| 142 |
|
---|
| 143 | .. function:: mkdtemp([suffix=''[, prefix='tmp'[, dir=None]]])
|
---|
| 144 |
|
---|
| 145 | Creates a temporary directory in the most secure manner possible. There
|
---|
| 146 | are no race conditions in the directory's creation. The directory is
|
---|
| 147 | readable, writable, and searchable only by the creating user ID.
|
---|
| 148 |
|
---|
| 149 | The user of :func:`mkdtemp` is responsible for deleting the temporary
|
---|
| 150 | directory and its contents when done with it.
|
---|
| 151 |
|
---|
| 152 | The *prefix*, *suffix*, and *dir* arguments are the same as for
|
---|
| 153 | :func:`mkstemp`.
|
---|
| 154 |
|
---|
| 155 | :func:`mkdtemp` returns the absolute pathname of the new directory.
|
---|
| 156 |
|
---|
| 157 | .. versionadded:: 2.3
|
---|
| 158 |
|
---|
| 159 |
|
---|
| 160 | .. function:: mktemp([suffix=''[, prefix='tmp'[, dir=None]]])
|
---|
| 161 |
|
---|
| 162 | .. deprecated:: 2.3
|
---|
| 163 | Use :func:`mkstemp` instead.
|
---|
| 164 |
|
---|
| 165 | Return an absolute pathname of a file that did not exist at the time the
|
---|
| 166 | call is made. The *prefix*, *suffix*, and *dir* arguments are the same
|
---|
| 167 | as for :func:`mkstemp`.
|
---|
| 168 |
|
---|
| 169 | .. warning::
|
---|
| 170 |
|
---|
| 171 | Use of this function may introduce a security hole in your program. By
|
---|
| 172 | the time you get around to doing anything with the file name it returns,
|
---|
| 173 | someone else may have beaten you to the punch. :func:`mktemp` usage can
|
---|
| 174 | be replaced easily with :func:`NamedTemporaryFile`, passing it the
|
---|
| 175 | ``delete=False`` parameter::
|
---|
| 176 |
|
---|
| 177 | >>> f = NamedTemporaryFile(delete=False)
|
---|
| 178 | >>> f
|
---|
| 179 | <open file '<fdopen>', mode 'w+b' at 0x384698>
|
---|
| 180 | >>> f.name
|
---|
| 181 | '/var/folders/5q/5qTPn6xq2RaWqk+1Ytw3-U+++TI/-Tmp-/tmpG7V1Y0'
|
---|
| 182 | >>> f.write("Hello World!\n")
|
---|
| 183 | >>> f.close()
|
---|
| 184 | >>> os.unlink(f.name)
|
---|
| 185 | >>> os.path.exists(f.name)
|
---|
| 186 | False
|
---|
| 187 |
|
---|
| 188 | The module uses two global variables that tell it how to construct a
|
---|
| 189 | temporary name. They are initialized at the first call to any of the
|
---|
| 190 | functions above. The caller may change them, but this is discouraged; use
|
---|
| 191 | the appropriate function arguments, instead.
|
---|
| 192 |
|
---|
| 193 |
|
---|
| 194 | .. data:: tempdir
|
---|
| 195 |
|
---|
| 196 | When set to a value other than ``None``, this variable defines the
|
---|
| 197 | default value for the *dir* argument to all the functions defined in this
|
---|
| 198 | module.
|
---|
| 199 |
|
---|
| 200 | If ``tempdir`` is unset or ``None`` at any call to any of the above
|
---|
| 201 | functions, Python searches a standard list of directories and sets
|
---|
| 202 | *tempdir* to the first one which the calling user can create files in.
|
---|
| 203 | The list is:
|
---|
| 204 |
|
---|
| 205 | #. The directory named by the :envvar:`TMPDIR` environment variable.
|
---|
| 206 |
|
---|
| 207 | #. The directory named by the :envvar:`TEMP` environment variable.
|
---|
| 208 |
|
---|
| 209 | #. The directory named by the :envvar:`TMP` environment variable.
|
---|
| 210 |
|
---|
| 211 | #. A platform-specific location:
|
---|
| 212 |
|
---|
| 213 | * On RiscOS, the directory named by the :envvar:`Wimp$ScrapDir` environment
|
---|
| 214 | variable.
|
---|
| 215 |
|
---|
| 216 | * On Windows, the directories :file:`C:\\TEMP`, :file:`C:\\TMP`,
|
---|
| 217 | :file:`\\TEMP`, and :file:`\\TMP`, in that order.
|
---|
| 218 |
|
---|
| 219 | * On all other platforms, the directories :file:`/tmp`, :file:`/var/tmp`, and
|
---|
| 220 | :file:`/usr/tmp`, in that order.
|
---|
| 221 |
|
---|
| 222 | #. As a last resort, the current working directory.
|
---|
| 223 |
|
---|
| 224 |
|
---|
| 225 | .. function:: gettempdir()
|
---|
| 226 |
|
---|
| 227 | Return the directory currently selected to create temporary files in. If
|
---|
| 228 | :data:`tempdir` is not ``None``, this simply returns its contents; otherwise,
|
---|
| 229 | the search described above is performed, and the result returned.
|
---|
| 230 |
|
---|
| 231 | .. versionadded:: 2.3
|
---|
| 232 |
|
---|
| 233 |
|
---|
| 234 | .. data:: template
|
---|
| 235 |
|
---|
| 236 | .. deprecated:: 2.0
|
---|
| 237 | Use :func:`gettempprefix` instead.
|
---|
| 238 |
|
---|
| 239 | When set to a value other than ``None``, this variable defines the prefix of the
|
---|
| 240 | final component of the filenames returned by :func:`mktemp`. A string of six
|
---|
| 241 | random letters and digits is appended to the prefix to make the filename unique.
|
---|
| 242 | The default prefix is :file:`tmp`.
|
---|
| 243 |
|
---|
| 244 | Older versions of this module used to require that ``template`` be set to
|
---|
| 245 | ``None`` after a call to :func:`os.fork`; this has not been necessary since
|
---|
| 246 | version 1.5.2.
|
---|
| 247 |
|
---|
| 248 |
|
---|
| 249 | .. function:: gettempprefix()
|
---|
| 250 |
|
---|
| 251 | Return the filename prefix used to create temporary files. This does not
|
---|
| 252 | contain the directory component. Using this function is preferred over reading
|
---|
| 253 | the *template* variable directly.
|
---|
| 254 |
|
---|
| 255 | .. versionadded:: 1.5.2
|
---|
| 256 |
|
---|