B \]Vh @s dZddddddddd d d d d g ZddlZddlZddlZddlZ ddl Z ddl Z ddlmZddlZddlZejZe je jBe jBZee dree jOZeZee dree jOZee dre jZndZdZeZ ee dre j!Z"nee dre j#Z"nddZ"ddZ$ddZ%ddZ&Gdd d Z'd!d"Z(d#d$Z)da*d%d&Z+d'd(Z,d)d Z-d*d Z.da/d+d Z0d,d Z1d@d.dZ2dAd/dZ3d0edfd1dZ4Gd2d3d3Z5Gd4d5d5Z6dBd9dZ7e j8d:kse j9j:d;kre7Z;nee d<addZ=Gd?dde>Z?dS)DaTemporary 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. The default path names are returned as str. If you supply bytes as input, 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. NamedTemporaryFile TemporaryFileSpooledTemporaryFileTemporaryDirectorymkstempmkdtempmktempTMP_MAX gettempprefixtempdir gettempdirgettempprefixb gettempdirbN)Random O_NOFOLLOWO_BINARYi'ZtmplstatstatcCst|tj}t|dS)N)_osopenO_RDONLYclose)fnfdr$/usr/local/lib/python3.7/tempfile.py_statPsrcCs*y t|Wntk r dSXdSdS)NFT)rOSError)rrrr_existsTs  rcGs`d}xJ|D]B}|dkrq t|tr8|tkr2tdt}q |tkrHtdt}q W|dkr\tS|S)zBLook at the type of all args and divine their implied return type.Nz1Can't mix bytes and non-bytes in path components.) isinstancebytesstr TypeError)argsZ return_typeargrrr_infer_return_type]s  r%cCsdt|||}|dkr|}|dkr:|tkr0t}n tt}|dkrX|tkrRt}nt}||||fS)z9Common parameter processing for most APIs in this module.N)r%r!templaterfsencoder r )prefixsuffixdir output_typerrr_sanitize_paramsrs  r,c@s0eZdZdZdZeddZddZddZd S) _RandomNameSequencea,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.Z%abcdefghijklmnopqrstuvwxyz0123456789_cCs,t}|t|ddkr&t|_||_|jS)N_rng_pid)rgetpidgetattr_RandomZ_rngr.)selfZcur_pidrrrrngs z_RandomNameSequence.rngcCs|S)Nr)r2rrr__iter__sz_RandomNameSequence.__iter__cs0|j|jjfddtdD}d|S)Ncsg|] }qSrr).0dummy)cchooserr sz0_RandomNameSequence.__next__..) charactersr3choicerangejoin)r2Zlettersr)r7r8r__next__sz_RandomNameSequence.__next__N) __name__ __module__ __qualname____doc__r<propertyr3r4r@rrrrr-s  r-c Csg}x$dD]}t|}|r ||q Wtjdkr\|tjdtjdddddgn|d d d gy|tWn$t t fk r|tj YnX|S) z[Generate a list of candidate temporary directories which _get_default_tempdir will try.)ZTMPDIRZTEMPZTMPntz~\AppData\Local\Tempz%SYSTEMROOT%\Tempzc:\tempzc:\tmpz\tempz\tmpz/tmpz/var/tmpz/usr/tmp) rgetenvappendnameextendpath expanduser expandvarsgetcwdAttributeErrorrcurdir)dirlistZenvnamedirnamerrr_candidate_tempdir_lists    rSc Cs4t}t}x|D]}|tjkr0tj|}xtdD]}t|}tj||}y\t |t d}znextr?r_bin_openflags_iowriterunlinkFileExistsErrorPermissionErrorrIisdiraccessW_OKrFileNotFoundError_errnoENOENT)ZnamerrQr*seqrIfilenamerfprrr_get_default_tempdirs:    rhcCs2tdkr.tztdkr taWdtXtS)z7Common setup sequence for all user-callable interfaces.N)_name_sequence _once_lockacquirer-releaserrrr_get_candidate_namess  rmc Cst}|tkrttj|}xttD]}t|}tj ||||}yt ||d} WnRt k rnw$Yn>t k rtj dkrtj|rt|tjrw$nYnX| tj|fSWt tjddS)z>Code common to mkstemp, TemporaryFile, and NamedTemporaryFile.irFz#No usable temporary file name foundN)rmr maprr'r>rrXrKr?rr]r^rIr_r`rarWrcEEXIST) r*preZsufflagsr+namesrerIfilerrrr_mkstemp_inners$ rtcCstS)z-The default prefix for temporary directories.)r&rrrrr scCs ttS)z6The default prefix for temporary directories as bytes.)rr'r rrrrr scCs2tdkr.tztdkr taWdtXtS)zAccessor for tempfile.tempdir.N)r rjrkrhrlrrrrr s  cCs ttS)z)A bytes version of tempfile.gettempdir().)rr'r rrrrr +sFcCs2t|||\}}}}|rt}nt}t|||||S)aUser-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. )r,_text_openflagsrYrt)r)r(r*textr+rqrrrr/s c Cst|||\}}}}t}|tkr.ttj|}xttD]}t|}tj ||||}yt |dWnRt k rw8Yn>t k rtjdkrtj |rt|tjrw8nYnX|SWt tjddS)aUser-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. irFz(No usable temporary directory name foundN)r,rmr rnrr'r>rrXrKr?mkdirr]r^rIr_r`rarcro)r)r(r*r+rrrerIrsrrrrWs&  r;cCs`|dkrt}t}x:ttD].}t|}tj||||}t|s|SqWt t j ddS)aUser-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. Nz"No usable temporary filename found) r rmr>rrXrrKr?rr]rcro)r)r(r*rrrerIrsrrrr~sc@sLeZdZdZdZdZd ddZejdkr@ej fdd Z d d Z nd d Z dS)_TemporaryFileCloserzA separate object allowing proper closing of a temporary file's underlying file object, without adding a __del__ method to the temporary file.NFTcCs||_||_||_dS)N)rsrIdelete)r2rsrIryrrr__init__sz_TemporaryFileCloser.__init__rFcCs<|js8|jdk r8d|_z|jWd|jr6||jXdS)NT) close_calledrsrryrI)r2r\rrrrs z_TemporaryFileCloser.closecCs |dS)N)r)r2rrr__del__sz_TemporaryFileCloser.__del__cCs|jsd|_|jdS)NT)r{rsr)r2rrrrs)T) rArBrCrDrsr{rzrrIr\rr|rrrrrxs   rxc@sBeZdZdZdddZddZddZd d Zd d Zd dZ dS)_TemporaryFileWrapperzTemporary 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. TcCs$||_||_||_t||||_dS)N)rsrIryrx_closer)r2rsrIryrrrrzsz_TemporaryFileWrapper.__init__cs^|jd}t||}t|drD|tfdd}|j|_|}t|tsZt||||S)Nrs__call__cs ||S)Nr)r#kwargs)funcrr func_wrappersz7_TemporaryFileWrapper.__getattr__..func_wrapper) __dict__r0hasattr _functoolswrapsr~rintsetattr)r2rIrsarr)rr __getattr__s     z!_TemporaryFileWrapper.__getattr__cCs|j|S)N)rs __enter__)r2rrrrs z_TemporaryFileWrapper.__enter__cCs|j|||}||S)N)rs__exit__r)r2excvaluetbresultrrrrsz_TemporaryFileWrapper.__exit__cCs|jdS)zA Close the temporary file, possibly deleting it. N)r~r)r2rrrrsz_TemporaryFileWrapper.closeccsx|jD] }|VqWdS)N)rs)r2linerrrr4s z_TemporaryFileWrapper.__iter__N)T) rArBrCrDrzrrrrr4rrrrr}s r}w+bTc Cst|||\}}}}t} tjdkr0|r0| tjO} t|||| |\} } y tj| ||||d} t| | |St k rt | t | YnXdS)aCreate 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. rF) bufferingnewlineencodingN) r,rYrrIZ O_TEMPORARYrtrZrr} BaseExceptionr\r) moderrrr)r(r*ryr+rqrrIrsrrrrs      posixcygwin O_TMPFILEc Cst|||\}}}}t}try$|tjBtj@} t|| d} Wn*tk rXdaYnBtk rjYn0Xyt j| ||||dSt | YnXt |||||\} } yt | t j| ||||dSt | YnXdS)a>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. iF)rrrN) r,rY_O_TMPFILE_WORKSrrO_CREATrIsADirectoryErrorrrZrrtr\) rrrrr)r(r*r+rqZflags2rrIrrrr9s0       c@seZdZdZdZd7ddZd d Zd d Zd dZddZ ddZ ddZ e ddZ e ddZddZddZddZe dd Ze d!d"Ze d#d$Zd%d&Zd'd(Zd)d*Zd+d,Ze d-d.Zd/d0Zd8d1d2Zd3d4Zd5d6ZdS)9rzTemporary 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. Frw+brNc CsHd|krt|_ntjdd|_||_d|_|||||||d|_dS)Nb )rF)rrr)r(rrr*)rZBytesIO_fileStringIO _max_size_rolled_TemporaryFileArgs) r2max_sizerrrrr)r(r*rrrrzzs zSpooledTemporaryFile.__init__cCs,|jr dS|j}|r(||kr(|dS)N)rrtellrollover)r2rsrrrr_checks zSpooledTemporaryFile._checkcCsN|jr dS|j}tf|j}|_|`||||dd|_dS)NrT)rrrrr[getvalueseekr)r2rsZnewfilerrrrszSpooledTemporaryFile.rollovercCs|jjrtd|S)Nz%Cannot enter context with closed file)rclosed ValueError)r2rrrrszSpooledTemporaryFile.__enter__cCs|jdS)N)rr)r2rrrrrrrszSpooledTemporaryFile.__exit__cCs |jS)N)rr4)r2rrrr4szSpooledTemporaryFile.__iter__cCs|jdS)N)rr)r2rrrrszSpooledTemporaryFile.closecCs|jjS)N)rr)r2rrrrszSpooledTemporaryFile.closedcCs8y|jjStk r2d|jdkr(|jdSXdS)Nrrr)rrrOr)r2rrrrs zSpooledTemporaryFile.encodingcCs||jS)N)rrfileno)r2rrrrszSpooledTemporaryFile.filenocCs|jdS)N)rflush)r2rrrrszSpooledTemporaryFile.flushcCs |jS)N)risatty)r2rrrrszSpooledTemporaryFile.isattycCs(y|jjStk r"|jdSXdS)Nr)rrrOr)r2rrrrszSpooledTemporaryFile.modecCs"y|jjStk rdSXdS)N)rrIrO)r2rrrrIszSpooledTemporaryFile.namecCs8y|jjStk r2d|jdkr(|jdSXdS)Nrrr)rnewlinesrOr)r2rrrrs zSpooledTemporaryFile.newlinescGs |jj|S)N)rread)r2r#rrrrszSpooledTemporaryFile.readcGs |jj|S)N)rreadline)r2r#rrrrszSpooledTemporaryFile.readlinecGs |jj|S)N)r readlines)r2r#rrrrszSpooledTemporaryFile.readlinescGs|jj|dS)N)rr)r2r#rrrrszSpooledTemporaryFile.seekcCs|jjS)N)r softspace)r2rrrrszSpooledTemporaryFile.softspacecCs |jS)N)rr)r2rrrrszSpooledTemporaryFile.tellcCs6|dkr|jn||jkr&||j|dS)N)rtruncaterr)r2sizerrrrs   zSpooledTemporaryFile.truncatecCs|j}||}|||S)N)rr[r)r2srsrvrrrr[s  zSpooledTemporaryFile.writecCs|j}||}|||S)N)r writelinesr)r2iterablersrrrrrs  zSpooledTemporaryFile.writelines)rrrNNNNN)N)rArBrCrDrrzrrrrr4rrErrrrrrrIrrrrrrrrr[rrrrrrss8        c@sFeZdZdZdddZeddZddZd d Zd d Z d dZ dS)ra+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. NcCs0t||||_tj||j|jd|d|_dS)NzImplicitly cleaning up {!r}) warn_message)rrI_weakreffinalize_cleanupformat _finalizer)r2r)r(r*rrrrzs zTemporaryDirectory.__init__cCst|t|tdS)N)_shutilrmtree _warningswarnResourceWarning)clsrIrrrrrs zTemporaryDirectory._cleanupcCsd|jj|jS)Nz <{} {!r}>)r __class__rArI)r2rrr__repr__szTemporaryDirectory.__repr__cCs|jS)N)rI)r2rrrr!szTemporaryDirectory.__enter__cCs |dS)N)cleanup)r2rrrrrrr$szTemporaryDirectory.__exit__cCs|jrt|jdS)N)rdetachrrrI)r2rrrr's zTemporaryDirectory.cleanup)NNN) rArBrCrDrz classmethodrrrrrrrrrrs   )NNNF)NNN)rrNNNNNT)rrNNNNN)@rD__all__ functoolsrwarningsriorZosrshutilrerrnorcrandomrr1weakrefr_thread allocate_lock_allocate_lockO_RDWRrO_EXCLrurrrYrrr&rjrrrrr%r,r-rSrhrirmrtr r r r r rrrrxr}rrIsysplatformrrrobjectrrrrrs         -  ( ' +? $  8