"tempfile" --- 一時ファイルやディレクトリの作成
***********************************************

**ソースコード:** Lib/tempfile.py

======================================================================

This module creates temporary files and directories.  It works on all
supported platforms. "TemporaryFile", "NamedTemporaryFile",
"TemporaryDirectory", and "SpooledTemporaryFile" are high-level
interfaces which provide automatic cleanup and can be used as *context
managers*. "mkstemp()" and "mkdtemp()" are lower-level functions which
require manual cleanup.

ユーザが呼び出し可能な全ての関数とコンストラクタは追加の引数を受け取り
ます。 その引数によって一時ファイルやディレクトリの場所と名前を直接操
作することが出来ます。 このモジュールに使用されるファイル名はランダム
な文字を含みます。そのためファイルは共有された一時ディレクトリに安全に
作成されます。 後方互換性を保つために引数の順序は若干奇妙です。 分かり
やすさのためにキーワード引数を使用してください。

このモジュールではユーザが呼び出し可能な以下の項目を定義しています:

tempfile.TemporaryFile(mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, *, errors=None)

   一時的な記憶領域として使うことの出来る *file-like object* を返しま
   す。 ファイルは "mkstemp()" と同じルールにより安全に作成されます。
   オブジェクトは閉じられる (オブジェクトのガベージコレクションによる
   暗黙的なものも含みます) とすぐに破壊されます。 Unix では、そのファ
   イルのディレクトリエントリは全く作成されないか、ファイル作成後すぐ
   に削除されます。 これは他のプラットフォームではサポートされません。
   よって、この関数で作成された一時ファイルがファイルシステムで可視な
   名前を持つかどうかをコードで当てにすべきではありません。

   The resulting object can be used as a *context manager* (see 使用例
   ).  On completion of the context or destruction of the file object
   the temporary file will be removed from the filesystem.

   作成されたファイルを閉じることなく読み書きできるように、 *mode* 引
   数のデフォルトは "'w+b'" です。 保存されるデータに関わらず全てのプ
   ラットフォーム上で一貫して動作するようにバイナリモードが使用されま
   す。 *buffering*、*encoding*、*errors*、*newline* は、 "open()" に
   対する引数として解釈されます。

   *dir*、*prefix*、*suffix* 引数の意味とデフォルトは "mkstemp()" のも
   のと同じです。

   返されたオブジェクトは、POSIXプラットフォームでは本物のファイルオブ
   ジェクトです。 それ以外のプラットフォームでは、"file" 属性が下層の
   本物のファイルであるファイル様オブジェクトです。

   The "os.O_TMPFILE" flag is used if it is available and works
   (Linux-specific, requires Linux kernel 3.11 or later).

   On platforms that are neither Posix nor Cygwin, TemporaryFile is an
   alias for NamedTemporaryFile.

   引数 "fullpath" を指定して 監査イベント "tempfile.mkstemp" を送出し
   ます。

   バージョン 3.5 で変更: The "os.O_TMPFILE" flag is now used if
   available.

   バージョン 3.8 で変更: *errors* 引数が追加されました。

tempfile.NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, delete=True, *, errors=None, delete_on_close=True)

   This function operates exactly as "TemporaryFile()" does, except
   the following differences:

   * This function returns a file that is guaranteed to have a visible
     name in the file system.

   * To manage the named file, it extends the parameters of
     "TemporaryFile()" with *delete* and *delete_on_close* parameters
     that determine whether and how the named file should be
     automatically deleted.

   The returned object is always a *file-like object* whose "file"
   attribute is the underlying true file object. This file-like object
   can be used in a "with" statement, just like a normal file.  The
   name of the temporary file can be retrieved from the "name"
   attribute of the returned file-like object. On Unix, unlike with
   the "TemporaryFile()", the directory entry does not get unlinked
   immediately after the file creation.

   If *delete* is true (the default) and *delete_on_close* is true
   (the default), the file is deleted as soon as it is closed. If
   *delete* is true and *delete_on_close* is false, the file is
   deleted on context manager exit only, or else when the *file-like
   object* is finalized. Deletion is not always guaranteed in this
   case (see "object.__del__()"). If *delete* is false, the value of
   *delete_on_close* is ignored.

   Therefore to use the name of the temporary file to reopen the file
   after closing it, either make sure not to delete the file upon
   closure (set the *delete* parameter to be false) or, in case the
   temporary file is created in a "with" statement, set the
   *delete_on_close* parameter to be false. The latter approach is
   recommended as it provides assistance in automatic cleaning of the
   temporary file upon the context manager exit.

   Opening the temporary file again by its name while it is still open
   works as follows:

   * On POSIX the file can always be opened again.

   * On Windows, make sure that at least one of the following
     conditions are fulfilled:

     * *delete* is false

     * additional open shares delete access (e.g. by calling
       "os.open()" with the flag "O_TEMPORARY")

     * *delete* is true but *delete_on_close* is false. Note, that in
       this case the additional opens that do not share delete access
       (e.g. created via builtin "open()") must be closed before
       exiting the context manager, else the "os.unlink()" call on
       context manager exit will fail with a "PermissionError".

   On Windows, if *delete_on_close* is false, and the file is created
   in a directory for which the user lacks delete access, then the
   "os.unlink()" call on exit of the context manager will fail with a
   "PermissionError". This cannot happen when *delete_on_close* is
   true because delete access is requested by the open, which fails
   immediately if the requested access is not granted.

   On POSIX (only), a process that is terminated abruptly with SIGKILL
   cannot automatically delete any NamedTemporaryFiles it created.

   引数 "fullpath" を指定して 監査イベント "tempfile.mkstemp" を送出し
   ます。

   バージョン 3.8 で変更: *errors* 引数が追加されました。

   バージョン 3.12 で変更: Added *delete_on_close* parameter.

class tempfile.SpooledTemporaryFile(max_size=0, mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, *, errors=None)

   This class operates exactly as "TemporaryFile()" does, except that
   data is spooled in memory until the file size exceeds *max_size*,
   or until the file's "fileno()" method is called, at which point the
   contents are written to disk and operation proceeds as with
   "TemporaryFile()".

   rollover()

      The resulting file has one additional method, "rollover()",
      which causes the file to roll over to an on-disk file regardless
      of its size.

   The returned object is a file-like object whose "_file" attribute
   is either an "io.BytesIO" or "io.TextIOWrapper" object (depending
   on whether binary or text *mode* was specified) or a true file
   object, depending on whether "rollover()" has been called.  This
   file-like object can be used in a "with" statement, just like a
   normal file.

   バージョン 3.3 で変更: the truncate method now accepts a *size*
   argument.

   バージョン 3.8 で変更: *errors* 引数が追加されました。

   バージョン 3.11 で変更: Fully implements the "io.BufferedIOBase"
   and "io.TextIOBase" abstract base classes (depending on whether
   binary or text *mode* was specified).

class tempfile.TemporaryDirectory(suffix=None, prefix=None, dir=None, ignore_cleanup_errors=False, *, delete=True)

   This class securely creates a temporary directory using the same
   rules as "mkdtemp()". The resulting object can be used as a
   *context manager* (see 使用例).  On completion of the context or
   destruction of the temporary directory object, the newly created
   temporary directory and all its contents are removed from the
   filesystem.

   name

      The directory name can be retrieved from the "name" attribute of
      the returned object.  When the returned object is used as a
      *context manager*, the "name" will be assigned to the target of
      the "as" clause in the "with" statement, if there is one.

   cleanup()

      The directory can be explicitly cleaned up by calling the
      "cleanup()" method. If *ignore_cleanup_errors* is true, any
      unhandled exceptions during explicit or implicit cleanup (such
      as a "PermissionError" removing open files on Windows) will be
      ignored, and the remaining removable items deleted on a "best-
      effort" basis. Otherwise, errors will be raised in whatever
      context cleanup occurs (the "cleanup()" call, exiting the
      context manager, when the object is garbage-collected or during
      interpreter shutdown).

   The *delete* parameter can be used to disable cleanup of the
   directory tree upon exiting the context.  While it may seem unusual
   for a context manager to disable the action taken when exiting the
   context, it can be useful during debugging or when you need your
   cleanup behavior to be conditional based on other logic.

   引数 "fullpath" を指定して 監査イベント "tempfile.mkdtemp" を送出し
   ます。

   Added in version 3.2.

   バージョン 3.10 で変更: *ignore_cleanup_errors* 引数が追加されまし
   た。

   バージョン 3.12 で変更: Added the *delete* parameter.

tempfile.mkstemp(suffix=None, prefix=None, dir=None, text=False)

   可能な限り最も安全な手段で一時ファイルを生成します。 プラットフォー
   ムが "os.open()" の "os.O_EXCL" フラグを正しく実装している限り、フ
   ァイルの作成で競合が起こることはありません。 作成したユーザのユーザ
   ID からのみファイルを読み書き出来ます。 プラットフォームがファイル
   が実行可能かどうかを示す許可ビットを使用している場合、ファイルは誰
   からも実行不可です。 このファイルのファイル記述子は子プロセスに継承
   されません。

   "TemporaryFile()" と違って、 "mkstemp()" のユーザは用済みになった時
   に一時ファイルを削除しなければなりません。

   *suffix* が "None" でない場合、ファイル名はその接尾辞で終わります。
   そうでない場合、接尾辞はありません。 "mkstemp()" はファイル名と接尾
   辞の間にドットを追加しません。 必要であれば *suffix* の先頭につけて
   ください。

   *prefix* が "None" でない場合、ファイル名はその接頭辞で始まります。
   そうでない場合、デフォルトの接頭辞が使われます。 必要に応じ、デフォ
   ルトは "gettempprefix()" または "gettempprefixb()" の返り値です。

   *dir* が "None" でない場合、ファイルはそのディレクトリ下に作成され
   ます。 "None" の場合、デフォルトのディレクトリが使われます。デフォ
   ルトのディレクトリはプラットフォームに依存するリストから選ばれます
   が、アプリケーションのユーザは *TMPDIR*、*TEMP*、または *TMP* 環境
   変数を設定することでディレクトリの場所を管理することができます。そ
   のため、生成されるファイル名が、"os.popen()" で外部コマンドにクォー
   ティング無しで渡すことができるなどといった、扱いやすい性質を持つ保
   証はありません。

   *suffix*、*prefix*、*dir* のいずれかが "None" でない場合、それらは
   同じ型でなければなりません。 bytes の場合、返された名前は str でな
   はく bytes です。 他の挙動はデフォルトで返り値を bytes に強制的にし
   たい場合は "suffix=b''" を渡してください。

   *text* に真を指定した場合は、ファイルはテキストモードで開かれます。
   そうでない場合(デフォルト)は、ファイルはバイナリモードで開かれます
   。

   "mkstemp()" は開かれたファイルを扱うための OS レベルのハンドル
   ("os.open()" が返すものと同じ) とファイルの絶対パス名が順番に並んだ
   タプルを返します。

   引数 "fullpath" を指定して 監査イベント "tempfile.mkstemp" を送出し
   ます。

   バージョン 3.5 で変更: *suffix*、*prefix*、*dir* は bytes の返り値
   を得るために bytes で渡すことが出来ます。 それ以前は str のみ許され
   ていました。 適切なデフォルト値を使用するよう、*suffix* と *prefix*
   は "None" を受け入れ、デフォルトにするようになりました。

   バージョン 3.6 で変更: *dir* パラメタが *path-like object* を受け付
   けるようになりました。

tempfile.mkdtemp(suffix=None, prefix=None, dir=None)

   可能な限り安全な方法で一時ディレクトリを作成します。 ディレクトリの
   生成で競合は発生しません。 ディレクトリを作成したユーザ ID だけが、
   このディレクトリに対して内容を読み出したり、書き込んだり、検索した
   りすることができます。

   "mkdtemp()" のユーザは用済みになった時に一時ディレクトリとその中身
   を削除しなければなりません。

   *prefix*, *suffix*, *dir* 引数は "mkstemp()" 関数のものと同じです。

   "mkdtemp()" は新たに生成されたディレクトリの絶対パス名を返します。

   引数 "fullpath" を指定して 監査イベント "tempfile.mkdtemp" を送出し
   ます。

   バージョン 3.5 で変更: *suffix*、*prefix*、*dir* は bytes の返り値
   を得るために bytes で渡すことが出来ます。 それ以前は str のみ許され
   ていました。 適切なデフォルト値を使用するよう、*suffix* と *prefix*
   は "None" を受け入れ、デフォルトにするようになりました。

   バージョン 3.6 で変更: *dir* パラメタが *path-like object* を受け付
   けるようになりました。

   バージョン 3.12 で変更: "mkdtemp()" now always returns an absolute
   path, even if *dir* is relative.

tempfile.gettempdir()

   一時ファイルに用いられるディレクトリの名前を返します。 これはモジュ
   ール内の全ての関数の *dir* 引数のデフォルト値を定義します。

   Python は呼び出したユーザがファイルを作ることの出来るディレクトリを
   検索するのに標準的なリストを使用します。 そのリストは:

   1. 環境変数 "TMPDIR" で与えられているディレクトリ名。

   2. 環境変数 "TEMP" で与えられているディレクトリ名。

   3. 環境変数 "TMP" で与えられているディレクトリ名。

   4. プラットフォーム依存の場所:

      * Windows ではディレクトリ "C:\TEMP" 、 "C:\TMP" 、 "\TEMP" 、お
        よび "\TMP" の順。

      * その他の全てのプラットフォームでは、 "/tmp" 、 "/var/tmp" 、お
        よび "/usr/tmp" の順。

   5. 最後の手段として、現在の作業ディレクトリ。

   この検索の結果はキャッシュされます。以下の "tempdir" の記述を参照し
   てください。

   バージョン 3.10 で変更: Always returns a str.  Previously it would
   return any "tempdir" value regardless of type so long as it was not
   "None".

tempfile.gettempdirb()

   "gettempdir()" と同じですが返り値は bytesです。

   Added in version 3.5.

tempfile.gettempprefix()

   一時ファイルを生成する際に使われるファイル名の接頭辞を返します。 こ
   れにはディレクトリ部は含まれません。

tempfile.gettempprefixb()

   "gettempprefix()" と同じですが返り値は bytes です。

   Added in version 3.5.

The module uses a global variable to store the name of the directory
used for temporary files returned by "gettempdir()".  It can be set
directly to override the selection process, but this is discouraged.
All functions in this module take a *dir* argument which can be used
to specify the directory. This is the recommended approach that does
not surprise other unsuspecting code by changing global API behavior.

tempfile.tempdir

   When set to a value other than "None", this variable defines the
   default value for the *dir* argument to the functions defined in
   this module, including its type, bytes or str.  It cannot be a
   *path-like object*.

   "tempdir" が (デフォルトの) "None" の場合、 "gettempprefix()" を除
   く上記のいずれかの関数を呼び出す際は常に "gettempdir()" で述べられ
   ているアルゴリズムによって初期化されます。

   注釈:

     Beware that if you set "tempdir" to a bytes value, there is a
     nasty side effect: The global default return type of "mkstemp()"
     and "mkdtemp()" changes to bytes when no explicit "prefix",
     "suffix", or "dir" arguments of type str are supplied. Please do
     not write code expecting or depending on this. This awkward
     behavior is maintained for compatibility with the historical
     implementation.


使用例
======

"tempfile" モジュールの典型的な使用法のいくつかの例を挙げます:

   >>> import tempfile

   # create a temporary file and write some data to it
   >>> fp = tempfile.TemporaryFile()
   >>> fp.write(b'Hello world!')
   # read data from file
   >>> fp.seek(0)
   >>> fp.read()
   b'Hello world!'
   # close the file, it will be removed
   >>> fp.close()

   # create a temporary file using a context manager
   >>> with tempfile.TemporaryFile() as fp:
   ...     fp.write(b'Hello world!')
   ...     fp.seek(0)
   ...     fp.read()
   b'Hello world!'
   >>>
   # file is now closed and removed

   # create a temporary file using a context manager
   # close the file, use the name to open the file again
   >>> with tempfile.NamedTemporaryFile(delete_on_close=False) as fp:
   ...     fp.write(b'Hello world!')
   ...     fp.close()
   ... # the file is closed, but not removed
   ... # open the file again by using its name
   ...     with open(fp.name, mode='rb') as f:
   ...         f.read()
   b'Hello world!'
   >>>
   # file is now removed

   # create a temporary directory using the context manager
   >>> with tempfile.TemporaryDirectory() as tmpdirname:
   ...     print('created temporary directory', tmpdirname)
   >>>
   # directory and contents have been removed


非推奨の関数と変数
==================

一時ファイルを作成する歴史的な手法は、まず "mktemp()" 関数でファイル名
を作り、その名前を使ってファイルを作成するというものでした。 残念なが
らこの方法は安全ではありません。 なぜなら、"mktemp()" の呼び出しと最初
のプロセスが続いてファイル作成を試みる間に、異なるプロセスがその名前で
ファイルを同時に作成するかもしれないからです。 解決策は二つのステップ
を同時に行い、ファイルをすぐに作成するというものです。 この方法は
"mkstemp()" や上述している他の関数で使用されています。

tempfile.mktemp(suffix='', prefix='tmp', dir=None)

   バージョン 2.3 で非推奨: 代わりに "mkstemp()" を使って下さい。

   呼び出し時には存在しなかった、ファイルの絶対パス名を返します。
   *prefix*、*suffix*、*dir* 引数は "mkstemp()" のものと似ていますが、
   bytes のファイル名、"suffix=None"、そして "prefix=None" がサポート
   されていない点で異なります。

   警告:

     この関数を使うとプログラムのセキュリティホールになる可能性があり
     ます。この関数がファイル名を返した後、あなたがそのファイル名を使
     って次に何かをしようとする段階に至る前に、誰か他の人間があなたを
     出し抜くことができてしまいます。 "mktemp()" の利用は、
     "NamedTemporaryFile()" に "delete=False" 引数を渡すことで、簡単に
     置き換えることができます:

        >>> f = NamedTemporaryFile(delete=False)
        >>> f.name
        '/tmp/tmptjujjt'
        >>> f.write(b"Hello World!\n")
        13
        >>> f.close()
        >>> os.unlink(f.name)
        >>> os.path.exists(f.name)
        False
