/Doc/library/tempfile.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 252 lines · 173 code · 79 blank · 0 comment · 0 complexity · d264f7be51994e722f4045c26dd23a32 MD5 · raw file

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