a DOg;m@sdZgdZddlZddlZddlZddlZ ddl Z ddl Z ddlmZddlZddlZddlZddlZejZe je jBe jBZee dree jOZeZ ee dre e j!OZ ee dre j"Z"ndZ"d Z#eZ$d d Z%d d Z&ddZ'GdddZ(ddZ)ddZ*da+ddZ,ddZ-ddZ.ddZ/ddZ0d d!Z1da2d"d#Z3d$d%Z4dAd'd(Z5dBd)d*Z6d+e#dfd,d-Z7Gd.d/d/Z8Gd0d1d1Z9dCdd5d6d7Z:e j;d8ksejdDdd5d;d<Z=Gd=d>d>Z?Gd?d@d@e@ZAdS)EaTemporary 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_BINARYri'tmpcCs,zt|Wnty"YdS0dSdS)NFT)_oslstatOSError)fnr /usr/lib64/python3.9/tempfile.py_existsLs  rcGsrd}|D]X}|durqt|tjr,t|}t|trL|turFtdt}q|tur\tdt}q|durntS|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 TypeError)args return_typeargrrr_infer_return_typeUs    r#cCsdt|||}|dur|}|dur:|tur0t}n tt}|durX|turRt}nt}||||fS)z9Common parameter processing for most APIs in this module.N)r#rtemplaterfsencoder r )prefixsuffixdir output_typerrr_sanitize_paramsns  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.%abcdefghijklmnopqrstuvwxyz0123456789_cCs,t}|t|ddkr&t|_||_|jS)N_rng_pid)rgetpidgetattr_Random_rngr-)selfcur_pidrrrrngs z_RandomNameSequence.rngcCs|SNrr2rrr__iter__sz_RandomNameSequence.__iter__cs0|j|jjfddtdD}d|S)Ncsg|] }qSrr).0dummycchooserr z0_RandomNameSequence.__next__..) charactersr4choicerangejoin)r2lettersrr:r__next__sz_RandomNameSequence.__next__N) __name__ __module__ __qualname____doc__rApropertyr4r7rFrrrrr+s  r+c 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.)TMPDIRTEMPTMPntz~\AppData\Local\Tempz%SYSTEMROOT%\Tempzc:\tempzc:\tmpz\tempz\tmp)z/tmpz/var/tmpz/usr/tmp) rgetenvappendnameextendpath expanduser expandvarsgetcwdAttributeErrorrcurdir)dirlistenvnamedirnamerrr_candidate_tempdir_lists   r]c 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)closefdsblatNrOz)No usable temporary directory found in %s)r+r]rrYrTabspathrCnextrDopen_bin_openflags_iowritecloseunlinkFileExistsErrorPermissionErrorrRisdiraccessW_OKrFileNotFoundError_errnoENOENT)namerrZr(seqrRfilenamefdfprrr_get_default_tempdirs@    *   rwcCs:tdur6tztdur taWtn t0tS)z7Common setup sequence for all user-callable interfaces.N)_name_sequence _once_lockacquirer+releaserrrr_get_candidate_namessr|c 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.mkstempr_rOz#No usable temporary file name foundN)r|rmaprr%rCrrcrTrD_sysauditrdrjrkrRrlrmrnrbrpEEXIST) r(presufflagsr)namesrsrRfilerurrr_mkstemp_inners*      rcGsL|tjvr"||g|Rddin&tjdks8tj|sH||g|RdS)Nfollow_symlinksFrO)rsupports_follow_symlinksrRrTislink)funcrTr rrr_dont_follow_symlinkss rcCs<z tj}WntyYn0t||dttj|ddS)Nr)rchflagsrXrchmod)rTrrrr _resetpermss    rcCstS)z-The default prefix for temporary directories.)r$rrrrr "sr cCs ttS)z6The default prefix for temporary directories as bytes.)rr%r rrrrr &sr cCs:tdur6tztdur taWtn t0tS)zAccessor for tempfile.tempdir.N)r ryrzrwr{rrrrr ,sr cCs ttS)z)A bytes version of tempfile.gettempdir().)rr%r rrrrr 8sr FcCs2t|||\}}}}|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_openflagsrer)r'r&r(textr)rrrrr<s 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.mkdtemprrOz(No usable temporary directory name foundN)r*r|rr}rr%rCrrcrTrDr~rmkdirrjrkrRrlrmrnrpr)r'r&r(r)rrsrRrrrrrcs,       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 r|rCrrcrrTrDrrjrpr)r'r&r(rrsrRrrrrrs  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||_||_||_dSr5)rrRdeleter2rrRrrrr__init__sz_TemporaryFileCloser.__init__rOcCsL|jsH|jdurHd|_z|jW|jrH||jn|jrF||j0dSNT) close_calledrrhrrR)r2rirrrrhs  z_TemporaryFileCloser.closecCs |dSr5)rhr6rrr__del__sz_TemporaryFileCloser.__del__cCs|jsd|_|jdSr)rrrhr6rrrrhs)T) rGrHrIrJrrrrrRrirhrrrrrrs   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||||_dSr5)rrRrr_closerrrrrrsz_TemporaryFileWrapper.__init__cs^|jd}t||}t|drD|tfdd}|j|_|}t|tsZt||||S)Nr__call__cs|i|Sr5r)r kwargsrrr func_wrappersz7_TemporaryFileWrapper.__getattr__..func_wrapper) __dict__r/hasattr _functoolswrapsrrintsetattr)r2rRrarrrr __getattr__s     z!_TemporaryFileWrapper.__getattr__cCs|j|Sr5)r __enter__r6rrrrs z_TemporaryFileWrapper.__enter__cCs|j|||}||Sr5)r__exit__rh)r2excvaluetbresultrrrrsz_TemporaryFileWrapper.__exit__cCs|jdS)zA Close the temporary file, possibly deleting it. N)rrhr6rrrrhsz_TemporaryFileWrapper.closeccs|jD] }|VqdSr5)r)r2linerrrr7 s z_TemporaryFileWrapper.__iter__N)T) rGrHrIrJrrrrrhr7rrrrrs 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. rO bufferingnewlineencodingrN) r*rerrR O_TEMPORARYrrfrdr BaseExceptionrirh)moderrrr'r&r(rrr)rrurRrrrrrs     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. r_FrN) r*re_O_TMPFILE_WORKSrrO_CREATrdIsADirectoryErrorrrfrhrri) rrrrr'r&r(rr)rflags2rurRrrrrGs6       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)rrr'r&rrr(r)rfBytesIO_file TextIOWrapper _max_size_rolled_TemporaryFileArgs) r2max_sizerrrrr'r&r(rrrrrs  zSpooledTemporaryFile.__init__cCs,|jr dS|j}|r(||kr(|dSr5)rrtellrollover)r2rrrrr_checks zSpooledTemporaryFile._checkcCsv|jr dS|j}tfi|j}|_|`|}t|drR|j| n|| | |dd|_dS)NbufferrT) rrrrrrrrgdetachgetvalueseek)r2rnewfileposrrrrs   zSpooledTemporaryFile.rollovercCs|jjrtd|S)Nz%Cannot enter context with closed file)rclosed ValueErrorr6rrrrszSpooledTemporaryFile.__enter__cCs|jdSr5rrhr2rrrrrrrszSpooledTemporaryFile.__exit__cCs |jSr5)rr7r6rrrr7szSpooledTemporaryFile.__iter__cCs|jdSr5rr6rrrrhszSpooledTemporaryFile.closecCs|jjSr5)rrr6rrrrszSpooledTemporaryFile.closedcCs|jjSr5)rrr6rrrrszSpooledTemporaryFile.encodingcCs|jjSr5)rrr6rrrrszSpooledTemporaryFile.errorscCs||jSr5)rrfilenor6rrrrszSpooledTemporaryFile.filenocCs|jdSr5)rflushr6rrrrszSpooledTemporaryFile.flushcCs |jSr5)risattyr6rrrrszSpooledTemporaryFile.isattycCs,z |jjWSty&|jdYS0dS)Nr)rrrXrr6rrrrs  zSpooledTemporaryFile.modecCs$z |jjWStyYdS0dSr5)rrRrXr6rrrrRs  zSpooledTemporaryFile.namecCs|jjSr5)rnewlinesr6rrrrszSpooledTemporaryFile.newlinescGs |jj|Sr5)rreadr2r rrrrszSpooledTemporaryFile.readcGs |jj|Sr5)rreadlinerrrrrszSpooledTemporaryFile.readlinecGs |jj|Sr5)r readlinesrrrrrszSpooledTemporaryFile.readlinescGs |jj|Sr5)rrrrrrrszSpooledTemporaryFile.seekcCs |jSr5)rrr6rrrrszSpooledTemporaryFile.tellcCs6|dur|jn||jkr&||j|dSr5)rtruncaterr)r2sizerrrrs   zSpooledTemporaryFile.truncatecCs|j}||}|||Sr5)rrgr)r2srrvrrrrgs  zSpooledTemporaryFile.writecCs|j}||}|||Sr5)r writelinesr)r2iterablerrrrrr s  zSpooledTemporaryFile.writelines)rrrNNNNN)N)"rGrHrIrJrr classmethod_types GenericAlias__class_getitem__rrrrr7rhrKrrrrrrrrRrrrrrrrrgrrrrrrsL         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)rrR_weakreffinalize_cleanupformat _finalizer)r2r'r&r(rrrrs  zTemporaryDirectory.__init__cs fdd}tj|ddS)Nc st|dtrxzT|kr(ttj|t|zt|Wn ttfy^|Yn0Wqt ytYq0nt|dt rndS)Nr) issubclassrkrrrTr\rir_rmtreero)rrTexc_infoclsrRrronerror&s z+TemporaryDirectory._rmtree..onerror)r)_shutilrmtree)rrRrrrrr$szTemporaryDirectory._rmtreecCs||t|tdSr5)r _warningswarnResourceWarning)rrRrrrrr;s zTemporaryDirectory._cleanupcCsd|jj|jS)Nz <{} {!r}>)r __class__rGrRr6rrr__repr__@szTemporaryDirectory.__repr__cCs|jSr5)rRr6rrrrCszTemporaryDirectory.__enter__cCs |dSr5)cleanuprrrrrFszTemporaryDirectory.__exit__cCs|jr||jdSr5)rrrrRr6rrrrIs zTemporaryDirectory.cleanup)NNN)rGrHrIrJrrrrrrrrrrrrrrrrs   r)NNNF)NNN)rrNNNNNT)rrNNNNN)BrJ__all__ functoolsrwarningsriorfosrshutilrerrnorprandomrr0sysr~typesrweakrefr_thread allocate_lock_allocate_lockO_RDWRrO_EXCLrrrrerrr$ryrr#r*r+r]rwrxr|rrrr r r r r rrrrrrrRplatformrrrobjectrrrrrs~        -   ' ( +? '  <