Fa{@sdZddddddddd d d d d g ZddlZddlZddlZddlZ yddl Z e j Z Wnek rddlZddlZddZddZe je je je jhe jkoe je jkoe je jkZddddZ YnXddlZddlm Z!ddl"Z#yddl$Z$Wnek rvddl%Z$YnXe$j&Z'e j(e j)Be j*BZ+e,e dre+e j-OZ+e+Z.e,e dre.e j/OZ.e,e dre j0Z0ndZ0dZ1e'Z2e,e dr e j3Zn'e,e dr;e jZn ddZd d!Z4d"d#Z5d$d%Z6Gd&d'd'Z7d(d)Z8d*d+Z9da:d,d-Z;d.d/Z<d0d Z=d1d Z>da?d2d Z@d3d ZAddddd4dZBdddd5dZCd6e1dd7dZDGd8d9d9ZEGd:d;d;ZFd<dFdddddd>d?dZGe jHd@kse jjIdAkreGZJn0e,e dBaKd<dGddddddCdZJGdDddZLGdEddeMZNdS)HaTemporary 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 gettempdirbNc$Csy"tjj|r!tdWn2tk rV|tjj|tjdSYnXg}ytj|}Wn+tk r|tj|tjYnXx|D]}tjj||}ytj|j }Wntk rd}YnXt j |rt ||qytj |Wqtk rN|tj |tjYqXqWytj|Wn+tk r|tj|tjYnXdS)Nz%Cannot call rmtree on a symbolic linkr)_ospathislinkOSError_sysexc_infolistdirjoinlstatst_mode_statS_ISDIR_rmtree_unsafeunlinkrmdir)ronerrornamesnamefullnamemoder#/usr/lib/python3.5/tempfile.pyr2s6       " rc 0Cs@g}ytj|}WnGtk rb}z'||_|tj|tjWYdd}~XnXx|D]}tjj||}y(tj|d|dd}|j }Wntk rd}YnXt j |rytj |tj d|} Wn+tk r#|tj |tjYq8Xztjj|tj| rt| ||ytj|d|Wqtk r|tj|tjYqXnAytdWn.tk r|tjj|tjYnXWdtj| Xqjytj|d|Wqjtk r7|tj|tjYqjXqjWdS)Ndir_fdfollow_symlinksFrz%Cannot call rmtree on a symbolic link)rrrfilenamerrrrstatrrropenO_RDONLYsamestatfstat_rmtree_safe_fdrrcloser) topfdrrrerrr r!orig_str"dirfdr#r#r$r-SsD ,      ! % r-Fc!Cs|rdd}n|dkr-dd}trt|trQtj|}ytj|}Wn/tk r|tj|tjdSYnXytj |tj }Wn/tk r|tj|tjdSYnXztj j |tj |rTt|||ytj|Wqtk rP|tj|tjYqXnAytdWn.tk r|tj j|tjYnXWdtj|Xn t||SdS)aRecursively delete a directory tree. If ignore_errors is set, errors are ignored; otherwise, if onerror is set, it is called to handle the error with arguments (func, path, exc_info) where func is platform and implementation dependent; path is the argument to that function that caused it to fail; and exc_info is a tuple returned by sys.exc_info(). If ignore_errors is false and onerror is None, an exception is raised. cWsdS)Nr#)argsr#r#r$rsz_rmtree..onerrorNcWsdS)Nr#)r3r#r#r$rsz%Cannot call rmtree on a symbolic link)_use_fd_functions isinstancebytesrfsdecoder Exceptionrrr)r*rr+r,r-rrrr.r)r ignore_errorsrr1fdr#r#r$_rmtrees<        ! %r;)Random O_NOFOLLOWO_BINARYi'Ztmprr(cCs&tj|tj}tj|dS)N)rr)r*r.)fnr:r#r#r$rsrc Cs/yt|Wntk r&dSYnXdSdS)NFT)rr)r?r#r#r$_existss   r@cGsd}xk|D]c}|dkr"q t|trR|tkrItdt}q |tkrjtdt}q W|dkrtS|S)zBLook at the type of all args and divine their implied return type.Nz1Can't mix bytes and non-bytes in path components.)r5r6str TypeError)r3Z return_typeargr#r#r$_infer_return_types         rDcCst|||}|dkr'|}|dkrW|tkrHt}ntjt}|dkr|tkr{t}n t}||||fS)z9Common parameter processing for most APIs in this module.N)rDrAtemplaterfsencoder r )prefixsuffixdir output_typer#r#r$_sanitize_paramss         rKc@sFeZdZdZdZeddZddZddZd S) _RandomNameSequencea*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.Z%abcdefghijklmnopqrstuvwxyz0123456789_cCs@tj}|t|ddkr9t|_||_|jS)N_rng_pid)rgetpidgetattr_RandomZ_rngrM)selfZcur_pidr#r#r$rngs    z_RandomNameSequence.rngcCs|S)Nr#)rQr#r#r$__iter__%sz_RandomNameSequence.__iter__csD|j|jjfddtdD}dj|S)Ncsg|]}qSr#r#).0Zdummy)cchooser#r$ +s z0_RandomNameSequence.__next__..) charactersrRZchoiceranger)rQZlettersr#)rUrVr$__next__(s  "z_RandomNameSequence.__next__N) __name__ __module__ __qualname____doc__rZpropertyrRrSr\r#r#r#r$rLs  rLc Csg}x0d D](}tj|}|r |j|q Wtjdkrd|jddddgn|jd d d gy|jtjWn(ttfk r|jtjYnX|S) z[Generate a list of candidate temporary directories which _get_default_tempdir will try.TMPDIRTEMPTMPntzc:\tempzc:\tmpz\tempz\tmpz/tmpz/var/tmpz/usr/tmp)rbrcrd) rgetenvappendr extendgetcwdAttributeErrorrcurdir)dirlistZenvnamedirnamer#r#r$_candidate_tempdir_list.s rncCs~t}t}xO|D]G}|tjkr@tjj|}xtdD]}t|}tjj||}yvtj |t d}zHz3t j |ddd}|j dWdQRXWdtj |XWdtj|X|SWqMtk rYqMtk rItjdkrDtjj|rDtj|tjrDwMPYqMtk r[PYqMXqMWqWttjd |dS) aqCalculate 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.diwbclosefdFsblatNrez)No usable temporary directory found in %s)rLrnrrkrabspathr[nextrr)_bin_openflags_iowriter.rFileExistsErrorPermissionErrorr isdiraccessW_OKrFileNotFoundError_errnoENOENT)ZnamerrlrIseqr r'r:fpr#r#r$_get_default_tempdirGs:      !  rc CsAtdkr=tjztdkr.taWdtjXtS)z7Common setup sequence for all user-callable interfaces.N)_name_sequence _once_lockacquirerLreleaser#r#r#r$_get_candidate_namesvs     rc Cst}|tkr'ttj|}xttD]}t|}tjj ||||}ytj ||d} Wnet k rw4YnQt k rtj dkrtjj|rtj|tjrw4nYnX| tjj|fSWt tjddS)z>Code common to mkstemp, TemporaryFile, and NamedTemporaryFile.irez#No usable temporary file name foundN)rr6maprrFr[rrsrrr)rwrxr ryrzr{rrr}EEXIST) rIZpreZsufflagsrJrrr filer:r#r#r$_mkstemp_inners$     ! rcCstS)z-The default prefix for temporary directories.)rEr#r#r#r$r scCstjtS)z6The default prefix for temporary directories as bytes.)rrFr r#r#r#r$r sc CsAtdkr=tjztdkr.taWdtjXtS)zAccessor for tempfile.tempdir.N)r rrrrr#r#r#r$r s     cCstjtS)z)A bytes version of tempfile.gettempdir().)rrFr r#r#r#r$r scCsIt|||\}}}}|r-t}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. )rK_text_openflagsrtr)rHrGrItextrJrr#r#r$rs  c Cst|||\}}}}t}|tkrEttj|}xttD]}t|}tj j ||||}ytj |dWnet k rwRYnQt k rtjdkrtj j|rtj|tjrwRnYnX|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. irez(No usable temporary directory name foundN)rKrr6rrrFr[rrsrrmkdirrwrxr ryrzr{r}r)rHrGrIrJrrr rr#r#r$rs&      ! rYcCs|dkrt}t}xMttD]?}t|}tjj||||}t|s+|Sq+Wt 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 rr[rrsrrrr@rwr}r)rHrGrIrrr rr#r#r$r s      c@smeZdZdZdZdZdddZejdkr]ej dd Z d d Z n d 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)rr delete)rQrr rr#r#r$__init__3s  z_TemporaryFileCloser.__init__rec CsQ|j rM|jdk rMd|_z|jjWd|jrL||jXdS)NT) close_calledrr.rr )rQrr#r#r$r.Bs   z_TemporaryFileCloser.closecCs|jdS)N)r.)rQr#r#r$__del__Lsz_TemporaryFileCloser.__del__cCs#|jsd|_|jjdS)NT)rrr.)rQr#r#r$r.Ps  ) r]r^r_r`rrrrr rr.rr#r#r#r$r+s  rc@saeZdZdZdddZddZddZd 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. TcCs4||_||_||_t||||_dS)N)rr rr_closer)rQrr rr#r#r$r^s   z_TemporaryFileWrapper.__init__cs|jd}t||}t|drd|tjfdd}|j|_|}t|tst||||S)Nr__call__cs ||S)Nr#)r3kwargs)funcr#r$ func_wrapperlsz7_TemporaryFileWrapper.__getattr__..func_wrapper) __dict__rOhasattr _functoolswrapsrr5intsetattr)rQr rarr#)rr$ __getattr__ds ! z!_TemporaryFileWrapper.__getattr__cCs|jj|S)N)r __enter__)rQr#r#r$rys z_TemporaryFileWrapper.__enter__cCs&|jj|||}|j|S)N)r__exit__r.)rQexcvaluetbresultr#r#r$rs z_TemporaryFileWrapper.__exit__cCs|jjdS)zA Close the temporary file, possibly deleting it. N)rr.)rQr#r#r$r.sz_TemporaryFileWrapper.closeccsx|jD] }|Vq WdS)N)r)rQliner#r#r$rSsz_TemporaryFileWrapper.__iter__N) r]r^r_r`rrrrr.rSr#r#r#r$rVs     rzw+bTc Cst|||\}}}}t} tjdkrF|rF| tjO} t|||| |\} } y8tj| |d|d|d|} t| | |SWn/t 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. re bufferingnewlineencodingN) rKrtrr Z O_TEMPORARYrrur)r BaseExceptionrr.) r"rrrrHrGrIrrJrr:r rr#r#r$rs    posixcygwin O_TMPFILEc Cs5t|||\}}}}t}try.|tjBtj@} tj|| d} Wn)tk rrdaYnStk rYnBXy&t j| |d|d|d|SWntj | YnXt |||||\} } y3tj | t j| |d|d|d|SWntj | 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. iFrrrN) rKrt_O_TMPFILE_WORKSrrO_CREATr)IsADirectoryErrorrrur.rr) r"rrrrHrGrIrJrZflags2r:r r#r#r$rs0      c @s{eZdZdZdZddd7dddddddZd 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/d0Zdd1d2Zd3d4Zd5d6ZdS)8rzTemporary 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. Frzw+brNc Cs|d|krtj|_ntjdd|_||_d|_d|d|d|d|d |d|d |i|_dS) Nbr Fr"rrHrGrrI)ruBytesIO_fileStringIO _max_size_rolled_TemporaryFileArgs) rQmax_sizer"rrrrHrGrIr#r#r$rs      zSpooledTemporaryFile.__init__cCs<|jr dS|j}|r8|j|kr8|jdS)N)rrtellrollover)rQrrr#r#r$_checks   zSpooledTemporaryFile._checkcCsh|jr dS|j}t|j}|_|`|j|j|j|jdd|_dS)NrT)rrrrrvgetvalueseekr)rQrZnewfiler#r#r$rs  zSpooledTemporaryFile.rollovercCs|jjrtd|S)Nz%Cannot enter context with closed file)rclosed ValueError)rQr#r#r$r/s  zSpooledTemporaryFile.__enter__cCs|jjdS)N)rr.)rQrrrr#r#r$r4szSpooledTemporaryFile.__exit__cCs |jjS)N)rrS)rQr#r#r$rS8szSpooledTemporaryFile.__iter__cCs|jjdS)N)rr.)rQr#r#r$r.;szSpooledTemporaryFile.closecCs |jjS)N)rr)rQr#r#r$r>szSpooledTemporaryFile.closedc CsHy|jjSWn3tk rCd|jdkr4|jdSYnXdS)Nrr"r)rrrjr)rQr#r#r$rBs  zSpooledTemporaryFile.encodingcCs|j|jjS)N)rrfileno)rQr#r#r$rKs zSpooledTemporaryFile.filenocCs|jjdS)N)rflush)rQr#r#r$rOszSpooledTemporaryFile.flushcCs |jjS)N)risatty)rQr#r#r$rRszSpooledTemporaryFile.isattyc Cs2y|jjSWntk r-|jdSYnXdS)Nr")rr"rjr)rQr#r#r$r"Us zSpooledTemporaryFile.modec Cs+y|jjSWntk r&dSYnXdS)N)rr rj)rQr#r#r$r \s zSpooledTemporaryFile.namec CsHy|jjSWn3tk rCd|jdkr4|jdSYnXdS)Nrr"r)rnewlinesrjr)rQr#r#r$rcs  zSpooledTemporaryFile.newlinescGs|jj|S)N)rread)rQr3r#r#r$rlszSpooledTemporaryFile.readcGs|jj|S)N)rreadline)rQr3r#r#r$roszSpooledTemporaryFile.readlinecGs|jj|S)N)r readlines)rQr3r#r#r$rrszSpooledTemporaryFile.readlinescGs|jj|dS)N)rr)rQr3r#r#r$ruszSpooledTemporaryFile.seekcCs |jjS)N)r softspace)rQr#r#r$rxszSpooledTemporaryFile.softspacecCs |jjS)N)rr)rQr#r#r$r|szSpooledTemporaryFile.tellcCsI|dkr|jjn)||jkr5|j|jj|dS)N)rtruncaterr)rQsizer#r#r$rs   zSpooledTemporaryFile.truncatecCs)|j}|j|}|j||S)N)rrvr)rQsrrvr#r#r$rvs  zSpooledTemporaryFile.writecCs)|j}|j|}|j||S)N)r writelinesr)rQiterablerrr#r#r$rs  zSpooledTemporaryFile.writelines)r]r^r_r`rrrrrrrSr.rarrrrrr"r rrrrrrrrrvrr#r#r#r$rs8                 c@smeZdZdZdddddZeddZddZd 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. NcCsFt||||_tj||j|jddj||_dS)N warn_messagezImplicitly cleaning up {!r})rr _weakreffinalize_cleanupformat _finalizer)rQrHrGrIr#r#r$rszTemporaryDirectory.__init__cCst|tj|tdS)N)r; _warningswarnResourceWarning)clsr rr#r#r$rs zTemporaryDirectory._cleanupcCsdj|jj|jS)Nz <{} {!r}>)r __class__r]r )rQr#r#r$__repr__szTemporaryDirectory.__repr__cCs|jS)N)r )rQr#r#r$rszTemporaryDirectory.__enter__cCs|jdS)N)cleanup)rQrrrr#r#r$rszTemporaryDirectory.__exit__cCs |jjrt|jdS)N)rdetachr;r )rQr#r#r$rszTemporaryDirectory.cleanup) r]r^r_r`r classmethodrrrrrr#r#r#r$rs    rr)Or`__all__ functoolsrwarningsrioruosrZshutilZ_shutilZrmtreer; ImportErrorsysrr(rrr-r)rrsupports_dir_fdr supports_fdsupports_follow_symlinksr4errnor}Zrandomr<rPweakrefr_threadZ _dummy_thread allocate_lockZ_allocate_lockO_RDWRrO_EXCLrrr=rtr>rrErrr@rDrKrLrnrrrrr r r r r rrrrrrr platformrrrobjectrr#r#r#r$s           ! , 3               -     (' +?  $!   8