cpython/Doc/library/tempfile.rst

253 lines
10 KiB
ReStructuredText
Raw Normal View History

2007-08-15 11:28:01 -03:00
:mod:`tempfile` --- Generate temporary files and directories
============================================================
.. sectionauthor:: Zack Weinberg <zack@codesourcery.com>
.. module:: tempfile
:synopsis: Generate temporary files and directories.
.. index::
pair: temporary; file name
pair: temporary; file
This module generates temporary files and directories. It works on all
supported platforms.
In version 2.3 of Python, this module was overhauled for enhanced security. It
now provides three new functions, :func:`NamedTemporaryFile`, :func:`mkstemp`,
and :func:`mkdtemp`, which should eliminate all remaining need to use the
insecure :func:`mktemp` function. Temporary file names created by this module
no longer contain the process ID; instead a string of six random characters is
used.
Also, all the user-callable functions now take additional arguments which
allow direct control over the location and name of temporary files. It is
no longer necessary to use the global *tempdir* and *template* variables.
To maintain backward compatibility, the argument order is somewhat odd; it
is recommended to use keyword arguments for clarity.
2007-08-15 11:28:01 -03:00
The module defines the following user-callable functions:
.. function:: TemporaryFile([mode='w+b'[, bufsize=-1[, suffix=''[, prefix='tmp'[, dir=None]]]]])
2007-08-15 11:28:01 -03:00
Return a file-like object that can be used as a temporary storage area.
The file is created using :func:`mkstemp`. It will be destroyed as soon
2007-08-15 11:28:01 -03:00
as it is closed (including an implicit close when the object is garbage
collected). Under Unix, the directory entry for the file is removed
immediately after the file is created. Other platforms do not support
this; your code should not rely on a temporary file created using this
function having or not having a visible name in the file system.
2007-08-15 11:28:01 -03:00
The *mode* parameter defaults to ``'w+b'`` so that the file created can
be read and written without being closed. Binary mode is used so that it
behaves consistently on all platforms without regard for the data that is
stored. *bufsize* defaults to ``-1``, meaning that the operating system
default is used.
2007-08-15 11:28:01 -03:00
The *dir*, *prefix* and *suffix* parameters are passed to :func:`mkstemp`.
The returned object is a true file object on POSIX platforms. On other
platforms, it is a file-like object whose :attr:`file` attribute is the
underlying true file object. This file-like object can be used in a
:keyword:`with` statement, just like a normal file.
2007-08-15 11:28:01 -03:00
.. function:: NamedTemporaryFile([mode='w+b'[, bufsize=-1[, suffix=''[, prefix='tmp'[, dir=None[, delete=True]]]]]])
2007-08-15 11:28:01 -03:00
This function operates exactly as :func:`TemporaryFile` does, except that
the file is guaranteed to have a visible name in the file system (on
Unix, the directory entry is not unlinked). That name can be retrieved
from the :attr:`name` member of the file object. Whether the name can be
used to open the file a second time, while the named temporary file is
still open, varies across platforms (it can be so used on Unix; it cannot
on Windows NT or later). If *delete* is true (the default), the file is
deleted as soon as it is closed.
2007-08-15 11:28:01 -03:00
The returned object is always a file-like object whose :attr:`file`
attribute is the underlying true file object. This file-like object can
be used in a :keyword:`with` statement, just like a normal file.
2007-08-15 11:28:01 -03:00
.. versionadded:: 2.3
.. versionadded:: 2.6
The *delete* parameter.
.. function:: SpooledTemporaryFile([max_size=0, [mode='w+b'[, bufsize=-1[, suffix=''[, prefix='tmp'[, dir=None]]]]]])
2007-08-15 11:28:01 -03:00
This function operates exactly as :func:`TemporaryFile` does, except that
data is spooled in memory until the file size exceeds *max_size*, or
until the file's :func:`fileno` method is called, at which point the
contents are written to disk and operation proceeds as with
:func:`TemporaryFile`.
2007-08-15 11:28:01 -03:00
The resulting file has one additional method, :func:`rollover`, which
causes the file to roll over to an on-disk file regardless of its size.
2007-08-15 11:28:01 -03:00
The returned object is a file-like object whose :attr:`_file` attribute
is either a :class:`StringIO` object or a true file object, depending on
whether :func:`rollover` has been called. This file-like object can be
used in a :keyword:`with` statement, just like a normal file.
2007-08-15 11:28:01 -03:00
.. versionadded:: 2.6
.. function:: mkstemp([suffix=''[, prefix='tmp'[, dir=None[, text=False]]]])
2007-08-15 11:28:01 -03:00
Creates a temporary file in the most secure manner possible. There are
no race conditions in the file's creation, assuming that the platform
properly implements the :const:`os.O_EXCL` flag for :func:`os.open`. The
file is readable and writable only by the creating user ID. If the
platform uses permission bits to indicate whether a file is executable,
the file is executable by no one. The file descriptor is not inherited
by child processes.
2007-08-15 11:28:01 -03:00
Unlike :func:`TemporaryFile`, the user of :func:`mkstemp` is responsible
for deleting the temporary file when done with it.
2007-08-15 11:28:01 -03:00
If *suffix* is specified, the file name will end with that suffix,
otherwise there will be no suffix. :func:`mkstemp` does not put a dot
between the file name and the suffix; if you need one, put it at the
beginning of *suffix*.
2007-08-15 11:28:01 -03:00
If *prefix* is specified, the file name will begin with that prefix;
otherwise, a default prefix is used.
2007-08-15 11:28:01 -03:00
If *dir* is specified, the file will be created in that directory;
otherwise, a default directory is used. The default directory is chosen
from a platform-dependent list, but the user of the application can
control the directory location by setting the *TMPDIR*, *TEMP* or *TMP*
environment variables. There is thus no guarantee that the generated
filename will have any nice properties, such as not requiring quoting
when passed to external commands via ``os.popen()``.
2007-08-15 11:28:01 -03:00
If *text* is specified, it indicates whether to open the file in binary
mode (the default) or text mode. On some platforms, this makes no
difference.
2007-08-15 11:28:01 -03:00
:func:`mkstemp` returns a tuple containing an OS-level handle to an open
file (as would be returned by :func:`os.open`) and the absolute pathname
of that file, in that order.
2007-08-15 11:28:01 -03:00
.. versionadded:: 2.3
.. function:: mkdtemp([suffix=''[, prefix='tmp'[, dir=None]]])
2007-08-15 11:28:01 -03:00
Creates a temporary directory in the most secure manner possible. There
are no race conditions in the directory's creation. The directory is
readable, writable, and searchable only by the creating user ID.
2007-08-15 11:28:01 -03:00
The user of :func:`mkdtemp` is responsible for deleting the temporary
directory and its contents when done with it.
2007-08-15 11:28:01 -03:00
The *prefix*, *suffix*, and *dir* arguments are the same as for
:func:`mkstemp`.
2007-08-15 11:28:01 -03:00
:func:`mkdtemp` returns the absolute pathname of the new directory.
.. versionadded:: 2.3
.. function:: mktemp([suffix=''[, prefix='tmp'[, dir=None]]])
2007-08-15 11:28:01 -03:00
.. deprecated:: 2.3
Use :func:`mkstemp` instead.
Return an absolute pathname of a file that did not exist at the time the
call is made. The *prefix*, *suffix*, and *dir* arguments are the same
as for :func:`mkstemp`.
2007-08-15 11:28:01 -03:00
.. warning::
Use of this function may introduce a security hole in your program.
By the time you get around to doing anything with the file name it
returns, someone else may have beaten you to the punch.
:func:`mktemp` usage can be replaced easily with
2008-05-08 21:50:40 -03:00
:func:`NamedTemporaryFile`, passing it the `delete=False` parameter::
>>> f = NamedTemporaryFile(delete=False)
>>> f
<open file '<fdopen>', mode 'w+b' at 0x384698>
>>> f.name
'/var/folders/5q/5qTPn6xq2RaWqk+1Ytw3-U+++TI/-Tmp-/tmpG7V1Y0'
>>> f.write("Hello World!\n")
>>> f.close()
>>> os.unlink(f.name)
>>> os.path.exists(f.name)
False
2007-08-15 11:28:01 -03:00
The module uses two global variables that tell it how to construct a
temporary name. They are initialized at the first call to any of the
functions above. The caller may change them, but this is discouraged; use
the appropriate function arguments, instead.
2007-08-15 11:28:01 -03:00
.. data:: tempdir
When set to a value other than ``None``, this variable defines the
default value for the *dir* argument to all the functions defined in this
module.
2007-08-15 11:28:01 -03:00
If ``tempdir`` is unset or ``None`` at any call to any of the above
functions, Python searches a standard list of directories and sets
*tempdir* to the first one which the calling user can create files in.
The list is:
2007-08-15 11:28:01 -03:00
#. The directory named by the :envvar:`TMPDIR` environment variable.
#. The directory named by the :envvar:`TEMP` environment variable.
#. The directory named by the :envvar:`TMP` environment variable.
#. A platform-specific location:
* On RiscOS, the directory named by the :envvar:`Wimp$ScrapDir` environment
variable.
* On Windows, the directories :file:`C:\\TEMP`, :file:`C:\\TMP`,
:file:`\\TEMP`, and :file:`\\TMP`, in that order.
* On all other platforms, the directories :file:`/tmp`, :file:`/var/tmp`, and
:file:`/usr/tmp`, in that order.
#. As a last resort, the current working directory.
.. function:: gettempdir()
Return the directory currently selected to create temporary files in. If
:data:`tempdir` is not ``None``, this simply returns its contents; otherwise,
the search described above is performed, and the result returned.
Merged revisions 66801,66803-66804,66813,66854-66856,66866,66870-66872,66874,66887,66903,66905,66911,66913,66927,66932,66938,66942,66962,66964,66973-66974,66977,66992,66998-66999,67002,67005,67007,67028,67040-67041,67044,67070,67089,67091,67101,67117-67119,67123-67124 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ................ r66801 | andrew.kuchling | 2008-10-04 23:51:59 +0200 (Sat, 04 Oct 2008) | 1 line Punctuation fix; expand dict.update docstring to be clearer ................ r66803 | benjamin.peterson | 2008-10-05 00:15:31 +0200 (Sun, 05 Oct 2008) | 1 line fix typo ................ r66804 | andrew.kuchling | 2008-10-05 02:11:56 +0200 (Sun, 05 Oct 2008) | 1 line #1415508 from Rocky Bernstein: add docstrings for enable_interspersed_args(), disable_interspersed_args() ................ r66813 | andrew.kuchling | 2008-10-06 14:07:04 +0200 (Mon, 06 Oct 2008) | 3 lines Per Greg Ward, optparse is no longer being externally maintained. I'll look at the bugs in the Optik bug tracker and copy them to the Python bug tracker if they're still relevant. ................ r66854 | georg.brandl | 2008-10-08 19:20:20 +0200 (Wed, 08 Oct 2008) | 2 lines #4059: patch up some sqlite docs. ................ r66855 | georg.brandl | 2008-10-08 19:30:55 +0200 (Wed, 08 Oct 2008) | 2 lines #4058: fix some whatsnew markup. ................ r66856 | georg.brandl | 2008-10-08 20:47:17 +0200 (Wed, 08 Oct 2008) | 3 lines #3935: properly support list subclasses in the C impl. of bisect. Patch reviewed by Raymond. ................ r66866 | benjamin.peterson | 2008-10-09 22:54:43 +0200 (Thu, 09 Oct 2008) | 1 line update paragraph about __future__ for 2.6 ................ r66870 | armin.rigo | 2008-10-10 10:40:44 +0200 (Fri, 10 Oct 2008) | 2 lines Typo: "ThreadError" is the name in the C source. ................ r66871 | benjamin.peterson | 2008-10-10 22:38:49 +0200 (Fri, 10 Oct 2008) | 1 line fix a small typo ................ r66872 | benjamin.peterson | 2008-10-10 22:51:37 +0200 (Fri, 10 Oct 2008) | 1 line talk about how you can unzip with zip ................ r66874 | benjamin.peterson | 2008-10-11 00:23:41 +0200 (Sat, 11 Oct 2008) | 1 line PyGILState_Acquire -> PyGILState_Ensure ................ r66887 | benjamin.peterson | 2008-10-13 23:51:40 +0200 (Mon, 13 Oct 2008) | 1 line document how to disable fixers ................ r66903 | benjamin.peterson | 2008-10-15 22:34:09 +0200 (Wed, 15 Oct 2008) | 1 line don't recurse into directories that start with '.' ................ r66905 | benjamin.peterson | 2008-10-15 23:05:55 +0200 (Wed, 15 Oct 2008) | 1 line support the optional line argument for idle ................ r66911 | benjamin.peterson | 2008-10-16 01:10:28 +0200 (Thu, 16 Oct 2008) | 41 lines Merged revisions 66805,66841,66860,66884-66886,66893,66907,66910 via svnmerge from svn+ssh://pythondev@svn.python.org/sandbox/trunk/2to3/lib2to3 ........ r66805 | benjamin.peterson | 2008-10-04 20:11:02 -0500 (Sat, 04 Oct 2008) | 1 line mention what the fixes directory is for ........ r66841 | benjamin.peterson | 2008-10-07 17:48:12 -0500 (Tue, 07 Oct 2008) | 1 line use assertFalse and assertTrue ........ r66860 | benjamin.peterson | 2008-10-08 16:05:07 -0500 (Wed, 08 Oct 2008) | 1 line instead of abusing the pattern matcher, use start_tree to find a next binding ........ r66884 | benjamin.peterson | 2008-10-13 15:50:30 -0500 (Mon, 13 Oct 2008) | 1 line don't print tokens to stdout when -v is given ........ r66885 | benjamin.peterson | 2008-10-13 16:28:57 -0500 (Mon, 13 Oct 2008) | 1 line add the -x option to disable fixers ........ r66886 | benjamin.peterson | 2008-10-13 16:33:53 -0500 (Mon, 13 Oct 2008) | 1 line cut down on some crud ........ r66893 | benjamin.peterson | 2008-10-14 17:16:54 -0500 (Tue, 14 Oct 2008) | 1 line add an optional set literal fixer ........ r66907 | benjamin.peterson | 2008-10-15 16:59:41 -0500 (Wed, 15 Oct 2008) | 1 line don't write backup files by default ........ r66910 | benjamin.peterson | 2008-10-15 17:43:10 -0500 (Wed, 15 Oct 2008) | 1 line add the -n option; it stops backupfiles from being written ........ ................ r66913 | benjamin.peterson | 2008-10-16 20:52:14 +0200 (Thu, 16 Oct 2008) | 1 line document that deque indexing is O(n) #4123 ................ r66927 | andrew.kuchling | 2008-10-16 22:15:47 +0200 (Thu, 16 Oct 2008) | 1 line Fix wording (2.6.1 backport candidate) ................ r66932 | benjamin.peterson | 2008-10-16 23:09:28 +0200 (Thu, 16 Oct 2008) | 1 line check for error conditions in _json #3623 ................ r66938 | benjamin.peterson | 2008-10-16 23:27:54 +0200 (Thu, 16 Oct 2008) | 1 line fix possible ref leak ................ r66942 | benjamin.peterson | 2008-10-16 23:48:06 +0200 (Thu, 16 Oct 2008) | 1 line fix more possible ref leaks in _json and use Py_CLEAR ................ r66962 | benjamin.peterson | 2008-10-17 22:01:01 +0200 (Fri, 17 Oct 2008) | 1 line clarify CALL_FUNCTION #4141 ................ r66964 | georg.brandl | 2008-10-17 23:41:49 +0200 (Fri, 17 Oct 2008) | 2 lines Fix duplicate word. ................ r66973 | armin.ronacher | 2008-10-19 10:27:43 +0200 (Sun, 19 Oct 2008) | 3 lines Fixed #4067 by implementing _attributes and _fields for the AST root node. ................ r66974 | benjamin.peterson | 2008-10-19 15:59:01 +0200 (Sun, 19 Oct 2008) | 1 line fix compiler warning ................ r66977 | benjamin.peterson | 2008-10-19 21:39:16 +0200 (Sun, 19 Oct 2008) | 1 line mention -n ................ r66992 | benjamin.peterson | 2008-10-21 22:51:13 +0200 (Tue, 21 Oct 2008) | 1 line make sure to call iteritems() ................ r66998 | benjamin.peterson | 2008-10-22 22:57:43 +0200 (Wed, 22 Oct 2008) | 1 line fix a few typos ................ r66999 | benjamin.peterson | 2008-10-22 23:05:30 +0200 (Wed, 22 Oct 2008) | 1 line and another typo... ................ r67002 | hirokazu.yamamoto | 2008-10-23 02:37:33 +0200 (Thu, 23 Oct 2008) | 1 line Issue #4183: Some tests didn't run with pickle.HIGHEST_PROTOCOL. ................ r67005 | walter.doerwald | 2008-10-23 15:11:39 +0200 (Thu, 23 Oct 2008) | 2 lines Use the correct names of the stateless codec functions (Fixes issue 4178). ................ r67007 | benjamin.peterson | 2008-10-23 23:43:48 +0200 (Thu, 23 Oct 2008) | 1 line only nonempty __slots__ don't work ................ r67028 | benjamin.peterson | 2008-10-26 01:27:07 +0200 (Sun, 26 Oct 2008) | 1 line don't use a catch-all ................ r67040 | armin.rigo | 2008-10-28 18:01:21 +0100 (Tue, 28 Oct 2008) | 5 lines Fix one of the tests: it relied on being present in an "output test" in order to actually test what it was supposed to test, i.e. that the code in the __del__ method did not crash. Use instead the new helper test_support.captured_output(). ................ r67041 | benjamin.peterson | 2008-10-29 21:33:00 +0100 (Wed, 29 Oct 2008) | 1 line mention the version gettempdir() was added ................ r67044 | amaury.forgeotdarc | 2008-10-30 00:15:57 +0100 (Thu, 30 Oct 2008) | 3 lines Correct error message in io.open(): closefd=True is the only accepted value with a file name. ................ r67070 | benjamin.peterson | 2008-10-31 21:41:44 +0100 (Fri, 31 Oct 2008) | 1 line rephrase has_key doc ................ r67089 | benjamin.peterson | 2008-11-03 21:43:20 +0100 (Mon, 03 Nov 2008) | 1 line clarify by splitting into multiple paragraphs ................ r67091 | benjamin.peterson | 2008-11-03 23:34:57 +0100 (Mon, 03 Nov 2008) | 1 line move a FileIO test to test_fileio ................ r67101 | georg.brandl | 2008-11-04 21:49:35 +0100 (Tue, 04 Nov 2008) | 2 lines #4167: fix markup glitches. ................ r67117 | georg.brandl | 2008-11-06 11:17:58 +0100 (Thu, 06 Nov 2008) | 2 lines #4268: Use correct module for two toplevel functions. ................ r67118 | georg.brandl | 2008-11-06 11:19:11 +0100 (Thu, 06 Nov 2008) | 2 lines #4267: small fixes in sqlite3 docs. ................ r67119 | georg.brandl | 2008-11-06 11:20:49 +0100 (Thu, 06 Nov 2008) | 2 lines #4245: move Thread section to the top. ................ r67123 | georg.brandl | 2008-11-06 19:49:15 +0100 (Thu, 06 Nov 2008) | 2 lines #4247: add "pass" examples to tutorial. ................ r67124 | andrew.kuchling | 2008-11-06 20:23:02 +0100 (Thu, 06 Nov 2008) | 1 line Fix grammar error; reword two paragraphs ................
2008-11-07 04:56:27 -04:00
.. versionadded:: 2.3
2007-08-15 11:28:01 -03:00
.. data:: template
.. deprecated:: 2.0
Use :func:`gettempprefix` instead.
When set to a value other than ``None``, this variable defines the prefix of the
final component of the filenames returned by :func:`mktemp`. A string of six
random letters and digits is appended to the prefix to make the filename unique.
2008-08-04 04:23:29 -03:00
The default prefix is :file:`tmp`.
2007-08-15 11:28:01 -03:00
Older versions of this module used to require that ``template`` be set to
``None`` after a call to :func:`os.fork`; this has not been necessary since
version 1.5.2.
.. function:: gettempprefix()
Return the filename prefix used to create temporary files. This does not
contain the directory component. Using this function is preferred over reading
the *template* variable directly.
.. versionadded:: 1.5.2