\dudZgdZddlZddlZddlZddlZ ddl Z ddl Z ddlmZddlZddlZddlZddlZejZe je jze jzZee dr ee jzZeZ ee dr e e j!zZ ee dre j"Z"ndZ"d Z#eZ$d Z%d Z&d Z'Gd dZ(dZ)dZ*da+dZ,dZ-dZ.dZ/da0dZ1dZ2dZ3d.dZ4d/dZ5de#dfdZ6GddZ7Gdd Z8 d0dd$d%Z9e j:d&ks ej;d'kre9ZZ?Gd,d-Z@dS)2aTemporary 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_BINARYr i'tmpcR tj|dS#t$rYdSwxYw)NTF)_oslstatOSError)fns ..\python\lib\tempfile.py_existsrLs? " t uus  &&cd}|D]}|t|tjrtj|}t|tr |t urt dt}h|turt dt }|/tttt rt StS|S)zBLook at the type of all args and divine their implied return type.Nz1Can't mix bytes and non-bytes in path components.) isinstancerPathLikefspathbytesstr TypeErrorr )args return_typeargs r_infer_return_typer%UsK ;  c3< ( ( "*S//C c5 ! ! c!!!3444KKe##!3444KK ?j#66?JL ct|||}| |}|*|turt}ntjt}|&|turt }nt }||||fS)z9Common parameter processing for most APIs in this module.)r%r templaterfsencoder r)prefixsuffixdir output_types r_sanitize_paramsr.rs|$VVS99K ~ ~ #  FF\(++F { #  ,,CC--C 63 ++r&c8eZdZdZdZedZdZdZdS)_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.%abcdefghijklmnopqrstuvwxyz0123456789_ctj}|t|ddkrt|_||_|jS)N_rng_pid)rgetpidgetattr_Random_rngr3)selfcur_pids rrngz_RandomNameSequence.rngs>*,, gdJ55 5 5 DI#DMyr&c|SNr8s r__iter__z_RandomNameSequence.__iter__s r&cjd|j|jdS)N)k)joinr:choices charactersr>s r__next__z_RandomNameSequence.__next__s+wwtx''1'==>>>r&N) __name__ __module__ __qualname____doc__rFpropertyr:r?rGr=r&rr0r0s\++9J X?????r&r0c g}dD]-}tj|}|r||.tjdkrV|tjdtjdddddgn|gd  |tjn6#ttf$r"|tj YnwxYw|S) z[Generate a list of candidate temporary directories which _get_default_tempdir will try.)TMPDIRTEMPTMPntz~\AppData\Local\Tempz%SYSTEMROOT%\Tempzc:\tempzc:\tmpz\tempz\tmp)z/tmpz/var/tmpz/usr/tmp) rgetenvappendnameextendpath expanduser expandvarsgetcwdAttributeErrorrcurdir)dirlistenvnamedirnames r_candidate_tempdir_listr_s!G+,,*W%% +GNN7+++ x4,,-DEE,,-ABB#Y'D E E E E 999:::#sz||$$$$ G $###sz"""""# Ns1&C0D  D ct}t}|D]}|tjkrtj|}t dD]?}t|}tj||} tj |td} tj |dtj |n#tj |wxYw tj |n#tj |wxYw|ccS#t$rYt$rUtjdkrAtj|r"tj|tjrY.Ynt($rYnwxYwt+t,jd|z)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.dsblatrQz)No usable temporary directory found in %s)r0r_rr[rVabspathrangenextrDopen_bin_openflagswritecloseunlinkFileExistsErrorPermissionErrorrTisdiraccessW_OKrFileNotFoundError_errnoENOENT)namerr\r,seqrTfilenamefds r_get_default_tempdirrws ! !E%''G #*  (""3''C::  C;;Dx}}S$//H Xh>>)& "g... "  " Jx((((CJx(((( "   "   H$$)<)<$JsCH--%H     FMG#$ % %%sID(0CD C00D 4D( DD(( F4AF FFctgt ttatn#twxYwtS)z7Common setup sequence for all user-callable interfaces.)_name_sequence _once_lockacquirer0releaser=r&r_get_candidate_namesr}se !%!4!6!6    J    AA,ctj|}t}|turt tj|}ttD]}t|}tj |||z|z}tj d| tj ||d} nj#t$rYpt$rRtjdkr@tj|r!tj|tjrYɂwxYw| |fcStt(jd)z>Code common to mkstemp, TemporaryFile, and NamedTemporaryFile.ztempfile.mkstemprbrQz#No usable temporary file name found)rrVrcr}rmapr)rdr rerD_sysauditrfrkrlrTrmrnrorqEEXIST) r,presufflagsr-namesrtrTfilervs r_mkstemp_innerrsH (  3  C " "EeCL%((W~~E{{x}}S#*s"233 %t,,, $u--BB    H   D  SX^^C%8%8  3))! 4x &-? A AAs2C  D0AD0.D0c4tjtS)z7The default prefix for temporary directories as string.)rfsdecoder(r=r&rr r  < ! !!r&c4tjtS)z6The default prefix for temporary directories as bytes.)rr)r(r=r&rr r rr&ctgt ttatn#twxYwtS)z&Private accessor for tempfile.tempdir.)r rzr{rwr|r=r&r _gettempdirrsb !.00    J   Nr~cBtjtS)z Returns tempfile.tempdir as str.)rrrr=r&rr r ) < & &&r&cBtjtS)z"Returns tempfile.tempdir as bytes.)rr)rr=r&rrr-rr&Fcvt|||\}}}}|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. 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_openflagsrgr)r+r*r,textr-rs rrr1sH:(8'L'L$FFC  #vvuk B BBr&ct|||\}}}}t}|turttj|}t tD]}t|}tj |||z|z}tj d| t j |dnj#t$rYot$rRtjdkr@tj |r!t j|tjrYȂwxYw|cStt(jd)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. ztempfile.mkdtemprQz(No usable temporary directory name found)r.r}rrrr)rdr rerVrDrrmkdirrkrlrTrmrnrorqr)r+r*r,r-rrtrTrs rrrXsI(8'L'L$FFC " "EeCL%((W~~E{{x}}S&4-&"899 %t,,,  IdE " " " "    H   D  SX^^C%8%8  3))!  &-D F FFs)B?? D& AD&$D&rAc0|t}t}ttD]J}t |}t j|||z|z}t|s|cSKttj d)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 r}rdr rerrVrDrrkrqr)r+r*r,rrtrTrs rrrs$ {ll " "EW~~E{{x}}S&4-&"899t}} KKK  &-> @ @@r&c\eZdZdZdZdZd dZejdkrej fdZ dZ dSd 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.NFTc0||_||_||_dSr<)rrTdeleter8rrTrs r__init__z_TemporaryFileCloser.__init__s   r&rQc|js`|j[d|_ |j|jr||jdSdS#|jr||jwwxYwdSdSNT) close_calledrrirrT)r8rjs rriz_TemporaryFileCloser.closes$ *)>$(!*IOO%%%{*ty)))))**t{*ty))))*  * *)>)>s A A%c.|dSr<)rir>s r__del__z_TemporaryFileCloser.__del__s JJLLLLLr&cX|js"d|_|jdSdSr)rrrir>s rriz_TemporaryFileCloser.closes7$ "$(! !!!!! " "r&T) rHrIrJrKrrrrrTrjrirr=r&rrrs DL x4 #z * * * *      " " " " "r&rc8eZdZdZd dZdZdZdZdZdZ d S) _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. Tc\||_||_||_t||||_dSr<)rrTrr_closerrs rrz_TemporaryFileWrapper.__init__s.   +D$?? r&c |jd}t||}t|dr/|tjfd}|j|_|}t |tst||||S)Nr__call__c|i|Sr<r=)r"kwargsfuncs r func_wrapperz7_TemporaryFileWrapper.__getattr__..func_wrapperstT,V,,,r&) __dict__r5hasattr _functoolswrapsrrintsetattr)r8rTrarrs @r __getattr__z!_TemporaryFileWrapper.__getattr__s}V$ D$   1j ! ! D  d # # - - - -$ # -$(s rrz_TemporaryFileWrapper.__enter__s  r&cf|j|||}||Sr<)r__exit__ri)r8excvaluetbresults rrz_TemporaryFileWrapper.__exit__s-##C33  r&c8|jdS)zA Close the temporary file, possibly deleting it. N)rrir>s rriz_TemporaryFileWrapper.closes r&c#&K|jD]}|VdSr<)r)r8lines rr?z_TemporaryFileWrapper.__iter__s. I  DJJJJ  r&Nr) rHrIrJrKrrrrrir?r=r&rrrs@@@@ *  r&rw+bTerrorsc  t\t tjdkr|r tjz d|vrt j|}d  fd} t j|||||| } t| d| } t| d| } | _t| |S#| xYw# &tjdkr|stj xYw)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). 'errors' -- the errors argument to io.open (default None) 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. On POSIX, NamedTemporaryFiles cannot be automatically deleted if the creating process is terminated abruptly with a SIGKILL signal. Windows can delete the file even in this case. rQbNc4t\}|Sr<)r)r"rvr,rrTr-r*r+s ropenerz"NamedTemporaryFile..opener.s!!#vvukJJD r& bufferingnewlineencodingrrbufferraw) r.rgrrT O_TEMPORARY_io text_encodingrfr5rrirj)moderrrr+r*r,rrrrrrrTr-s ``` @@@rrr sP.(8'L'L$FFC E x4F   $$X.. DxTY '(6%''' $$//C#uc**CCH(tV<< <  JJLLL   SX%5%5&%5 Jt    s*C9CCC+Dposixcygwin O_TMPFILEc  d|vrtj|}t\ t trmd  fd} tj||||||} t | d| } t | d| } | _| S#t$rdaYnt$rYnwxYwd  fd}tj||||||} t | d| } t | d| } | _| S) 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) 'errors' -- the errors 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. rNcntjztjz}tj|dS)Nrb)rrO_CREATrf)r"flags2r,rvrs rrzTemporaryFile..openerhs0#-/CK<?Xc6511 r&rrrFct\} tj|n'#t$r}tjd}~wwxYwSr<)rrrj BaseExceptionri) r"rTer,rvrr-r*r+s rrzTemporaryFile..openersj%c665+NNHB  4         "  Is. AA  A) rrr.rg_O_TMPFILE_WORKSrfr5rTIsADirectoryErrorr)rrrrr+r*r,rrrrrvrr-s ``` @@@rrrNs$ d??(22H+;FFC+P+P([  B         xTY(/('-f>>>dHd33c5#.. $ ) ) ) $)                 xTY '(6%'''dHd++c5#&& s AB B-! B-,B-cfeZdZdZdZ d(dddZeejZ d Z d Z d Z d Z d ZdZdZedZedZedZdZdZdZedZedZedZdZdZdZdZdZdZ dZ!d Z"d!Z#d"Z$d)d#Z%d$Z&d%Z'd&Z(d'Z)dS)*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. FrrrNrc  d|vrtj|_nBtj|}tjtj|| ||_||_d|_|||||||| d|_dS)Nr)rrrF)rrr+r*rrr,r)rBytesIO_filer TextIOWrapper _max_size_rolled_TemporaryFileArgs) r8max_sizerrrrr+r*r,rs rrzSpooledTemporaryFile.__init__s $;;DJJ(22H*3;==%-f$+---DJ" +/i-3v/7G*-#A#Ar&c|jrdS|j}|r.||kr|dSdSdSr<)rrtellrollover)r8rrs r_checkzSpooledTemporaryFile._checksP <>   h.. MMOOOOO  ..r&c|jrdS|j}tdi|jx}|_|`|}t |dr?|j| n'|| | |dd|_dS)NrrTr=) rrrrrrrrhdetachgetvalueseek)r8rnewfileposs rrzSpooledTemporaryFile.rollovers <z,GGt/FGGG$*  #iikk 7H % % + N !7!7!9!9 : : : : MM$--// * * * S! r&c<|jjrtd|S)Nz%Cannot enter context with closed file)rclosed ValueErrorr>s rrzSpooledTemporaryFile.__enter__s$ :  FDEE E r&c8|jdSr<rrir8rrrs rrzSpooledTemporaryFile.__exit__ r&c4|jSr<)rr?r>s rr?zSpooledTemporaryFile.__iter__z""$$$r&c|jsFtjd|td||dSdS)NzUnclosed file {!r}) stacklevelsource)r _warningswarnformatResourceWarningrir>s rrzSpooledTemporaryFile.__del__s\{  N$++D11      JJLLLLL  r&c8|jdSr<rr>s rrizSpooledTemporaryFile.closerr&c|jjSr<)rrr>s rrzSpooledTemporaryFile.closed z  r&c|jjSr<)rrr>s rrzSpooledTemporaryFile.encoding z""r&c|jjSr<)rrr>s rrzSpooledTemporaryFile.errorsrr&c\||jSr<)rrfilenor>s rr zSpooledTemporaryFile.filenos# z  """r&c8|jdSr<)rflushr>s rrzSpooledTemporaryFile.flushrr&c4|jSr<)risattyr>s rrzSpooledTemporaryFile.isattyz  """r&cV |jjS#t$r|jdcYSwxYw)Nr)rrrZrr>s rrzSpooledTemporaryFile.modes@ 3:? " 3 3 3*62 2 2 2 3s ((c> |jjS#t$rYdSwxYwr<)rrTrZr>s rrTzSpooledTemporaryFile.names3 :? "   44 s  c|jjSr<)rnewlinesr>s rrzSpooledTemporaryFile.newlines r r&c4|jSr<)rreadabler>s rrzSpooledTemporaryFile.readablerr&c |jj|Sr<)rreadr8r"s rrzSpooledTemporaryFile.readtz%%r&c |jj|Sr<)rread1rs rrzSpooledTemporaryFile.read1stz&&r&c6|j|Sr<)rreadintor8rs rr zSpooledTemporaryFile.readintosz""1%%%r&c6|j|Sr<)r readinto1r!s rr#zSpooledTemporaryFile.readinto1sz##A&&&r&c |jj|Sr<)rreadliners rr%zSpooledTemporaryFile.readlines"tz"D))r&c |jj|Sr<)r readlinesrs rr'zSpooledTemporaryFile.readlines!s#tz#T**r&c4|jSr<)rseekabler>s rr)zSpooledTemporaryFile.seekable$rr&c |jj|Sr<)rrrs rrzSpooledTemporaryFile.seek'rr&c4|jSr<)rrr>s rrzSpooledTemporaryFile.tell*sz   r&c||jS||jkr||j|Sr<)rtruncaterr)r8sizes rr-zSpooledTemporaryFile.truncate-sK <:&&(( (dn$$ :&&t,, ,r&c4|jSr<)rwritabler>s rr0zSpooledTemporaryFile.writable5rr&ch|j}||}|||Sr<)rrhr)r8srrvs rrhzSpooledTemporaryFile.write8s/z ZZ]] D r&ch|j}||}|||Sr<)r writelinesr)r8iterablerr3s rr5zSpooledTemporaryFile.writelines>s1z __X & & D r&c4|jSr<)rrr>s rrzSpooledTemporaryFile.detachDrr&)rrrNNNNNr<)*rHrIrJrKrr classmethod_types GenericAlias__class_getitem__rrrrr?rrirLrrrr rrrrTrrrrr r#r%r'r)rrr-r0rhr5rr=r&rrrsG9;(,/3A?CAAAAA"$ F$788   * %%%!!X!##X#!!X!######33X3 X ##X#%%%&&&'''&&&'''***+++%%%&&&!!!----%%%  #####r&rceZdZdZ d dZed dZed dZdZdZ d Z d Z ee j ZdS) 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. NFct||||_||_tj||j|jd||j|_dS)NzImplicitly cleaning up {!r}) warn_message ignore_errors)rrT_ignore_cleanup_errors_weakreffinalize_cleanupr _finalizer)r8r+r*r,ignore_cleanup_errorss rrzTemporaryDirectory.__init__Ts\FFC00 &;#"+ $-6==dCC5777r&cFfd}tj|dS)Nct|dtrd} |kr(|tj||| tj|dS#t tf$r|YnwxYwdS#t$rYdSwxYwt|dtrdSsdS)Nrc~ tj|dn#t$rYnwxYwtj|ddS)Nrr)rchflagsrZchmod)rVs r resetpermsz?TemporaryDirectory._rmtree..onerror..resetpermsasT D!,,,,)IdE*****s  %%r?) issubclassrlrrVr^rjr_rmtreerp)rrVexc_inforKclsr?rTs ronerrorz+TemporaryDirectory._rmtree..onerror_s(1+77 +++ t||" 38#3#3D#9#9:::Jt$$$G 4(((((-?GGG D FFFFFGFF(DDHQK):;; $s/9B!A11(BB!BB!! B/.B/)rQ)_shutilrmtree)rPrTr?rQs``` rrNzTemporaryDirectory._rmtree]sE       6 tW------r&ch|||tj|tdSNrL)rNrrr)rPrTr>r?s rrCzTemporaryDirectory._cleanup|s0 D 666|_55555r&cLd|jj|jS)Nz <{} {!r}>)r __class__rHrTr>s r__repr__zTemporaryDirectory.__repr__s!!$."949EEEr&c|jSr<)rTr>s rrzTemporaryDirectory.__enter__s yr&c.|dSr<)cleanuprs rrzTemporaryDirectory.__exit__s r&c|js$tj|jr#||j|jdSdSrU)rDrrrVexistsrTrNr@r>s rr[zTemporaryDirectory.cleanups^ ? ! ! # # Osxty'A'A O LL$2ML N N N N N O Or&NNNF)F)rHrIrJrKrr8rNrCrXrrr[r9r:r;r=r&rrrHs  6:',7777...[.<666[6FFFOOO$ F$788r&rr^)NNN)rrNNNNNT)rrNNNNN)ArK__all__ functoolsrwarningsriorosrshutilrRerrnorqrandomrr6sysrtypesr9weakrefrA_thread allocate_lock_allocate_lockO_RDWRrO_EXCLrrrrgrr r(rzrr%r.r0r_rwryr}rr r r rr rrrrrrrrTplatformrrIOBaserrr=r&rrqs2   $$$$$$&*s{*SZ7 73 &s~%O  73 #cl"N 73 kGGG ^   :,,,$????????06*%*%*%X   AAA@""""""    ''''''$C$C$C$CN&F&F&F&FPX4@@@@@("("("("("("("("V<<<<<<<<~;?9=(,78<77777r8w$-833'MM wsK009=8<I*.IIIIIVl#l#l#l#l#3:l#l#l#^F9F9F9F9F9F9F9F9F9F9r&