blob: 014d673ea807a2e8f7240cc95971809ea7405414 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001: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
15This module generates temporary files and directories. It works on all
Georg Brandle6bcc912008-05-12 18:05:20 +000016supported platforms. It provides three new functions,
17:func:`NamedTemporaryFile`, :func:`mkstemp`, and :func:`mkdtemp`, which should
18eliminate all remaining need to use the insecure :func:`mktemp` function.
19Temporary file names created by this module no longer contain the process ID;
20instead a string of six random characters is used.
Georg Brandl116aa622007-08-15 14:28:22 +000021
Christian Heimes81ee3ef2008-05-04 22:42:01 +000022Also, all the user-callable functions now take additional arguments which
23allow direct control over the location and name of temporary files. It is
24no longer necessary to use the global *tempdir* and *template* variables.
25To maintain backward compatibility, the argument order is somewhat odd; it
26is recommended to use keyword arguments for clarity.
Georg Brandl116aa622007-08-15 14:28:22 +000027
28The module defines the following user-callable functions:
29
30
Georg Brandl7f01a132009-09-16 15:58:14 +000031.. function:: TemporaryFile(mode='w+b', bufsize=-1, suffix='', prefix='tmp', dir=None)
Georg Brandl116aa622007-08-15 14:28:22 +000032
Christian Heimes81ee3ef2008-05-04 22:42:01 +000033 Return a file-like object that can be used as a temporary storage area.
34 The file is created using :func:`mkstemp`. It will be destroyed as soon
Georg Brandl116aa622007-08-15 14:28:22 +000035 as it is closed (including an implicit close when the object is garbage
Christian Heimes81ee3ef2008-05-04 22:42:01 +000036 collected). Under Unix, the directory entry for the file is removed
37 immediately after the file is created. Other platforms do not support
38 this; your code should not rely on a temporary file created using this
39 function having or not having a visible name in the file system.
Georg Brandl116aa622007-08-15 14:28:22 +000040
Christian Heimes81ee3ef2008-05-04 22:42:01 +000041 The *mode* parameter defaults to ``'w+b'`` so that the file created can
42 be read and written without being closed. Binary mode is used so that it
43 behaves consistently on all platforms without regard for the data that is
44 stored. *bufsize* defaults to ``-1``, meaning that the operating system
45 default is used.
Georg Brandl116aa622007-08-15 14:28:22 +000046
47 The *dir*, *prefix* and *suffix* parameters are passed to :func:`mkstemp`.
48
Christian Heimes7f044312008-01-06 17:05:40 +000049 The returned object is a true file object on POSIX platforms. On other
Georg Brandl502d9a52009-07-26 15:02:41 +000050 platforms, it is a file-like object whose :attr:`!file` attribute is the
Christian Heimes81ee3ef2008-05-04 22:42:01 +000051 underlying true file object. This file-like object can be used in a
Christian Heimes3ecfea712008-02-09 20:51:34 +000052 :keyword:`with` statement, just like a normal file.
Christian Heimes7f044312008-01-06 17:05:40 +000053
Georg Brandl116aa622007-08-15 14:28:22 +000054
Georg Brandl7f01a132009-09-16 15:58:14 +000055.. function:: NamedTemporaryFile(mode='w+b', bufsize=-1, suffix='', prefix='tmp', dir=None, delete=True)
Georg Brandl116aa622007-08-15 14:28:22 +000056
Christian Heimes81ee3ef2008-05-04 22:42:01 +000057 This function operates exactly as :func:`TemporaryFile` does, except that
58 the file is guaranteed to have a visible name in the file system (on
59 Unix, the directory entry is not unlinked). That name can be retrieved
60 from the :attr:`name` member of the file object. Whether the name can be
61 used to open the file a second time, while the named temporary file is
62 still open, varies across platforms (it can be so used on Unix; it cannot
63 on Windows NT or later). If *delete* is true (the default), the file is
64 deleted as soon as it is closed.
Georg Brandl502d9a52009-07-26 15:02:41 +000065 The returned object is always a file-like object whose :attr:`!file`
Christian Heimes81ee3ef2008-05-04 22:42:01 +000066 attribute is the underlying true file object. This file-like object can
67 be used in a :keyword:`with` statement, just like a normal file.
Georg Brandl116aa622007-08-15 14:28:22 +000068
Georg Brandl116aa622007-08-15 14:28:22 +000069
Georg Brandl7f01a132009-09-16 15:58:14 +000070.. function:: SpooledTemporaryFile(max_size=0, mode='w+b', bufsize=-1, suffix='', prefix='tmp', dir=None)
Georg Brandl116aa622007-08-15 14:28:22 +000071
Christian Heimes81ee3ef2008-05-04 22:42:01 +000072 This function operates exactly as :func:`TemporaryFile` does, except that
73 data is spooled in memory until the file size exceeds *max_size*, or
74 until the file's :func:`fileno` method is called, at which point the
75 contents are written to disk and operation proceeds as with
76 :func:`TemporaryFile`.
Georg Brandl116aa622007-08-15 14:28:22 +000077
Christian Heimes81ee3ef2008-05-04 22:42:01 +000078 The resulting file has one additional method, :func:`rollover`, which
79 causes the file to roll over to an on-disk file regardless of its size.
Georg Brandl116aa622007-08-15 14:28:22 +000080
Christian Heimes81ee3ef2008-05-04 22:42:01 +000081 The returned object is a file-like object whose :attr:`_file` attribute
82 is either a :class:`StringIO` object or a true file object, depending on
83 whether :func:`rollover` has been called. This file-like object can be
84 used in a :keyword:`with` statement, just like a normal file.
85
86
Georg Brandl7f01a132009-09-16 15:58:14 +000087.. function:: mkstemp(suffix='', prefix='tmp', dir=None, text=False)
Christian Heimes81ee3ef2008-05-04 22:42:01 +000088
89 Creates a temporary file in the most secure manner possible. There are
90 no race conditions in the file's creation, assuming that the platform
91 properly implements the :const:`os.O_EXCL` flag for :func:`os.open`. The
92 file is readable and writable only by the creating user ID. If the
93 platform uses permission bits to indicate whether a file is executable,
94 the file is executable by no one. The file descriptor is not inherited
95 by child processes.
96
97 Unlike :func:`TemporaryFile`, the user of :func:`mkstemp` is responsible
98 for deleting the temporary file when done with it.
99
100 If *suffix* is specified, the file name will end with that suffix,
101 otherwise there will be no suffix. :func:`mkstemp` does not put a dot
102 between the file name and the suffix; if you need one, put it at the
103 beginning of *suffix*.
104
105 If *prefix* is specified, the file name will begin with that prefix;
106 otherwise, a default prefix is used.
107
108 If *dir* is specified, the file will be created in that directory;
109 otherwise, a default directory is used. The default directory is chosen
110 from a platform-dependent list, but the user of the application can
111 control the directory location by setting the *TMPDIR*, *TEMP* or *TMP*
112 environment variables. There is thus no guarantee that the generated
113 filename will have any nice properties, such as not requiring quoting
114 when passed to external commands via ``os.popen()``.
115
116 If *text* is specified, it indicates whether to open the file in binary
117 mode (the default) or text mode. On some platforms, this makes no
118 difference.
119
120 :func:`mkstemp` returns a tuple containing an OS-level handle to an open
121 file (as would be returned by :func:`os.open`) and the absolute pathname
122 of that file, in that order.
123
124
Georg Brandl7f01a132009-09-16 15:58:14 +0000125.. function:: mkdtemp(suffix='', prefix='tmp', dir=None)
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000126
127 Creates a temporary directory in the most secure manner possible. There
128 are no race conditions in the directory's creation. The directory is
129 readable, writable, and searchable only by the creating user ID.
130
131 The user of :func:`mkdtemp` is responsible for deleting the temporary
132 directory and its contents when done with it.
133
134 The *prefix*, *suffix*, and *dir* arguments are the same as for
135 :func:`mkstemp`.
Georg Brandl116aa622007-08-15 14:28:22 +0000136
137 :func:`mkdtemp` returns the absolute pathname of the new directory.
138
Georg Brandl116aa622007-08-15 14:28:22 +0000139
Georg Brandl7f01a132009-09-16 15:58:14 +0000140.. function:: mktemp(suffix='', prefix='tmp', dir=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000141
142 .. deprecated:: 2.3
143 Use :func:`mkstemp` instead.
144
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000145 Return an absolute pathname of a file that did not exist at the time the
146 call is made. The *prefix*, *suffix*, and *dir* arguments are the same
147 as for :func:`mkstemp`.
Georg Brandl116aa622007-08-15 14:28:22 +0000148
149 .. warning::
150
Georg Brandl36ab1ef2009-01-03 21:17:04 +0000151 Use of this function may introduce a security hole in your program. By
152 the time you get around to doing anything with the file name it returns,
153 someone else may have beaten you to the punch. :func:`mktemp` usage can
154 be replaced easily with :func:`NamedTemporaryFile`, passing it the
155 ``delete=False`` parameter::
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000156
157 >>> f = NamedTemporaryFile(delete=False)
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000158 >>> f
159 <open file '<fdopen>', mode 'w+b' at 0x384698>
160 >>> f.name
161 '/var/folders/5q/5qTPn6xq2RaWqk+1Ytw3-U+++TI/-Tmp-/tmpG7V1Y0'
162 >>> f.write("Hello World!\n")
163 >>> f.close()
164 >>> os.unlink(f.name)
165 >>> os.path.exists(f.name)
166 False
Georg Brandl116aa622007-08-15 14:28:22 +0000167
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000168The module uses two global variables that tell it how to construct a
169temporary name. They are initialized at the first call to any of the
170functions above. The caller may change them, but this is discouraged; use
171the appropriate function arguments, instead.
Georg Brandl116aa622007-08-15 14:28:22 +0000172
173
174.. data:: tempdir
175
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000176 When set to a value other than ``None``, this variable defines the
177 default value for the *dir* argument to all the functions defined in this
178 module.
Georg Brandl116aa622007-08-15 14:28:22 +0000179
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000180 If ``tempdir`` is unset or ``None`` at any call to any of the above
181 functions, Python searches a standard list of directories and sets
182 *tempdir* to the first one which the calling user can create files in.
183 The list is:
Georg Brandl116aa622007-08-15 14:28:22 +0000184
185 #. The directory named by the :envvar:`TMPDIR` environment variable.
186
187 #. The directory named by the :envvar:`TEMP` environment variable.
188
189 #. The directory named by the :envvar:`TMP` environment variable.
190
191 #. A platform-specific location:
192
Georg Brandl116aa622007-08-15 14:28:22 +0000193 * On Windows, the directories :file:`C:\\TEMP`, :file:`C:\\TMP`,
194 :file:`\\TEMP`, and :file:`\\TMP`, in that order.
195
196 * On all other platforms, the directories :file:`/tmp`, :file:`/var/tmp`, and
197 :file:`/usr/tmp`, in that order.
198
199 #. As a last resort, the current working directory.
200
201
202.. function:: gettempdir()
203
204 Return the directory currently selected to create temporary files in. If
205 :data:`tempdir` is not ``None``, this simply returns its contents; otherwise,
206 the search described above is performed, and the result returned.
207
208
Georg Brandl116aa622007-08-15 14:28:22 +0000209.. function:: gettempprefix()
210
211 Return the filename prefix used to create temporary files. This does not
Georg Brandl4b26ff82008-08-04 07:24:52 +0000212 contain the directory component.
Georg Brandl116aa622007-08-15 14:28:22 +0000213