Secure temporary file

From Rosetta Code
Revision as of 20:53, 22 October 2007 by rosettacode>JimD (New page: {{Task}} Create a temporary file, '''securely and exclusively''' (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other...)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Task
Secure temporary file
You are encouraged to solve this task according to the task description, using any language you may know.

Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria). The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).


Python

Interpreter: Python 2.3 and later

import tempfile
tfile = tempfile.TemporaryFile()
   # Will be "anonymous" under UNIX-like systems
   # Implicitly uses $TMPDIR from UNIX/Linux or %TEMP for MS Windows, etc.
tfilen = tempfile.NamedTemporaryFile()
   # Will be automatically unlinked (removed) on tfilen.close()
   # (use os.link() to preserve temporary file contents after close())
print tfile.name   # Somthing like: /tmp/tmpXXXXXX --- with random alphanumerics for XXXXXX
mytf = tempfile.NamedTemporaryFile(dir="/some/special/directory", prefix="myTempFile", suffix="TMP")
   # "keyword arguments" can over-ride default location and other aspects of temporary file creation

Note: prior to version 2.3 programmers had to use their own calls to tempfile.mkstemp() and os.open() (with special flags and other options) in order to correctly avoid race conditions. The programmer was also responsible for removing the file (possibly in a try: .... finally block or using the atexit module to register the actions to occur as part of the normal interpreter shutdown.