Edit File by line
/home/barbar84/public_h.../wp-conte.../plugins/sujqvwi/AnonR/anonr.TX.../opt/imh-pyth.../lib/python3....
File: tempfile.py
"""Temporary files.
[0] Fix | Delete
[1] Fix | Delete
This module provides generic, low- and high-level interfaces for
[2] Fix | Delete
creating temporary files and directories. All of the interfaces
[3] Fix | Delete
provided by this module can be used without fear of race conditions
[4] Fix | Delete
except for 'mktemp'. 'mktemp' is subject to race conditions and
[5] Fix | Delete
should not be used; it is provided for backward compatibility only.
[6] Fix | Delete
[7] Fix | Delete
The default path names are returned as str. If you supply bytes as
[8] Fix | Delete
input, all return values will be in bytes. Ex:
[9] Fix | Delete
[10] Fix | Delete
>>> tempfile.mkstemp()
[11] Fix | Delete
(4, '/tmp/tmptpu9nin8')
[12] Fix | Delete
>>> tempfile.mkdtemp(suffix=b'')
[13] Fix | Delete
b'/tmp/tmppbi8f0hy'
[14] Fix | Delete
[15] Fix | Delete
This module also provides some data items to the user:
[16] Fix | Delete
[17] Fix | Delete
TMP_MAX - maximum number of names that will be tried before
[18] Fix | Delete
giving up.
[19] Fix | Delete
tempdir - If this is set to a string before the first use of
[20] Fix | Delete
any routine from this module, it will be considered as
[21] Fix | Delete
another candidate location to store temporary files.
[22] Fix | Delete
"""
[23] Fix | Delete
[24] Fix | Delete
__all__ = [
[25] Fix | Delete
"NamedTemporaryFile", "TemporaryFile", # high level safe interfaces
[26] Fix | Delete
"SpooledTemporaryFile", "TemporaryDirectory",
[27] Fix | Delete
"mkstemp", "mkdtemp", # low level safe interfaces
[28] Fix | Delete
"mktemp", # deprecated unsafe interface
[29] Fix | Delete
"TMP_MAX", "gettempprefix", # constants
[30] Fix | Delete
"tempdir", "gettempdir",
[31] Fix | Delete
"gettempprefixb", "gettempdirb",
[32] Fix | Delete
]
[33] Fix | Delete
[34] Fix | Delete
[35] Fix | Delete
# Imports.
[36] Fix | Delete
[37] Fix | Delete
import functools as _functools
[38] Fix | Delete
import warnings as _warnings
[39] Fix | Delete
import io as _io
[40] Fix | Delete
import os as _os
[41] Fix | Delete
import shutil as _shutil
[42] Fix | Delete
import errno as _errno
[43] Fix | Delete
from random import Random as _Random
[44] Fix | Delete
import sys as _sys
[45] Fix | Delete
import types as _types
[46] Fix | Delete
import weakref as _weakref
[47] Fix | Delete
import _thread
[48] Fix | Delete
_allocate_lock = _thread.allocate_lock
[49] Fix | Delete
[50] Fix | Delete
_text_openflags = _os.O_RDWR | _os.O_CREAT | _os.O_EXCL
[51] Fix | Delete
if hasattr(_os, 'O_NOFOLLOW'):
[52] Fix | Delete
_text_openflags |= _os.O_NOFOLLOW
[53] Fix | Delete
[54] Fix | Delete
_bin_openflags = _text_openflags
[55] Fix | Delete
if hasattr(_os, 'O_BINARY'):
[56] Fix | Delete
_bin_openflags |= _os.O_BINARY
[57] Fix | Delete
[58] Fix | Delete
if hasattr(_os, 'TMP_MAX'):
[59] Fix | Delete
TMP_MAX = _os.TMP_MAX
[60] Fix | Delete
else:
[61] Fix | Delete
TMP_MAX = 10000
[62] Fix | Delete
[63] Fix | Delete
# This variable _was_ unused for legacy reasons, see issue 10354.
[64] Fix | Delete
# But as of 3.5 we actually use it at runtime so changing it would
[65] Fix | Delete
# have a possibly desirable side effect... But we do not want to support
[66] Fix | Delete
# that as an API. It is undocumented on purpose. Do not depend on this.
[67] Fix | Delete
template = "tmp"
[68] Fix | Delete
[69] Fix | Delete
# Internal routines.
[70] Fix | Delete
[71] Fix | Delete
_once_lock = _allocate_lock()
[72] Fix | Delete
[73] Fix | Delete
[74] Fix | Delete
def _exists(fn):
[75] Fix | Delete
try:
[76] Fix | Delete
_os.lstat(fn)
[77] Fix | Delete
except OSError:
[78] Fix | Delete
return False
[79] Fix | Delete
else:
[80] Fix | Delete
return True
[81] Fix | Delete
[82] Fix | Delete
[83] Fix | Delete
def _infer_return_type(*args):
[84] Fix | Delete
"""Look at the type of all args and divine their implied return type."""
[85] Fix | Delete
return_type = None
[86] Fix | Delete
for arg in args:
[87] Fix | Delete
if arg is None:
[88] Fix | Delete
continue
[89] Fix | Delete
if isinstance(arg, bytes):
[90] Fix | Delete
if return_type is str:
[91] Fix | Delete
raise TypeError("Can't mix bytes and non-bytes in "
[92] Fix | Delete
"path components.")
[93] Fix | Delete
return_type = bytes
[94] Fix | Delete
else:
[95] Fix | Delete
if return_type is bytes:
[96] Fix | Delete
raise TypeError("Can't mix bytes and non-bytes in "
[97] Fix | Delete
"path components.")
[98] Fix | Delete
return_type = str
[99] Fix | Delete
if return_type is None:
[100] Fix | Delete
return str # tempfile APIs return a str by default.
[101] Fix | Delete
return return_type
[102] Fix | Delete
[103] Fix | Delete
[104] Fix | Delete
def _sanitize_params(prefix, suffix, dir):
[105] Fix | Delete
"""Common parameter processing for most APIs in this module."""
[106] Fix | Delete
output_type = _infer_return_type(prefix, suffix, dir)
[107] Fix | Delete
if suffix is None:
[108] Fix | Delete
suffix = output_type()
[109] Fix | Delete
if prefix is None:
[110] Fix | Delete
if output_type is str:
[111] Fix | Delete
prefix = template
[112] Fix | Delete
else:
[113] Fix | Delete
prefix = _os.fsencode(template)
[114] Fix | Delete
if dir is None:
[115] Fix | Delete
if output_type is str:
[116] Fix | Delete
dir = gettempdir()
[117] Fix | Delete
else:
[118] Fix | Delete
dir = gettempdirb()
[119] Fix | Delete
return prefix, suffix, dir, output_type
[120] Fix | Delete
[121] Fix | Delete
[122] Fix | Delete
class _RandomNameSequence:
[123] Fix | Delete
"""An instance of _RandomNameSequence generates an endless
[124] Fix | Delete
sequence of unpredictable strings which can safely be incorporated
[125] Fix | Delete
into file names. Each string is eight characters long. Multiple
[126] Fix | Delete
threads can safely use the same instance at the same time.
[127] Fix | Delete
[128] Fix | Delete
_RandomNameSequence is an iterator."""
[129] Fix | Delete
[130] Fix | Delete
characters = "abcdefghijklmnopqrstuvwxyz0123456789_"
[131] Fix | Delete
[132] Fix | Delete
@property
[133] Fix | Delete
def rng(self):
[134] Fix | Delete
cur_pid = _os.getpid()
[135] Fix | Delete
if cur_pid != getattr(self, '_rng_pid', None):
[136] Fix | Delete
self._rng = _Random()
[137] Fix | Delete
self._rng_pid = cur_pid
[138] Fix | Delete
return self._rng
[139] Fix | Delete
[140] Fix | Delete
def __iter__(self):
[141] Fix | Delete
return self
[142] Fix | Delete
[143] Fix | Delete
def __next__(self):
[144] Fix | Delete
c = self.characters
[145] Fix | Delete
choose = self.rng.choice
[146] Fix | Delete
letters = [choose(c) for dummy in range(8)]
[147] Fix | Delete
return ''.join(letters)
[148] Fix | Delete
[149] Fix | Delete
def _candidate_tempdir_list():
[150] Fix | Delete
"""Generate a list of candidate temporary directories which
[151] Fix | Delete
_get_default_tempdir will try."""
[152] Fix | Delete
[153] Fix | Delete
dirlist = []
[154] Fix | Delete
[155] Fix | Delete
# First, try the environment.
[156] Fix | Delete
for envname in 'TMPDIR', 'TEMP', 'TMP':
[157] Fix | Delete
dirname = _os.getenv(envname)
[158] Fix | Delete
if dirname: dirlist.append(dirname)
[159] Fix | Delete
[160] Fix | Delete
# Failing that, try OS-specific locations.
[161] Fix | Delete
if _os.name == 'nt':
[162] Fix | Delete
dirlist.extend([ _os.path.expanduser(r'~\AppData\Local\Temp'),
[163] Fix | Delete
_os.path.expandvars(r'%SYSTEMROOT%\Temp'),
[164] Fix | Delete
r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ])
[165] Fix | Delete
else:
[166] Fix | Delete
dirlist.extend([ '/tmp', '/var/tmp', '/usr/tmp' ])
[167] Fix | Delete
[168] Fix | Delete
# As a last resort, the current directory.
[169] Fix | Delete
try:
[170] Fix | Delete
dirlist.append(_os.getcwd())
[171] Fix | Delete
except (AttributeError, OSError):
[172] Fix | Delete
dirlist.append(_os.curdir)
[173] Fix | Delete
[174] Fix | Delete
return dirlist
[175] Fix | Delete
[176] Fix | Delete
def _get_default_tempdir():
[177] Fix | Delete
"""Calculate the default directory to use for temporary files.
[178] Fix | Delete
This routine should be called exactly once.
[179] Fix | Delete
[180] Fix | Delete
We determine whether or not a candidate temp dir is usable by
[181] Fix | Delete
trying to create and write to a file in that directory. If this
[182] Fix | Delete
is successful, the test file is deleted. To prevent denial of
[183] Fix | Delete
service, the name of the test file must be randomized."""
[184] Fix | Delete
[185] Fix | Delete
namer = _RandomNameSequence()
[186] Fix | Delete
dirlist = _candidate_tempdir_list()
[187] Fix | Delete
[188] Fix | Delete
for dir in dirlist:
[189] Fix | Delete
if dir != _os.curdir:
[190] Fix | Delete
dir = _os.path.abspath(dir)
[191] Fix | Delete
# Try only a few names per directory.
[192] Fix | Delete
for seq in range(100):
[193] Fix | Delete
name = next(namer)
[194] Fix | Delete
filename = _os.path.join(dir, name)
[195] Fix | Delete
try:
[196] Fix | Delete
fd = _os.open(filename, _bin_openflags, 0o600)
[197] Fix | Delete
try:
[198] Fix | Delete
try:
[199] Fix | Delete
with _io.open(fd, 'wb', closefd=False) as fp:
[200] Fix | Delete
fp.write(b'blat')
[201] Fix | Delete
finally:
[202] Fix | Delete
_os.close(fd)
[203] Fix | Delete
finally:
[204] Fix | Delete
_os.unlink(filename)
[205] Fix | Delete
return dir
[206] Fix | Delete
except FileExistsError:
[207] Fix | Delete
pass
[208] Fix | Delete
except PermissionError:
[209] Fix | Delete
# This exception is thrown when a directory with the chosen name
[210] Fix | Delete
# already exists on windows.
[211] Fix | Delete
if (_os.name == 'nt' and _os.path.isdir(dir) and
[212] Fix | Delete
_os.access(dir, _os.W_OK)):
[213] Fix | Delete
continue
[214] Fix | Delete
break # no point trying more names in this directory
[215] Fix | Delete
except OSError:
[216] Fix | Delete
break # no point trying more names in this directory
[217] Fix | Delete
raise FileNotFoundError(_errno.ENOENT,
[218] Fix | Delete
"No usable temporary directory found in %s" %
[219] Fix | Delete
dirlist)
[220] Fix | Delete
[221] Fix | Delete
_name_sequence = None
[222] Fix | Delete
[223] Fix | Delete
def _get_candidate_names():
[224] Fix | Delete
"""Common setup sequence for all user-callable interfaces."""
[225] Fix | Delete
[226] Fix | Delete
global _name_sequence
[227] Fix | Delete
if _name_sequence is None:
[228] Fix | Delete
_once_lock.acquire()
[229] Fix | Delete
try:
[230] Fix | Delete
if _name_sequence is None:
[231] Fix | Delete
_name_sequence = _RandomNameSequence()
[232] Fix | Delete
finally:
[233] Fix | Delete
_once_lock.release()
[234] Fix | Delete
return _name_sequence
[235] Fix | Delete
[236] Fix | Delete
[237] Fix | Delete
def _mkstemp_inner(dir, pre, suf, flags, output_type):
[238] Fix | Delete
"""Code common to mkstemp, TemporaryFile, and NamedTemporaryFile."""
[239] Fix | Delete
[240] Fix | Delete
names = _get_candidate_names()
[241] Fix | Delete
if output_type is bytes:
[242] Fix | Delete
names = map(_os.fsencode, names)
[243] Fix | Delete
[244] Fix | Delete
for seq in range(TMP_MAX):
[245] Fix | Delete
name = next(names)
[246] Fix | Delete
file = _os.path.join(dir, pre + name + suf)
[247] Fix | Delete
_sys.audit("tempfile.mkstemp", file)
[248] Fix | Delete
try:
[249] Fix | Delete
fd = _os.open(file, flags, 0o600)
[250] Fix | Delete
except FileExistsError:
[251] Fix | Delete
continue # try again
[252] Fix | Delete
except PermissionError:
[253] Fix | Delete
# This exception is thrown when a directory with the chosen name
[254] Fix | Delete
# already exists on windows.
[255] Fix | Delete
if (_os.name == 'nt' and _os.path.isdir(dir) and
[256] Fix | Delete
_os.access(dir, _os.W_OK)):
[257] Fix | Delete
continue
[258] Fix | Delete
else:
[259] Fix | Delete
raise
[260] Fix | Delete
return (fd, _os.path.abspath(file))
[261] Fix | Delete
[262] Fix | Delete
raise FileExistsError(_errno.EEXIST,
[263] Fix | Delete
"No usable temporary file name found")
[264] Fix | Delete
[265] Fix | Delete
[266] Fix | Delete
# User visible interfaces.
[267] Fix | Delete
[268] Fix | Delete
def gettempprefix():
[269] Fix | Delete
"""The default prefix for temporary directories."""
[270] Fix | Delete
return template
[271] Fix | Delete
[272] Fix | Delete
def gettempprefixb():
[273] Fix | Delete
"""The default prefix for temporary directories as bytes."""
[274] Fix | Delete
return _os.fsencode(gettempprefix())
[275] Fix | Delete
[276] Fix | Delete
tempdir = None
[277] Fix | Delete
[278] Fix | Delete
def gettempdir():
[279] Fix | Delete
"""Accessor for tempfile.tempdir."""
[280] Fix | Delete
global tempdir
[281] Fix | Delete
if tempdir is None:
[282] Fix | Delete
_once_lock.acquire()
[283] Fix | Delete
try:
[284] Fix | Delete
if tempdir is None:
[285] Fix | Delete
tempdir = _get_default_tempdir()
[286] Fix | Delete
finally:
[287] Fix | Delete
_once_lock.release()
[288] Fix | Delete
return tempdir
[289] Fix | Delete
[290] Fix | Delete
def gettempdirb():
[291] Fix | Delete
"""A bytes version of tempfile.gettempdir()."""
[292] Fix | Delete
return _os.fsencode(gettempdir())
[293] Fix | Delete
[294] Fix | Delete
def mkstemp(suffix=None, prefix=None, dir=None, text=False):
[295] Fix | Delete
"""User-callable function to create and return a unique temporary
[296] Fix | Delete
file. The return value is a pair (fd, name) where fd is the
[297] Fix | Delete
file descriptor returned by os.open, and name is the filename.
[298] Fix | Delete
[299] Fix | Delete
If 'suffix' is not None, the file name will end with that suffix,
[300] Fix | Delete
otherwise there will be no suffix.
[301] Fix | Delete
[302] Fix | Delete
If 'prefix' is not None, the file name will begin with that prefix,
[303] Fix | Delete
otherwise a default prefix is used.
[304] Fix | Delete
[305] Fix | Delete
If 'dir' is not None, the file will be created in that directory,
[306] Fix | Delete
otherwise a default directory is used.
[307] Fix | Delete
[308] Fix | Delete
If 'text' is specified and true, the file is opened in text
[309] Fix | Delete
mode. Else (the default) the file is opened in binary mode.
[310] Fix | Delete
[311] Fix | Delete
If any of 'suffix', 'prefix' and 'dir' are not None, they must be the
[312] Fix | Delete
same type. If they are bytes, the returned name will be bytes; str
[313] Fix | Delete
otherwise.
[314] Fix | Delete
[315] Fix | Delete
The file is readable and writable only by the creating user ID.
[316] Fix | Delete
If the operating system uses permission bits to indicate whether a
[317] Fix | Delete
file is executable, the file is executable by no one. The file
[318] Fix | Delete
descriptor is not inherited by children of this process.
[319] Fix | Delete
[320] Fix | Delete
Caller is responsible for deleting the file when done with it.
[321] Fix | Delete
"""
[322] Fix | Delete
[323] Fix | Delete
prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)
[324] Fix | Delete
[325] Fix | Delete
if text:
[326] Fix | Delete
flags = _text_openflags
[327] Fix | Delete
else:
[328] Fix | Delete
flags = _bin_openflags
[329] Fix | Delete
[330] Fix | Delete
return _mkstemp_inner(dir, prefix, suffix, flags, output_type)
[331] Fix | Delete
[332] Fix | Delete
[333] Fix | Delete
def mkdtemp(suffix=None, prefix=None, dir=None):
[334] Fix | Delete
"""User-callable function to create and return a unique temporary
[335] Fix | Delete
directory. The return value is the pathname of the directory.
[336] Fix | Delete
[337] Fix | Delete
Arguments are as for mkstemp, except that the 'text' argument is
[338] Fix | Delete
not accepted.
[339] Fix | Delete
[340] Fix | Delete
The directory is readable, writable, and searchable only by the
[341] Fix | Delete
creating user.
[342] Fix | Delete
[343] Fix | Delete
Caller is responsible for deleting the directory when done with it.
[344] Fix | Delete
"""
[345] Fix | Delete
[346] Fix | Delete
prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)
[347] Fix | Delete
[348] Fix | Delete
names = _get_candidate_names()
[349] Fix | Delete
if output_type is bytes:
[350] Fix | Delete
names = map(_os.fsencode, names)
[351] Fix | Delete
[352] Fix | Delete
for seq in range(TMP_MAX):
[353] Fix | Delete
name = next(names)
[354] Fix | Delete
file = _os.path.join(dir, prefix + name + suffix)
[355] Fix | Delete
_sys.audit("tempfile.mkdtemp", file)
[356] Fix | Delete
try:
[357] Fix | Delete
_os.mkdir(file, 0o700)
[358] Fix | Delete
except FileExistsError:
[359] Fix | Delete
continue # try again
[360] Fix | Delete
except PermissionError:
[361] Fix | Delete
# This exception is thrown when a directory with the chosen name
[362] Fix | Delete
# already exists on windows.
[363] Fix | Delete
if (_os.name == 'nt' and _os.path.isdir(dir) and
[364] Fix | Delete
_os.access(dir, _os.W_OK)):
[365] Fix | Delete
continue
[366] Fix | Delete
else:
[367] Fix | Delete
raise
[368] Fix | Delete
return file
[369] Fix | Delete
[370] Fix | Delete
raise FileExistsError(_errno.EEXIST,
[371] Fix | Delete
"No usable temporary directory name found")
[372] Fix | Delete
[373] Fix | Delete
def mktemp(suffix="", prefix=template, dir=None):
[374] Fix | Delete
"""User-callable function to return a unique temporary file name. The
[375] Fix | Delete
file is not created.
[376] Fix | Delete
[377] Fix | Delete
Arguments are similar to mkstemp, except that the 'text' argument is
[378] Fix | Delete
not accepted, and suffix=None, prefix=None and bytes file names are not
[379] Fix | Delete
supported.
[380] Fix | Delete
[381] Fix | Delete
THIS FUNCTION IS UNSAFE AND SHOULD NOT BE USED. The file name may
[382] Fix | Delete
refer to a file that did not exist at some point, but by the time
[383] Fix | Delete
you get around to creating it, someone else may have beaten you to
[384] Fix | Delete
the punch.
[385] Fix | Delete
"""
[386] Fix | Delete
[387] Fix | Delete
## from warnings import warn as _warn
[388] Fix | Delete
## _warn("mktemp is a potential security risk to your program",
[389] Fix | Delete
## RuntimeWarning, stacklevel=2)
[390] Fix | Delete
[391] Fix | Delete
if dir is None:
[392] Fix | Delete
dir = gettempdir()
[393] Fix | Delete
[394] Fix | Delete
names = _get_candidate_names()
[395] Fix | Delete
for seq in range(TMP_MAX):
[396] Fix | Delete
name = next(names)
[397] Fix | Delete
file = _os.path.join(dir, prefix + name + suffix)
[398] Fix | Delete
if not _exists(file):
[399] Fix | Delete
return file
[400] Fix | Delete
[401] Fix | Delete
raise FileExistsError(_errno.EEXIST,
[402] Fix | Delete
"No usable temporary filename found")
[403] Fix | Delete
[404] Fix | Delete
[405] Fix | Delete
class _TemporaryFileCloser:
[406] Fix | Delete
"""A separate object allowing proper closing of a temporary file's
[407] Fix | Delete
underlying file object, without adding a __del__ method to the
[408] Fix | Delete
temporary file."""
[409] Fix | Delete
[410] Fix | Delete
file = None # Set here since __del__ checks it
[411] Fix | Delete
close_called = False
[412] Fix | Delete
[413] Fix | Delete
def __init__(self, file, name, delete=True):
[414] Fix | Delete
self.file = file
[415] Fix | Delete
self.name = name
[416] Fix | Delete
self.delete = delete
[417] Fix | Delete
[418] Fix | Delete
# NT provides delete-on-close as a primitive, so we don't need
[419] Fix | Delete
# the wrapper to do anything special. We still use it so that
[420] Fix | Delete
# file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile.
[421] Fix | Delete
if _os.name != 'nt':
[422] Fix | Delete
# Cache the unlinker so we don't get spurious errors at
[423] Fix | Delete
# shutdown when the module-level "os" is None'd out. Note
[424] Fix | Delete
# that this must be referenced as self.unlink, because the
[425] Fix | Delete
# name TemporaryFileWrapper may also get None'd out before
[426] Fix | Delete
# __del__ is called.
[427] Fix | Delete
[428] Fix | Delete
def close(self, unlink=_os.unlink):
[429] Fix | Delete
if not self.close_called and self.file is not None:
[430] Fix | Delete
self.close_called = True
[431] Fix | Delete
try:
[432] Fix | Delete
self.file.close()
[433] Fix | Delete
finally:
[434] Fix | Delete
if self.delete:
[435] Fix | Delete
unlink(self.name)
[436] Fix | Delete
[437] Fix | Delete
# Need to ensure the file is deleted on __del__
[438] Fix | Delete
def __del__(self):
[439] Fix | Delete
self.close()
[440] Fix | Delete
[441] Fix | Delete
else:
[442] Fix | Delete
def close(self):
[443] Fix | Delete
if not self.close_called:
[444] Fix | Delete
self.close_called = True
[445] Fix | Delete
self.file.close()
[446] Fix | Delete
[447] Fix | Delete
[448] Fix | Delete
class _TemporaryFileWrapper:
[449] Fix | Delete
"""Temporary file wrapper
[450] Fix | Delete
[451] Fix | Delete
This class provides a wrapper around files opened for
[452] Fix | Delete
temporary use. In particular, it seeks to automatically
[453] Fix | Delete
remove the file when it is no longer needed.
[454] Fix | Delete
"""
[455] Fix | Delete
[456] Fix | Delete
def __init__(self, file, name, delete=True):
[457] Fix | Delete
self.file = file
[458] Fix | Delete
self.name = name
[459] Fix | Delete
self.delete = delete
[460] Fix | Delete
self._closer = _TemporaryFileCloser(file, name, delete)
[461] Fix | Delete
[462] Fix | Delete
def __getattr__(self, name):
[463] Fix | Delete
# Attribute lookups are delegated to the underlying file
[464] Fix | Delete
# and cached for non-numeric results
[465] Fix | Delete
# (i.e. methods are cached, closed and friends are not)
[466] Fix | Delete
file = self.__dict__['file']
[467] Fix | Delete
a = getattr(file, name)
[468] Fix | Delete
if hasattr(a, '__call__'):
[469] Fix | Delete
func = a
[470] Fix | Delete
@_functools.wraps(func)
[471] Fix | Delete
def func_wrapper(*args, **kwargs):
[472] Fix | Delete
return func(*args, **kwargs)
[473] Fix | Delete
# Avoid closing the file as long as the wrapper is alive,
[474] Fix | Delete
# see issue #18879.
[475] Fix | Delete
func_wrapper._closer = self._closer
[476] Fix | Delete
a = func_wrapper
[477] Fix | Delete
if not isinstance(a, int):
[478] Fix | Delete
setattr(self, name, a)
[479] Fix | Delete
return a
[480] Fix | Delete
[481] Fix | Delete
# The underlying __enter__ method returns the wrong object
[482] Fix | Delete
# (self.file) so override it to return the wrapper
[483] Fix | Delete
def __enter__(self):
[484] Fix | Delete
self.file.__enter__()
[485] Fix | Delete
return self
[486] Fix | Delete
[487] Fix | Delete
# Need to trap __exit__ as well to ensure the file gets
[488] Fix | Delete
# deleted when used in a with statement
[489] Fix | Delete
def __exit__(self, exc, value, tb):
[490] Fix | Delete
result = self.file.__exit__(exc, value, tb)
[491] Fix | Delete
self.close()
[492] Fix | Delete
return result
[493] Fix | Delete
[494] Fix | Delete
def close(self):
[495] Fix | Delete
"""
[496] Fix | Delete
Close the temporary file, possibly deleting it.
[497] Fix | Delete
"""
[498] Fix | Delete
self._closer.close()
[499] Fix | Delete
12
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function