"""Temporary files.This module provides generic, low- and high-level interfaces forcreating temporary files and directories. All of the interfacesprovided by this module can be used without fear of race conditionsexcept for 'mktemp'. 'mktemp' is subject to race conditions andshould not be used; it is provided for backward compatibility only.The default path names are returned as str. If you supply bytes asinput, all return values will be in bytes. Ex: >>> tempfile.mkstemp() (4, '/tmp/tmptpu9nin8') >>> tempfile.mkdtemp(suffix=b'') b'/tmp/tmppbi8f0hy'This module also provides some data items to the user: TMP_MAX - maximum number of names that will be tried before giving up. 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","TemporaryDirectory","mkstemp","mkdtemp",# low level safe interfaces"mktemp",# deprecated unsafe interface"TMP_MAX","gettempprefix",# constants"tempdir","gettempdir","gettempprefixb","gettempdirb",]# Imports.importfunctoolsas_functoolsimportwarningsas_warningsimportioas_ioimportosas_osimportshutilas_shutilimporterrnoas_errnofromrandomimportRandomas_Randomimportweakrefas_weakreftry:import_threadexceptImportError:import_dummy_threadas_thread_allocate_lock=_thread.allocate_lock_text_openflags=_os.O_RDWR|_os.O_CREAT|_os.O_EXCLifhasattr(_os,'O_NOFOLLOW'):_text_openflags|=_os.O_NOFOLLOW_bin_openflags=_text_openflagsifhasattr(_os,'O_BINARY'):_bin_openflags|=_os.O_BINARYifhasattr(_os,'TMP_MAX'):TMP_MAX=_os.TMP_MAXelse:TMP_MAX=10000# This variable _was_ unused for legacy reasons, see issue 10354.# But as of 3.5 we actually use it at runtime so changing it would# have a possibly desirable side effect... But we do not want to support# that as an API. It is undocumented on purpose. Do not depend on this.template="tmp"# Internal routines._once_lock=_allocate_lock()ifhasattr(_os,"lstat"):_stat=_os.lstatelifhasattr(_os,"stat"):_stat=_os.statelse:# Fallback. All we need is something that raises OSError if the# file doesn't exist.def_stat(fn):fd=_os.open(fn,_os.O_RDONLY)_os.close(fd)def_exists(fn):try:_stat(fn)exceptOSError:returnFalseelse:returnTruedef_infer_return_type(*args):"""Look at the type of all args and divine their implied return type."""return_type=Noneforarginargs:ifargisNone:continueifisinstance(arg,bytes):ifreturn_typeisstr:raiseTypeError("Can't mix bytes and non-bytes in ""path components.")return_type=byteselse:ifreturn_typeisbytes:raiseTypeError("Can't mix bytes and non-bytes in ""path components.")return_type=strifreturn_typeisNone:returnstr# tempfile APIs return a str by default.returnreturn_typedef_sanitize_params(prefix,suffix,dir):"""Common parameter processing for most APIs in this module."""output_type=_infer_return_type(prefix,suffix,dir)ifsuffixisNone:suffix=output_type()ifprefixisNone:ifoutput_typeisstr:prefix=templateelse:prefix=_os.fsencode(template)ifdirisNone:ifoutput_typeisstr:dir=gettempdir()else:dir=gettempdirb()returnprefix,suffix,dir,output_typeclass_RandomNameSequence:"""An instance of _RandomNameSequence generates an endless sequence of unpredictable strings which can safely be incorporated into file names. Each string is eight characters long. Multiple threads can safely use the same instance at the same time. _RandomNameSequence is an iterator."""characters="abcdefghijklmnopqrstuvwxyz0123456789_"@propertydefrng(self):cur_pid=_os.getpid()ifcur_pid!=getattr(self,'_rng_pid',None):self._rng=_Random()self._rng_pid=cur_pidreturnself._rngdef__iter__(self):returnselfdef__next__(self):c=self.characterschoose=self.rng.choiceletters=[choose(c)fordummyinrange(8)]return''.join(letters)def_candidate_tempdir_list():"""Generate a list of candidate temporary directories which _get_default_tempdir will try."""dirlist=[]# First, try the environment.forenvnamein'TMPDIR','TEMP','TMP':dirname=_os.getenv(envname)ifdirname:dirlist.append(dirname)# Failing that, try OS-specific locations.if_os.name=='nt':dirlist.extend([_os.path.expanduser(r'~\AppData\Local\Temp'),_os.path.expandvars(r'%SYSTEMROOT%\Temp'),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,OSError):dirlist.append(_os.curdir)returndirlistdef_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()fordirindirlist:ifdir!=_os.curdir:dir=_os.path.abspath(dir)# Try only a few names per directory.forseqinrange(100):name=next(namer)filename=_os.path.join(dir,name)try:fd=_os.open(filename,_bin_openflags,0o600)try:try:with_io.open(fd,'wb',closefd=False)asfp:fp.write(b'blat')finally:_os.close(fd)finally:_os.unlink(filename)returndirexceptFileExistsError:passexceptPermissionError:# This exception is thrown when a directory with the chosen name# already exists on windows.if(_os.name=='nt'and_os.path.isdir(dir)and_os.access(dir,_os.W_OK)):continuebreak# no point trying more names in this directoryexceptOSError:break# no point trying more names in this directoryraiseFileNotFoundError(_errno.ENOENT,"No usable temporary directory found in %s"%dirlist)_name_sequence=Nonedef_get_candidate_names():"""Common setup sequence for all user-callable interfaces."""global_name_sequenceif_name_sequenceisNone:_once_lock.acquire()try:if_name_sequenceisNone:_name_sequence=_RandomNameSequence()finally:_once_lock.release()return_name_sequencedef_mkstemp_inner(dir,pre,suf,flags,output_type):"""Code common to mkstemp, TemporaryFile, and NamedTemporaryFile."""names=_get_candidate_names()ifoutput_typeisbytes:names=map(_os.fsencode,names)forseqinrange(TMP_MAX):name=next(names)file=_os.path.join(dir,pre+name+suf)try:fd=_os.open(file,flags,0o600)exceptFileExistsError:continue# try againexceptPermissionError:# This exception is thrown when a directory with the chosen name# already exists on windows.if(_os.name=='nt'and_os.path.isdir(dir)and_os.access(dir,_os.W_OK)):continueelse:raisereturn(fd,_os.path.abspath(file))raiseFileExistsError(_errno.EEXIST,"No usable temporary file name found")# User visible interfaces.defgettempprefix():"""The default prefix for temporary directories."""returntemplatedefgettempprefixb():"""The default prefix for temporary directories as bytes."""return_os.fsencode(gettempprefix())tempdir=Nonedefgettempdir():"""Accessor for tempfile.tempdir."""globaltempdiriftempdirisNone:_once_lock.acquire()try:iftempdirisNone:tempdir=_get_default_tempdir()finally:_once_lock.release()returntempdirdefgettempdirb():"""A bytes version of tempfile.gettempdir()."""return_os.fsencode(gettempdir())defmkstemp(suffix=None,prefix=None,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 not None, the file name will end with that suffix, otherwise there will be no suffix. If 'prefix' is not None, the file name will begin with that prefix, otherwise a default prefix is used. If 'dir' is not None, 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. If any of 'suffix', 'prefix' and 'dir' are not None, they must be the same type. If they are bytes, the returned name will be bytes; str otherwise. 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. """prefix,suffix,dir,output_type=_sanitize_params(prefix,suffix,dir)iftext:flags=_text_openflagselse:flags=_bin_openflagsreturn_mkstemp_inner(dir,prefix,suffix,flags,output_type)defmkdtemp(suffix=None,prefix=None,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. """prefix,suffix,dir,output_type=_sanitize_params(prefix,suffix,dir)names=_get_candidate_names()ifoutput_typeisbytes:names=map(_os.fsencode,names)forseqinrange(TMP_MAX):name=next(names)file=_os.path.join(dir,prefix+name+suffix)try:_os.mkdir(file,0o700)exceptFileExistsError:continue# try againexceptPermissionError:# This exception is thrown when a directory with the chosen name# already exists on windows.if(_os.name=='nt'and_os.path.isdir(dir)and_os.access(dir,_os.W_OK)):continueelse:raisereturnfileraiseFileExistsError(_errno.EEXIST,"No usable temporary directory name found")defmktemp(suffix="",prefix=template,dir=None):"""User-callable function to return a unique temporary file name. The file is not created. Arguments are similar to mkstemp, except that the 'text' argument is not accepted, and suffix=None, prefix=None and bytes file names are not supported. THIS FUNCTION IS UNSAFE AND SHOULD NOT BE USED. The file name may refer 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)ifdirisNone:dir=gettempdir()names=_get_candidate_names()forseqinrange(TMP_MAX):name=next(names)file=_os.path.join(dir,prefix+name+suffix)ifnot_exists(file):returnfileraiseFileExistsError(_errno.EEXIST,"No usable temporary filename found")class_TemporaryFileCloser:"""A separate object allowing proper closing of a temporary file's underlying file object, without adding a __del__ method to the temporary file."""file=None# Set here since __del__ checks itclose_called=Falsedef__init__(self,file,name,delete=True):self.file=fileself.name=nameself.delete=delete# 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.defclose(self,unlink=_os.unlink):ifnotself.close_calledandself.fileisnotNone:self.close_called=Truetry:self.file.close()finally:ifself.delete:unlink(self.name)# Need to ensure the file is deleted on __del__def__del__(self):self.close()else:defclose(self):ifnotself.close_called:self.close_called=Trueself.file.close()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=fileself.name=nameself.delete=deleteself._closer=_TemporaryFileCloser(file,name,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)ifhasattr(a,'__call__'):func=a@_functools.wraps(func)deffunc_wrapper(*args,**kwargs):returnfunc(*args,**kwargs)# Avoid closing the file as long as the wrapper is alive,# see issue #18879.func_wrapper._closer=self._closera=func_wrapperifnotisinstance(a,int):setattr(self,name,a)returna# The underlying __enter__ method returns the wrong object# (self.file) so override it to return the wrapperdef__enter__(self):self.file.__enter__()returnself# Need to trap __exit__ as well to ensure the file gets# deleted when used in a with statementdef__exit__(self,exc,value,tb):result=self.file.__exit__(exc,value,tb)self.close()returnresultdefclose(self):""" Close the temporary file, possibly deleting it. """self._closer.close()# iter() doesn't use __getattr__ to find the __iter__ methoddef__iter__(self):# Don't return iter(self.file), but yield from it to avoid closing# file as long as it's being used as iterator (see issue #23700). We# can't use 'yield from' here because iter(file) returns the file# object itself, which has a close method, and thus the file would get# closed when the generator is finalized, due to PEP380 semantics.forlineinself.file:yieldlinedefNamedTemporaryFile(mode='w+b',buffering=-1,encoding=None,newline=None,suffix=None,prefix=None,dir=None,delete=True):"""Create and return a temporary file. Arguments: 'prefix', 'suffix', 'dir' -- as for mkstemp. 'mode' -- the mode argument to io.open (default "w+b"). 'buffering' -- the buffer size argument to io.open (default -1). 'encoding' -- the encoding argument to io.open (default None) 'newline' -- the newline argument to io.open (default None) '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. """prefix,suffix,dir,output_type=_sanitize_params(prefix,suffix,dir)flags=_bin_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'anddelete:flags|=_os.O_TEMPORARY(fd,name)=_mkstemp_inner(dir,prefix,suffix,flags,output_type)try:file=_io.open(fd,mode,buffering=buffering,newline=newline,encoding=encoding)return_TemporaryFileWrapper(file,name,delete)exceptBaseException:_os.unlink(name)_os.close(fd)raiseif_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=NamedTemporaryFileelse:# Is the O_TMPFILE flag available and does it work?# The flag is set to False if os.open(dir, os.O_TMPFILE) raises an# IsADirectoryError exception_O_TMPFILE_WORKS=hasattr(_os,'O_TMPFILE')defTemporaryFile(mode='w+b',buffering=-1,encoding=None,newline=None,suffix=None,prefix=None,dir=None):"""Create and return a temporary file. Arguments: 'prefix', 'suffix', 'dir' -- as for mkstemp. 'mode' -- the mode argument to io.open (default "w+b"). 'buffering' -- the buffer size argument to io.open (default -1). 'encoding' -- the encoding argument to io.open (default None) 'newline' -- the newline argument to io.open (default None) 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. """global_O_TMPFILE_WORKSprefix,suffix,dir,output_type=_sanitize_params(prefix,suffix,dir)flags=_bin_openflagsif_O_TMPFILE_WORKS:try:flags2=(flags|_os.O_TMPFILE)&~_os.O_CREATfd=_os.open(dir,flags2,0o600)exceptIsADirectoryError:# Linux kernel older than 3.11 ignores the O_TMPFILE flag:# O_TMPFILE is read as O_DIRECTORY. Trying to open a directory# with O_RDWR|O_DIRECTORY fails with IsADirectoryError, a# directory cannot be open to write. Set flag to False to not# try again._O_TMPFILE_WORKS=FalseexceptOSError:# The filesystem of the directory does not support O_TMPFILE.# For example, OSError(95, 'Operation not supported').## On Linux kernel older than 3.11, trying to open a regular# file (or a symbolic link to a regular file) with O_TMPFILE# fails with NotADirectoryError, because O_TMPFILE is read as# O_DIRECTORY.passelse:try:return_io.open(fd,mode,buffering=buffering,newline=newline,encoding=encoding)except:_os.close(fd)raise# Fallback to _mkstemp_inner().(fd,name)=_mkstemp_inner(dir,prefix,suffix,flags,output_type)try:_os.unlink(name)return_io.open(fd,mode,buffering=buffering,newline=newline,encoding=encoding)except:_os.close(fd)raiseclassSpooledTemporaryFile:"""Temporary file wrapper, specialized to switch from BytesIO or StringIO to a real file when it exceeds a certain size or when a fileno is needed. """_rolled=Falsedef__init__(self,max_size=0,mode='w+b',buffering=-1,encoding=None,newline=None,suffix=None,prefix=None,dir=None):if'b'inmode:self._file=_io.BytesIO()else:# Setting newline="\n" avoids newline translation;# this is important because otherwise on Windows we'd# get double newline translation upon rollover().self._file=_io.StringIO(newline="\n")self._max_size=max_sizeself._rolled=Falseself._TemporaryFileArgs={'mode':mode,'buffering':buffering,'suffix':suffix,'prefix':prefix,'encoding':encoding,'newline':newline,'dir':dir}def_check(self,file):ifself._rolled:returnmax_size=self._max_sizeifmax_sizeandfile.tell()>max_size:self.rollover()defrollover(self):ifself._rolled:returnfile=self._filenewfile=self._file=TemporaryFile(**self._TemporaryFileArgs)delself._TemporaryFileArgsnewfile.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# BytesIO/StringIO instance to a real file. So we list# all the methods directly.# Context management protocoldef__enter__(self):ifself._file.closed:raiseValueError("Cannot enter context with closed file")returnselfdef__exit__(self,exc,value,tb):self._file.close()# file protocoldef__iter__(self):returnself._file.__iter__()defclose(self):self._file.close()@propertydefclosed(self):returnself._file.closed@propertydefencoding(self):try:returnself._file.encodingexceptAttributeError:if'b'inself._TemporaryFileArgs['mode']:raisereturnself._TemporaryFileArgs['encoding']deffileno(self):self.rollover()returnself._file.fileno()defflush(self):self._file.flush()defisatty(self):returnself._file.isatty()@propertydefmode(self):try:returnself._file.modeexceptAttributeError:returnself._TemporaryFileArgs['mode']@propertydefname(self):try:returnself._file.nameexceptAttributeError:returnNone@propertydefnewlines(self):try:returnself._file.newlinesexceptAttributeError:if'b'inself._TemporaryFileArgs['mode']:raisereturnself._TemporaryFileArgs['newline']defread(self,*args):returnself._file.read(*args)defreadline(self,*args):returnself._file.readline(*args)defreadlines(self,*args):returnself._file.readlines(*args)defseek(self,*args):self._file.seek(*args)@propertydefsoftspace(self):returnself._file.softspacedeftell(self):returnself._file.tell()deftruncate(self,size=None):ifsizeisNone:self._file.truncate()else:ifsize>self._max_size:self.rollover()self._file.truncate(size)defwrite(self,s):file=self._filerv=file.write(s)self._check(file)returnrvdefwritelines(self,iterable):file=self._filerv=file.writelines(iterable)self._check(file)returnrvclassTemporaryDirectory(object):"""Create and return a temporary directory. This has the same behavior as mkdtemp but can be used as a context manager. For example: with TemporaryDirectory() as tmpdir: ... Upon exiting the context, the directory and everything contained in it are removed. """def__init__(self,suffix=None,prefix=None,dir=None):self.name=mkdtemp(suffix,prefix,dir)self._finalizer=_weakref.finalize(self,self._cleanup,self.name,warn_message="Implicitly cleaning up {!r}".format(self))@classmethoddef_cleanup(cls,name,warn_message):_shutil.rmtree(name)_warnings.warn(warn_message,ResourceWarning)def__repr__(self):return"<{}{!r}>".format(self.__class__.__name__,self.name)def__enter__(self):returnself.namedef__exit__(self,exc,value,tb):self.cleanup()defcleanup(self):ifself._finalizer.detach():_shutil.rmtree(self.name)