a xa@sddZgdZddlZddlZddlZddlZ zddl Z e j Z WnneyddlZddlZddZddZe je je je jhe jkoe je jvoe je jvZdCd d Z Yn0ddlZdd lm Z!ddlZddl"Z#ddl$Z%ddl&Z&e&j'Z(e j)e j*Be j+BZ,e-e d re,e j.OZ,e,Z/e-e d r*e/e j0OZ/e-e dr>e j1Z1ndZ1dZ2e(Z3ddZ4ddZ5ddZ6GdddZ7ddZ8ddZ9da:ddZ;dd Zda?d%d&Z@d'd(ZAdDd)d*ZBdEd+d,ZCd-e2dfd.d/ZDGd0d1d1ZEGd2d3d3ZFdFdd7d8d9ZGe jHd:ks"ejId;kr(eGZJne-e d<aKdGdd7d=d>ZJGd?d@d@ZLGdAdBdBeMZNdS)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 Cs@ztj|rtdWn(ty@|tjj|tYdS0g}zt|}Wn$tyx|tj|tYn0|D]}tj||}zt|j }Wntyd}Yn0t |rt ||q~zt |Wq~ty|tj |tYq~0q~zt|Wn&ty:|tj|tYn0dS)N%Cannot call rmtree on a symbolic linkr)_ospathislinkOSError_sysexc_infolistdirjoinlstatst_mode_statS_ISDIR_rmtree_unsafeunlinkrmdir)ronerrornamesnamefullnamemoder$/usr/lib/python3.9/tempfile.pyr2s6        rc Csg}zt|}Wn<tyN}z$||_|tj|tWYd}~n d}~00|D]x}tj||}ztj||dd}|j }Wntyd}Yn0t |rztj |tj |d} Wn$ty|tj |tYn0ztj|t| rBt| ||ztj||dWn&ty>|tj|tYn0n6z tdWn(tyv|tjj|tYn0Wt| n t| 0qTztj||dWqTty|tj|tYqT0qTdS)NF)dir_fdfollow_symlinksr)r&r)rrrfilenamerrrrstatrrropenO_RDONLYsamestatfstat_rmtree_safe_fdrrcloser) topfdrrr errr!r"orig_str#dirfdr$r$r%r.SsD(        r.Fc Csd|rdd}n|durdd}trVt|tr8t|}zt|}Wn&tyl|tj|tYdS0zt |tj }Wn&ty|tj|tYdS0ztj |t |rt|||zt|Wn&ty|tj|tYn0n6z tdWn(ty8|tj j|tYn0Wt|n t|0n 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. cWsdSNr$argsr$r$r%rsz_rmtree..onerrorNcWsdSr4r$r5r$r$r%rsr)_use_fd_functions isinstancebytesrfsdecoder Exceptionrrr*r+rr,r-r.rrrr/r)r ignore_errorsrr2fdr$r$r%_rmtrees<        r>)Random O_NOFOLLOWO_BINARYri'tmpcCs,zt|Wnty"YdS0dSdS)NFT)rrr)fnr$r$r%_existss  rDcGs\d}|D]B}|durqt|tr6|tur0tdt}q|turFtdt}q|durXtS|S)zBLook at the type of all args and divine their implied return type.Nz1Can't mix bytes and non-bytes in path components.)r8r9str TypeError)r6Z return_typeargr$r$r%_infer_return_types rHcCsdt|||}|dur|}|dur:|tur0t}n tt}|durX|turRt}nt}||||fS)z9Common parameter processing for most APIs in this module.N)rHrEtemplaterfsencoder r )prefixsuffixdir output_typer$r$r%_sanitize_paramss  rOc@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_rngrQ)selfZcur_pidr$r$r%rngs z_RandomNameSequence.rngcCs|Sr4r$rUr$r$r%__iter__sz_RandomNameSequence.__iter__cs0|j|jjfddtdD}d|S)Ncsg|] }qSr$r$).0ZdummycZchooser$r% z0_RandomNameSequence.__next__..) charactersrVZchoiceranger)rUZlettersr$rZr%__next__sz_RandomNameSequence.__next__N) __name__ __module__ __qualname____doc__r`propertyrVrXrbr$r$r$r%rPs  rPc Csg}dD]}t|}|r||qtjdkrX|tjdtjdddddgn|gd z|tWn"t t fy|tj Yn0|S) z[Generate a list of candidate temporary directories which _get_default_tempdir will try.)ZTMPDIRZTEMPZTMPntz~\AppData\Local\Tempz%SYSTEMROOT%\Tempzc:\tempzc:\tmpz\tempz\tmp)z/tmpz/var/tmpz/usr/tmp) rgetenvappendr!extendr expanduser expandvarsgetcwdAttributeErrorrcurdir)dirlistZenvnamedirnamer$r$r%_candidate_tempdir_list"s   rsc Csht}t}|D]@}|tjkr,tj|}tdD]}t|}tj||}zt |t d}zdzHt j |ddd}| dWdn1s0YWt |n t |0Wt|n t|0|WStyYq4ty6tjdkr,tj|r,t|tjr,Yq4YqYq4tyNYqYq40q4qttjd |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.dwbF)closefdsblatNrhz)No usable temporary directory found in %s)rPrsrrprabspathranextrr*_bin_openflags_iowriter/rFileExistsErrorPermissionErrorr!isdiraccessW_OKrFileNotFoundError_errnoZENOENT)ZnamerrqrMseqr!r(r=fpr$r$r%_get_default_tempdir=s@    *   rcCs:tdur6tztdur taWtn t0tS)z7Common setup sequence for all user-callable interfaces.N)_name_sequence _once_lockacquirerPreleaser$r$r$r%_get_candidate_nameslsrc Cst}|turttj|}ttD]}t|}tj ||||}t d|zt ||d} WnRt yxYq"Yn>tytjdkrtj|rt|tjrYq"nYn0| tj|fSt tjddS)z>Code common to mkstemp, TemporaryFile, and NamedTemporaryFile.ztempfile.mkstemprurhz#No usable temporary file name foundN)rr9maprrJrarryrrrauditr*r}r~r!rrrrxrEEXIST) rMZpreZsufflagsrNr rr!filer=r$r$r%_mkstemp_innerzs*      rcCstS)z-The default prefix for temporary directories.)rIr$r$r$r%r sr cCs ttS)z6The default prefix for temporary directories as bytes.)rrJr r$r$r$r%r sr cCs:tdur6tztdur taWtn t0tS)zAccessor for tempfile.tempdir.N)r rrrrr$r$r$r%r sr cCs ttS)z)A bytes version of tempfile.gettempdir().)rrJr r$r$r$r%r sr cCs2t|||\}}}}|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. )rO_text_openflagsrzr)rLrKrMtextrNrr$r$r%rs rc Cst|||\}}}}t}|tur.ttj|}ttD]}t|}tj ||||}t d|zt |dWnRtyYq6Yn>tytjdkrtj |rt|tjrYq6nYn0|SttjddS)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.mkdtemprhz(No usable temporary directory name foundN)rOrr9rrrJrarryrrrrmkdirr}r~r!rrrrr)rLrKrMrNr rr!rr$r$r%rs,       rr_cCs`|durt}t}ttD]2}t|}tj||||}t|s|Sqt 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 rrarryrrrrDr}rr)rLrKrMr rr!rr$r$r%rs  rc@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||_||_||_dSr4)rr!deleterUrr!rr$r$r%__init__*sz_TemporaryFileCloser.__init__rhcCsL|jsH|jdurHd|_z|jW|jrH||jn|jrF||j0dSNT) close_calledrr/rr!)rUrr$r$r%r/9s  z_TemporaryFileCloser.closecCs |dSr4)r/rWr$r$r%__del__Csz_TemporaryFileCloser.__del__cCs|jsd|_|jdSr)rrr/rWr$r$r%r/Gs)T) rcrdrerfrrrrr!rr/rr$r$r$r%r"s   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||||_dSr4)rr!rr_closerrr$r$r%rUsz_TemporaryFileWrapper.__init__cs^|jd}t||}t|drD|tfdd}|j|_|}t|tsZt||||S)Nr__call__cs|i|Sr4r$)r6kwargsfuncr$r% func_wrappercsz7_TemporaryFileWrapper.__getattr__..func_wrapper) __dict__rShasattr _functoolswrapsrr8intsetattr)rUr!rarr$rr% __getattr__[s     z!_TemporaryFileWrapper.__getattr__cCs|j|Sr4)r __enter__rWr$r$r%rps z_TemporaryFileWrapper.__enter__cCs|j|||}||Sr4)r__exit__r/)rUexcvaluetbresultr$r$r%rvsz_TemporaryFileWrapper.__exit__cCs|jdS)zA Close the temporary file, possibly deleting it. N)rr/rWr$r$r%r/{sz_TemporaryFileWrapper.closeccs|jD] }|VqdSr4)r)rUliner$r$r%rXs z_TemporaryFileWrapper.__iter__N)T) rcrdrerfrrrrr/rXr$r$r$r%rMs rw+bTerrorscCst|||\}}}} t} tjdkr0|r0| tjO} t|||| | \} } z$tj| |||||d} t| | |WSt yt | t | Yn0dS)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. rh bufferingnewlineencodingrN) rOrzrr!Z O_TEMPORARYrr{r*r BaseExceptionrr/)r#rrrrLrKrMrrrNrr=r!rr$r$r%rs     rposixcygwin O_TMPFILEc Cst|||\}}}}t} trz$| tjBtj@} t|| d} Wn&tyVdaYnDtyfYn40zt j| |||||dWSt | Yn0t |||| |\} } z"t | t j| |||||dWSt | Yn0dS)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. ruFrN) rOrz_O_TMPFILE_WORKSrrO_CREATr*IsADirectoryErrorrr{r/rr) r#rrrrLrKrMrrNrZflags2r=r!r$r$r%rs6       rc@seZdZdZdZd8dddd ZeejZ d d Z d d Z ddZ ddZ ddZddZeddZeddZeddZddZddZd d!Zed"d#Zed$d%Zed&d'Zd(d)Zd*d+Zd,d-Zd.d/Zd0d1Zd9d2d3Zd4d5Z d6d7Z!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  CsTd|vrt|_ntjt|| |d|_||_d|_|||||||| d|_dS)Nb)rrrF)r#rrLrKrrrMr)r{BytesIO_file TextIOWrapper _max_size_rolled_TemporaryFileArgs) rUmax_sizer#rrrrLrKrMrr$r$r%rs  zSpooledTemporaryFile.__init__cCs,|jr dS|j}|r(||kr(|dSr4)rrtellrollover)rUrrr$r$r%_checks zSpooledTemporaryFile._checkcCsv|jr dS|j}tfi|j}|_|`|}t|drR|j| n|| | |dd|_dS)NbufferrT) rrrrrrrr|detachgetvalueseek)rUrZnewfileposr$r$r%rs   zSpooledTemporaryFile.rollovercCs|jjrtd|S)Nz%Cannot enter context with closed file)rclosed ValueErrorrWr$r$r%r.szSpooledTemporaryFile.__enter__cCs|jdSr4rr/rUrrrr$r$r%r3szSpooledTemporaryFile.__exit__cCs |jSr4)rrXrWr$r$r%rX7szSpooledTemporaryFile.__iter__cCs|jdSr4rrWr$r$r%r/:szSpooledTemporaryFile.closecCs|jjSr4)rrrWr$r$r%r=szSpooledTemporaryFile.closedcCs|jjSr4)rrrWr$r$r%rAszSpooledTemporaryFile.encodingcCs|jjSr4)rrrWr$r$r%rEszSpooledTemporaryFile.errorscCs||jSr4)rrfilenorWr$r$r%rIszSpooledTemporaryFile.filenocCs|jdSr4)rflushrWr$r$r%rMszSpooledTemporaryFile.flushcCs |jSr4)risattyrWr$r$r%rPszSpooledTemporaryFile.isattycCs,z |jjWSty&|jdYS0dS)Nr#)rr#rorrWr$r$r%r#Ss  zSpooledTemporaryFile.modecCs$z |jjWStyYdS0dSr4)rr!rorWr$r$r%r!Zs  zSpooledTemporaryFile.namecCs|jjSr4)rnewlinesrWr$r$r%raszSpooledTemporaryFile.newlinescGs |jj|Sr4)rreadrUr6r$r$r%reszSpooledTemporaryFile.readcGs |jj|Sr4)rreadlinerr$r$r%rhszSpooledTemporaryFile.readlinecGs |jj|Sr4)r readlinesrr$r$r%rkszSpooledTemporaryFile.readlinescGs |jj|Sr4)rrrr$r$r%rnszSpooledTemporaryFile.seekcCs |jSr4)rrrWr$r$r%rqszSpooledTemporaryFile.tellcCs6|dur|jn||jkr&||j|dSr4)rtruncaterr)rUsizer$r$r%rts   zSpooledTemporaryFile.truncatecCs|j}||}|||Sr4)rr|r)rUsrrvr$r$r%r||s  zSpooledTemporaryFile.writecCs|j}||}|||Sr4)r writelinesr)rUiterablerrr$r$r%rs  zSpooledTemporaryFile.writelines)rrrNNNNN)N)"rcrdrerfrr classmethod_types GenericAlias__class_getitem__rrrrrXr/rgrrrrrrr#r!rrrrrrrr|rr$r$r$r%rsL         rc@s\eZdZdZdddZeddZeddZd d Zd d Z d dZ ddZ 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. NcCs0t||||_tj||j|jd|d|_dS)NzImplicitly cleaning up {!r}) warn_message)rr!_weakrefZfinalize_cleanupformat _finalizer)rUrLrKrMr$r$r%rs  zTemporaryDirectory.__init__csfdd}t|ddS)Nc st|dtrdd}zT|kr0|tj|||zt|Wn ttfyf|Yn0Wqty|Yq0nt|dtrndS)NrcSs4zt|dWnty"Yn0t|ddS)Nrr)rZchflagsrochmod)rr$r$r% resetpermss  z?TemporaryDirectory._rmtree..onerror..resetperms) issubclassr~rrrrrrr>r)rrrrclsr!r$r%rs z+TemporaryDirectory._rmtree..onerror)r)r>)rr!rr$rr%r>szTemporaryDirectory._rmtreecCs||t|tdSr4)r> _warningswarnResourceWarning)rr!rr$r$r%rs zTemporaryDirectory._cleanupcCsd|jj|jS)Nz <{} {!r}>)r __class__rcr!rWr$r$r%__repr__szTemporaryDirectory.__repr__cCs|jSr4)r!rWr$r$r%rszTemporaryDirectory.__enter__cCs |dSr4)cleanuprr$r$r%rszTemporaryDirectory.__exit__cCs|jr||jdSr4)rrr>r!rWr$r$r%rs zTemporaryDirectory.cleanup)NNN)rcrdrerfrrr>rrrrrrrrr$r$r$r%rs   r)FN)NNNF)NNN)rrNNNNNT)rrNNNNN)Orf__all__ functoolsrwarningsrior{osrZshutilZ_shutilZrmtreer> ImportErrorsysrr)rrr.r*rrsupports_dir_fdr supports_fdsupports_follow_symlinksr7errnorZrandomr?rTtypesrweakrefr_thread allocate_lockZ_allocate_lockO_RDWRrO_EXCLrrr@rzrArrIrrDrHrOrPrsrrrrr r r r r rrrrrrr!platformrrrobjectrr$r$r$r%s   !,  3       -  ' ( +? '  <