3 fm@sBdZddddddddd d d d d g ZddlZddlZddlZddlZ ddl Z ddl Z ddlmZddlZy ddlZWnek rddlZYnXejZe je jBe jBZee dree jOZeZee dree jOZee dre j Z ndZ dZ!eZ"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,Z0d-d Z1d.d Z2da3d/d Z4d0d Z5dDd2dZ6dEd3dZ7d4e!dfd5dZ8Gd6d7d7Z9Gd8d9d9Z:dGd=dZ;e jkse j=j>d?kr e;Z?nee d@a@dIdAdZ?GdBddZAGdCddeBZCdS)JaTemporary 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'ZtmplstatstatcCstj|tj}tj|dS)N)_osopenO_RDONLYclose)fnfdr /usr/lib64/python3.6/tempfile.py_statTsrc Cs*y t|Wntk r dSXdSdS)NFT)rOSError)rrrr_existsXs  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_typeas  r%cCsdt|||}|dkr|}|dkr:|tkr0t}n tjt}|dkrX|tkrRt}nt}||||fS)z9Common parameter processing for most APIs in this module.N)r%r!templaterfsencoder r )prefixsuffixdir output_typerrr_sanitize_paramsvs  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,tj}|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}dj|S)Ncsg|] }qSrr).0Zdummy)cchooserr sz0_RandomNameSequence.__next__..) charactersr3Zchoicerangejoin)r2Zlettersr)r6r7r__next__sz_RandomNameSequence.__next__N) __name__ __module__ __qualname____doc__r;propertyr3r4r>rrrrr-s  r-c Csg}x$dD]}tj|}|r |j|q Wtjdkr\|jtjjdtjjdddd d gn|jd d d gy|jtjWn$t t fk r|jtj YnX|S)z[Generate a list of candidate temporary directories which _get_default_tempdir will try.TMPDIRTEMPTMPntz~\AppData\Local\Tempz%SYSTEMROOT%\Tempzc:\tempzc:\tmpz\tempz\tmpz/tmpz/var/tmpz/usr/tmp)rDrErF) rgetenvappendnameextendpath expanduser expandvarsgetcwdAttributeErrorrcurdir)dirlistZenvnamedirnamerrr_candidate_tempdir_lists    rTcCs4t}t}x|D]}|tjkr0tjj|}xtdD]}t|}tjj||}y\tj |t d}zt k rtj dkrtjj|rtj|tjrw$nYnX| tjj|fSWt tjddS)z>Code common to mkstemp, TemporaryFile, and NamedTemporaryFile.irGz#No usable temporary file name foundN)rnr maprr'r<rrYrLr=rr^r_rJr`rarbrXrdEEXIST) r*ZpreZsufflagsr+namesrfrJfilerrrr_mkstemp_inners$ rtcGsJ|tjkr ||f|ddin&tjdks8tjj| rF||f|dS)Nfollow_symlinksFrG)rsupports_follow_symlinksrJrLislink)funcrLr#rrr_dont_follow_symlinkss ryc Cs>y tj}Wntk rYnXt||dttj|ddS)Nri)rchflagsrPrychmod)rLrzrrr _resetpermss   r|cCstS)z-The default prefix for temporary directories.)r&rrrrr *scCs tjtS)z6The default prefix for temporary directories as bytes.)rr'r rrrrr .sc Cs2tdkr.tjztdkr taWdtjXtS)zAccessor for tempfile.tempdir.N)r rkrlrirmrrrrr 4s  cCs tjtS)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_openflagsrZrt)r)r(r*textr+rqrrrrDs c Cst|||\}}}}t}|tkr.ttj|}xttD]}t|}tj j ||||}ytj |dWnRt k rw8Yn>t k rtjdkrtj j|rtj|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. irGz(No usable temporary directory name foundN)r,rnr rorr'r<rrYrLr=mkdirr^r_rJr`rarbrdrp)r)r(r*r+rrrfrJrsrrrrls&  r:cCs`|dkrt}t}x:ttD].}t|}tjj||||}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 rnr<rrYrrLr=rr^rdrp)r)r(r*rrrfrJrsrrrrsc@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)rsrJdelete)r2rsrJrrrr__init__sz_TemporaryFileCloser.__init__rGc Cs>|j r:|jdk r:d|_z|jjWd|jr8||jXdS)NT) close_calledrsrrrJ)r2r]rrrrs z_TemporaryFileCloser.closecCs |jdS)N)r)r2rrr__del__sz_TemporaryFileCloser.__del__cCs|jsd|_|jjdS)NT)rrsr)r2rrrrs)T) r?r@rArBrsrrrrJr]rrrrrrrs   rc@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)rsrJrr_closer)r2rsrJrrrrrsz_TemporaryFileWrapper.__init__cs^|jd}t||}t|drD|tjfdd}|j|_|}t|tsZt||||S)Nrs__call__cs ||S)Nr)r#kwargs)rxrr func_wrappersz7_TemporaryFileWrapper.__getattr__..func_wrapper) __dict__r0hasattr _functoolswrapsrrintsetattr)r2rJrsarr)rxr __getattr__s     z!_TemporaryFileWrapper.__getattr__cCs|jj|S)N)rs __enter__)r2rrrrs z_TemporaryFileWrapper.__enter__cCs|jj|||}|j|S)N)rs__exit__r)r2excvaluetbresultrrrrsz_TemporaryFileWrapper.__exit__cCs|jjdS)zA Close the temporary file, possibly deleting it. N)rr)r2rrrr sz_TemporaryFileWrapper.closeccsx|jD] }|VqWdS)N)rs)r2linerrrr4s z_TemporaryFileWrapper.__iter__N)T) r?r@rArBrrrrrr4rrrrrs rw+bTc Cst|||\}}}}t} tjdkr0|r0| tjO} t|||| |\} } y tj| ||||d} t| | |St k rtj | tj | 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. rG) bufferingnewlineencodingN) r,rZrrJZ O_TEMPORARYrtr[rr BaseExceptionr]r) moderrrr)r(r*rr+rqrrJrsrrrrs      posixcygwin O_TMPFILEc Cst|||\}}}}t}try$|tjBtj@} tj|| d} Wn*tk rXdaYnBtk rjYn0Xyt j| ||||dStj | YnXt |||||\} } ytj | t j| ||||dStj | 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,rZ_O_TMPFILE_WORKSrrO_CREATrIsADirectoryErrorrr[rrtr]) rrrrr)r(r*r+rqZflags2rrJrrrrNs0       c@seZdZdZdZd8ddZd 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/d0Zd9d1d2Zd3d4Zd5d6ZdS):rzTemporary 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|krtj|_ntjdd|_||_d|_|||||||d|_dS)Nb )rF)rrr)r(rrr*)r[BytesIO_fileStringIO _max_size_rolled_TemporaryFileArgs) r2max_sizerrrrr)r(r*rrrrs zSpooledTemporaryFile.__init__cCs,|jr dS|j}|r(|j|kr(|jdS)N)rrtellrollover)r2rsrrrr_checks zSpooledTemporaryFile._checkcCsN|jr dS|j}tf|j}|_|`|j|j|j|jdd|_dS)NrT)rrrrr\getvalueseekr)r2rsZnewfilerrrrszSpooledTemporaryFile.rollovercCs|jjrtd|S)Nz%Cannot enter context with closed file)rclosed ValueError)r2rrrrszSpooledTemporaryFile.__enter__cCs|jjdS)N)rr)r2rrrrrrrszSpooledTemporaryFile.__exit__cCs |jjS)N)rr4)r2rrrr4szSpooledTemporaryFile.__iter__cCs|jjdS)N)rr)r2rrrrszSpooledTemporaryFile.closecCs|jjS)N)rr)r2rrrrszSpooledTemporaryFile.closedc Cs8y|jjStk r2d|jdkr(|jdSXdS)Nrrr)rrrPr)r2rrrrs zSpooledTemporaryFile.encodingcCs|j|jjS)N)rrfileno)r2rrrrszSpooledTemporaryFile.filenocCs|jjdS)N)rflush)r2rrrrszSpooledTemporaryFile.flushcCs |jjS)N)risatty)r2rrrrszSpooledTemporaryFile.isattyc Cs(y|jjStk r"|jdSXdS)Nr)rrrPr)r2rrrrszSpooledTemporaryFile.modec Cs"y|jjStk rdSXdS)N)rrJrP)r2rrrrJszSpooledTemporaryFile.namec Cs8y|jjStk r2d|jdkr(|jdSXdS)Nrrr)rnewlinesrPr)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 |jjS)N)rr)r2rrrrszSpooledTemporaryFile.tellcCs6|dkr|jjn||jkr&|j|jj|dS)N)rtruncaterr)r2sizerrrrs   zSpooledTemporaryFile.truncatecCs|j}|j|}|j||S)N)rr\r)r2srsrvrrrr\s  zSpooledTemporaryFile.writecCs|j}|j|}|j||S)N)r writelinesr)r2iterablersrrrrrs  zSpooledTemporaryFile.writelines)rrrNNNNN)N)r?r@rArBrrrrrrr4rrCrrrrrrrJrrrrrrrrr\rrrrrrs8        c@sReZdZdZdddZeddZeddZd d Zd d Z d dZ ddZ 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|jdj|d|_dS)NzImplicitly cleaning up {!r}) warn_message)rrJ_weakreffinalize_cleanupformat _finalizer)r2r)r(r*rrrr(s zTemporaryDirectory.__init__cs fdd}tj|ddS)Ncst|dtr|yV|kr(ttjj|t|ytj|Wn"ttfk r`j|YnXWqt k rxYqXnt|dt rndS)Nr) issubclassr_r|rrLrSr]r_rmtreerc)rxrLexc_info)clsrJrronerror0sz+TemporaryDirectory._rmtree..onerror)r)_shutilZrmtree)rrJrr)rrJrr.szTemporaryDirectory._rmtreecCs|j|tj|tdS)N)r _warningswarnResourceWarning)rrJrrrrrEs zTemporaryDirectory._cleanupcCsdj|jj|jS)Nz <{} {!r}>)r __class__r?rJ)r2rrr__repr__JszTemporaryDirectory.__repr__cCs|jS)N)rJ)r2rrrrMszTemporaryDirectory.__enter__cCs |jdS)N)cleanup)r2rrrrrrrPszTemporaryDirectory.__exit__cCs|jjr|j|jdS)N)rdetachrrJ)r2rrrrSs zTemporaryDirectory.cleanup)NNN) r?r@rArBr classmethodrrrrrrrrrrrs    )NNNF)NNNr)rrNNNNNTr)rrNNNNN)DrB__all__ functoolsrwarningsrior[osrZshutilrerrnordZrandomrr1weakrefr_thread ImportErrorZ _dummy_thread allocate_lockZ_allocate_lockO_RDWRrO_EXCLr}rrrZrrr&rkrrrrr%r,r-rTrirjrnrtryr|r r r r r rrrrrrrJsysplatformrrrobjectrrrrrs          -   ( ' +? $  8