tempfile.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. """Temporary files.
  2. This module provides generic, low- and high-level interfaces for
  3. creating temporary files and directories. The interfaces listed
  4. as "safe" just below can be used without fear of race conditions.
  5. Those listed as "unsafe" cannot, and are provided for backward
  6. compatibility only.
  7. This module also provides some data items to the user:
  8. TMP_MAX - maximum number of names that will be tried before
  9. giving up.
  10. template - the default prefix for all temporary names.
  11. You may change this to control the default prefix.
  12. tempdir - If this is set to a string before the first use of
  13. any routine from this module, it will be considered as
  14. another candidate location to store temporary files.
  15. """
  16. __all__ = [
  17. "NamedTemporaryFile", "TemporaryFile", # high level safe interfaces
  18. "mkstemp", "mkdtemp", # low level safe interfaces
  19. "mktemp", # deprecated unsafe interface
  20. "TMP_MAX", "gettempprefix", # constants
  21. "tempdir", "gettempdir"
  22. ]
  23. # Imports.
  24. import os as _os
  25. import errno as _errno
  26. from random import Random as _Random
  27. if _os.name == 'mac':
  28. import Carbon.Folder as _Folder
  29. import Carbon.Folders as _Folders
  30. try:
  31. import fcntl as _fcntl
  32. except ImportError:
  33. def _set_cloexec(fd):
  34. pass
  35. else:
  36. def _set_cloexec(fd):
  37. try:
  38. flags = _fcntl.fcntl(fd, _fcntl.F_GETFD, 0)
  39. except IOError:
  40. pass
  41. else:
  42. # flags read successfully, modify
  43. flags |= _fcntl.FD_CLOEXEC
  44. _fcntl.fcntl(fd, _fcntl.F_SETFD, flags)
  45. try:
  46. import thread as _thread
  47. except ImportError:
  48. import dummy_thread as _thread
  49. _allocate_lock = _thread.allocate_lock
  50. _text_openflags = _os.O_RDWR | _os.O_CREAT | _os.O_EXCL
  51. if hasattr(_os, 'O_NOINHERIT'):
  52. _text_openflags |= _os.O_NOINHERIT
  53. if hasattr(_os, 'O_NOFOLLOW'):
  54. _text_openflags |= _os.O_NOFOLLOW
  55. _bin_openflags = _text_openflags
  56. if hasattr(_os, 'O_BINARY'):
  57. _bin_openflags |= _os.O_BINARY
  58. if hasattr(_os, 'TMP_MAX'):
  59. TMP_MAX = _os.TMP_MAX
  60. else:
  61. TMP_MAX = 10000
  62. template = "tmp"
  63. tempdir = None
  64. # Internal routines.
  65. _once_lock = _allocate_lock()
  66. if hasattr(_os, "lstat"):
  67. _stat = _os.lstat
  68. elif hasattr(_os, "stat"):
  69. _stat = _os.stat
  70. else:
  71. # Fallback. All we need is something that raises os.error if the
  72. # file doesn't exist.
  73. def _stat(fn):
  74. try:
  75. f = open(fn)
  76. except IOError:
  77. raise _os.error
  78. f.close()
  79. def _exists(fn):
  80. try:
  81. _stat(fn)
  82. except _os.error:
  83. return False
  84. else:
  85. return True
  86. class _RandomNameSequence:
  87. """An instance of _RandomNameSequence generates an endless
  88. sequence of unpredictable strings which can safely be incorporated
  89. into file names. Each string is six characters long. Multiple
  90. threads can safely use the same instance at the same time.
  91. _RandomNameSequence is an iterator."""
  92. characters = ("abcdefghijklmnopqrstuvwxyz" +
  93. "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
  94. "0123456789-_")
  95. def __init__(self):
  96. self.mutex = _allocate_lock()
  97. self.rng = _Random()
  98. self.normcase = _os.path.normcase
  99. def __iter__(self):
  100. return self
  101. def next(self):
  102. m = self.mutex
  103. c = self.characters
  104. choose = self.rng.choice
  105. m.acquire()
  106. try:
  107. letters = [choose(c) for dummy in "123456"]
  108. finally:
  109. m.release()
  110. return self.normcase(''.join(letters))
  111. def _candidate_tempdir_list():
  112. """Generate a list of candidate temporary directories which
  113. _get_default_tempdir will try."""
  114. dirlist = []
  115. # First, try the environment.
  116. for envname in 'TMPDIR', 'TEMP', 'TMP':
  117. dirname = _os.getenv(envname)
  118. if dirname: dirlist.append(dirname)
  119. # Failing that, try OS-specific locations.
  120. if _os.name == 'mac':
  121. try:
  122. fsr = _Folder.FSFindFolder(_Folders.kOnSystemDisk,
  123. _Folders.kTemporaryFolderType, 1)
  124. dirname = fsr.as_pathname()
  125. dirlist.append(dirname)
  126. except _Folder.error:
  127. pass
  128. elif _os.name == 'riscos':
  129. dirname = _os.getenv('Wimp$ScrapDir')
  130. if dirname: dirlist.append(dirname)
  131. elif _os.name == 'nt':
  132. dirlist.extend([ r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ])
  133. else:
  134. dirlist.extend([ '/tmp', '/var/tmp', '/usr/tmp' ])
  135. # As a last resort, the current directory.
  136. try:
  137. dirlist.append(_os.getcwd())
  138. except (AttributeError, _os.error):
  139. dirlist.append(_os.curdir)
  140. return dirlist
  141. def _get_default_tempdir():
  142. """Calculate the default directory to use for temporary files.
  143. This routine should be called exactly once.
  144. We determine whether or not a candidate temp dir is usable by
  145. trying to create and write to a file in that directory. If this
  146. is successful, the test file is deleted. To prevent denial of
  147. service, the name of the test file must be randomized."""
  148. namer = _RandomNameSequence()
  149. dirlist = _candidate_tempdir_list()
  150. flags = _text_openflags
  151. for dir in dirlist:
  152. if dir != _os.curdir:
  153. dir = _os.path.normcase(_os.path.abspath(dir))
  154. # Try only a few names per directory.
  155. for seq in xrange(100):
  156. name = namer.next()
  157. filename = _os.path.join(dir, name)
  158. try:
  159. fd = _os.open(filename, flags, 0600)
  160. fp = _os.fdopen(fd, 'w')
  161. fp.write('blat')
  162. fp.close()
  163. _os.unlink(filename)
  164. del fp, fd
  165. return dir
  166. except (OSError, IOError), e:
  167. if e[0] != _errno.EEXIST:
  168. break # no point trying more names in this directory
  169. pass
  170. raise IOError, (_errno.ENOENT,
  171. ("No usable temporary directory found in %s" % dirlist))
  172. _name_sequence = None
  173. def _get_candidate_names():
  174. """Common setup sequence for all user-callable interfaces."""
  175. global _name_sequence
  176. if _name_sequence is None:
  177. _once_lock.acquire()
  178. try:
  179. if _name_sequence is None:
  180. _name_sequence = _RandomNameSequence()
  181. finally:
  182. _once_lock.release()
  183. return _name_sequence
  184. def _mkstemp_inner(dir, pre, suf, flags):
  185. """Code common to mkstemp, TemporaryFile, and NamedTemporaryFile."""
  186. names = _get_candidate_names()
  187. for seq in xrange(TMP_MAX):
  188. name = names.next()
  189. file = _os.path.join(dir, pre + name + suf)
  190. try:
  191. fd = _os.open(file, flags, 0600)
  192. _set_cloexec(fd)
  193. return (fd, _os.path.abspath(file))
  194. except OSError, e:
  195. if e.errno == _errno.EEXIST:
  196. continue # try again
  197. raise
  198. raise IOError, (_errno.EEXIST, "No usable temporary file name found")
  199. # User visible interfaces.
  200. def gettempprefix():
  201. """Accessor for tempdir.template."""
  202. return template
  203. tempdir = None
  204. def gettempdir():
  205. """Accessor for tempdir.tempdir."""
  206. global tempdir
  207. if tempdir is None:
  208. _once_lock.acquire()
  209. try:
  210. if tempdir is None:
  211. tempdir = _get_default_tempdir()
  212. finally:
  213. _once_lock.release()
  214. return tempdir
  215. def mkstemp(suffix="", prefix=template, dir=None, text=False):
  216. """mkstemp([suffix, [prefix, [dir, [text]]]])
  217. User-callable function to create and return a unique temporary
  218. file. The return value is a pair (fd, name) where fd is the
  219. file descriptor returned by os.open, and name is the filename.
  220. If 'suffix' is specified, the file name will end with that suffix,
  221. otherwise there will be no suffix.
  222. If 'prefix' is specified, the file name will begin with that prefix,
  223. otherwise a default prefix is used.
  224. If 'dir' is specified, the file will be created in that directory,
  225. otherwise a default directory is used.
  226. If 'text' is specified and true, the file is opened in text
  227. mode. Else (the default) the file is opened in binary mode. On
  228. some operating systems, this makes no difference.
  229. The file is readable and writable only by the creating user ID.
  230. If the operating system uses permission bits to indicate whether a
  231. file is executable, the file is executable by no one. The file
  232. descriptor is not inherited by children of this process.
  233. Caller is responsible for deleting the file when done with it.
  234. """
  235. if dir is None:
  236. dir = gettempdir()
  237. if text:
  238. flags = _text_openflags
  239. else:
  240. flags = _bin_openflags
  241. return _mkstemp_inner(dir, prefix, suffix, flags)
  242. def mkdtemp(suffix="", prefix=template, dir=None):
  243. """mkdtemp([suffix, [prefix, [dir]]])
  244. User-callable function to create and return a unique temporary
  245. directory. The return value is the pathname of the directory.
  246. Arguments are as for mkstemp, except that the 'text' argument is
  247. not accepted.
  248. The directory is readable, writable, and searchable only by the
  249. creating user.
  250. Caller is responsible for deleting the directory when done with it.
  251. """
  252. if dir is None:
  253. dir = gettempdir()
  254. names = _get_candidate_names()
  255. for seq in xrange(TMP_MAX):
  256. name = names.next()
  257. file = _os.path.join(dir, prefix + name + suffix)
  258. try:
  259. _os.mkdir(file, 0700)
  260. return file
  261. except OSError, e:
  262. if e.errno == _errno.EEXIST:
  263. continue # try again
  264. raise
  265. raise IOError, (_errno.EEXIST, "No usable temporary directory name found")
  266. def mktemp(suffix="", prefix=template, dir=None):
  267. """mktemp([suffix, [prefix, [dir]]])
  268. User-callable function to return a unique temporary file name. The
  269. file is not created.
  270. Arguments are as for mkstemp, except that the 'text' argument is
  271. not accepted.
  272. This function is unsafe and should not be used. The file name
  273. refers to a file that did not exist at some point, but by the time
  274. you get around to creating it, someone else may have beaten you to
  275. the punch.
  276. """
  277. ## from warnings import warn as _warn
  278. ## _warn("mktemp is a potential security risk to your program",
  279. ## RuntimeWarning, stacklevel=2)
  280. if dir is None:
  281. dir = gettempdir()
  282. names = _get_candidate_names()
  283. for seq in xrange(TMP_MAX):
  284. name = names.next()
  285. file = _os.path.join(dir, prefix + name + suffix)
  286. if not _exists(file):
  287. return file
  288. raise IOError, (_errno.EEXIST, "No usable temporary filename found")
  289. class _TemporaryFileWrapper:
  290. """Temporary file wrapper
  291. This class provides a wrapper around files opened for
  292. temporary use. In particular, it seeks to automatically
  293. remove the file when it is no longer needed.
  294. """
  295. def __init__(self, file, name):
  296. self.file = file
  297. self.name = name
  298. self.close_called = False
  299. def __getattr__(self, name):
  300. file = self.__dict__['file']
  301. a = getattr(file, name)
  302. if type(a) != type(0):
  303. setattr(self, name, a)
  304. return a
  305. # NT provides delete-on-close as a primitive, so we don't need
  306. # the wrapper to do anything special. We still use it so that
  307. # file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile.
  308. if _os.name != 'nt':
  309. # Cache the unlinker so we don't get spurious errors at
  310. # shutdown when the module-level "os" is None'd out. Note
  311. # that this must be referenced as self.unlink, because the
  312. # name TemporaryFileWrapper may also get None'd out before
  313. # __del__ is called.
  314. unlink = _os.unlink
  315. def close(self):
  316. if not self.close_called:
  317. self.close_called = True
  318. self.file.close()
  319. self.unlink(self.name)
  320. def __del__(self):
  321. self.close()
  322. def NamedTemporaryFile(mode='w+b', bufsize=-1, suffix="",
  323. prefix=template, dir=None):
  324. """Create and return a temporary file.
  325. Arguments:
  326. 'prefix', 'suffix', 'dir' -- as for mkstemp.
  327. 'mode' -- the mode argument to os.fdopen (default "w+b").
  328. 'bufsize' -- the buffer size argument to os.fdopen (default -1).
  329. The file is created as mkstemp() would do it.
  330. Returns an object with a file-like interface; the name of the file
  331. is accessible as file.name. The file will be automatically deleted
  332. when it is closed.
  333. """
  334. if dir is None:
  335. dir = gettempdir()
  336. if 'b' in mode:
  337. flags = _bin_openflags
  338. else:
  339. flags = _text_openflags
  340. # Setting O_TEMPORARY in the flags causes the OS to delete
  341. # the file when it is closed. This is only supported by Windows.
  342. if _os.name == 'nt':
  343. flags |= _os.O_TEMPORARY
  344. (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
  345. file = _os.fdopen(fd, mode, bufsize)
  346. return _TemporaryFileWrapper(file, name)
  347. if _os.name != 'posix' or _os.sys.platform == 'cygwin':
  348. # On non-POSIX and Cygwin systems, assume that we cannot unlink a file
  349. # while it is open.
  350. TemporaryFile = NamedTemporaryFile
  351. else:
  352. def TemporaryFile(mode='w+b', bufsize=-1, suffix="",
  353. prefix=template, dir=None):
  354. """Create and return a temporary file.
  355. Arguments:
  356. 'prefix', 'suffix', 'directory' -- as for mkstemp.
  357. 'mode' -- the mode argument to os.fdopen (default "w+b").
  358. 'bufsize' -- the buffer size argument to os.fdopen (default -1).
  359. The file is created as mkstemp() would do it.
  360. Returns an object with a file-like interface. The file has no
  361. name, and will cease to exist when it is closed.
  362. """
  363. if dir is None:
  364. dir = gettempdir()
  365. if 'b' in mode:
  366. flags = _bin_openflags
  367. else:
  368. flags = _text_openflags
  369. (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
  370. try:
  371. _os.unlink(name)
  372. return _os.fdopen(fd, mode, bufsize)
  373. except:
  374. _os.close(fd)
  375. raise