Yf h@sNdZddddddddd d d d d g ZddlZddlZddlZddlZ ddl Z ddl Z ddlmZddlZyddlZWnek rddlZYnXejZe je jBe jBZee dree jOZeZee dr&ee jOZee drAe j Z ndZ dZ!eZ"ee drqe j#Z$n'ee dre j%Z$n ddZ$ddZ&ddZ'ddZ(Gdd d Z)d!d"Z*d#d$Z+da,d%d&Z-d'd(Z.d)d Z/d*d Z0da1d+d Z2d,d Z3dddd-d.dZ4dddd/dZ5d0e!dd1dZ6Gd2d3d3Z7Gd4d5d5Z8d6d@dddddd8d9dZ9e j:d:kse j;j<d;kre9Z=n0ee d<a>d6dAdddddd=dZ=Gd>ddZ?Gd?dde@ZAdS)BaTemporary 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'ZtmplstatstatcCs&tj|tj}tj|dS)N)_osopenO_RDONLYclose)fnfdr-/opt/alt/python35/lib64/python3.5/tempfile.py_statTsrc Cs/yt|Wntk r&dSYnXdSdS)NFT)rOSError)rrrr_existsXs   rcGsd}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.) isinstancebytesstr TypeError)argsZ return_typeargrrr_infer_return_typeas         r%cCst|||}|dkr'|}|dkrW|tkrHt}ntjt}|dkr|tkr{t}n t}||||fS)z9Common parameter processing for most APIs in this module.N)r%r!templaterfsencoder r )prefixsuffixdir output_typerrr_sanitize_paramsvs         r,c@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_rngr.)selfZcur_pidrrrrngs    z_RandomNameSequence.rngcCs|S)Nr)r2rrr__iter__sz_RandomNameSequence.__iter__csD|j|jjfddtdD}dj|S)Ncsg|]}qSrr).0Zdummy)cchooserr s z0_RandomNameSequence.__next__..) charactersr3Zchoicerangejoin)r2Zlettersr)r6r7r__next__s  "z_RandomNameSequence.__next__N) __name__ __module__ __qualname____doc__r;propertyr3r4r>rrrrr-s  r-c 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)rDrErF) rgetenvappendnameextendgetcwdAttributeErrorrcurdir)dirlistZenvnamedirnamerrr_candidate_tempdir_lists rQcCs~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.diwbclosefdFsblatNrGz)No usable temporary directory found in %s)r-rQrrNpathabspathr<nextr=r_bin_openflags_iowriterunlinkFileExistsErrorPermissionErrorrJisdiraccessW_OKrFileNotFoundError_errnoENOENT)ZnamerrOr*seqrJfilenamerfprrr_get_default_tempdirs:      !  rgc CsAtdkr=tjztdkr.taWdtjXtS)z7Common setup sequence for all user-callable interfaces.N)_name_sequence _once_lockacquirer-releaserrrr_get_candidate_namess     rlc 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.irGz#No usable temporary file name foundN)rlr maprr'r<rrWrUr=rr\r]rJr^r_r`rVrbEEXIST) r*ZpreZsufflagsr+namesrdrJfilerrrr_mkstemp_inners$     ! rrcCstS)z-The default prefix for temporary directories.)r&rrrrr scCstjtS)z6The default prefix for temporary directories as bytes.)rr'r rrrrr sc CsAtdkr=tjztdkr.taWdtjXtS)zAccessor for tempfile.tempdir.N)r rirjrgrkrrrrr !s     cCstjtS)z)A bytes version of tempfile.gettempdir().)rr'r rrrrr -sFcCsIt|||\}}}}|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. )r,_text_openflagsrXrr)r)r(r*textr+rorrrr1s  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. irGz(No usable temporary directory name foundN)r,rlr rmrr'r<rrWrUr=mkdirr\r]rJr^r_r`rbrn)r)r(r*r+rprdrJrqrrrrYs&      ! r:cCs|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 rlr<rrWrrUr=rr\rbrn)r)r(r*rprdrJrqrrrrs      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)rqrJdelete)r2rqrJrwrrr__init__s  z_TemporaryFileCloser.__init__rGc CsQ|j rM|jdk rMd|_z|jjWd|jrL||jXdS)NT) close_calledrqrrwrJ)r2r[rrrrs   z_TemporaryFileCloser.closecCs|jdS)N)r)r2rrr__del__sz_TemporaryFileCloser.__del__cCs#|jsd|_|jjdS)NT)ryrqr)r2rrrrs  ) r?r@rArBrqryrxrrJr[rrzrrrrrvs  rvc@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)rqrJrwrv_closer)r2rqrJrwrrrrxs   z_TemporaryFileWrapper.__init__cs|jd}t||}t|drd|tjfdd}|j|_|}t|tst||||S)Nrq__call__cs ||S)Nr)r#kwargs)funcrr func_wrappersz7_TemporaryFileWrapper.__getattr__..func_wrapper) __dict__r0hasattr _functoolswrapsr|rintsetattr)r2rJrqarr)rr __getattr__s ! z!_TemporaryFileWrapper.__getattr__cCs|jj|S)N)rq __enter__)r2rrrrs z_TemporaryFileWrapper.__enter__cCs&|jj|||}|j|S)N)rq__exit__r)r2excvaluetbresultrrrrs z_TemporaryFileWrapper.__exit__cCs|jjdS)zA Close the temporary file, possibly deleting it. N)r|r)r2rrrrsz_TemporaryFileWrapper.closeccsx|jD] }|Vq WdS)N)rq)r2linerrrr4sz_TemporaryFileWrapper.__iter__N) r?r@rArBrxrrrrr4rrrrr{s     r{zw+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. rG bufferingnewlineencodingN) r,rXrrJZ O_TEMPORARYrrrYrr{ BaseExceptionr[r) moderrrr)r(r*rwr+rorrJrqrrrr s    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) r,rX_O_TMPFILE_WORKSrrO_CREATrIsADirectoryErrorrrYrrrr[) rrrrr)r(r*r+roZflags2rrJrrrr;s0      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 Frrr)r(rr*)rYBytesIO_fileStringIO _max_size_rolled_TemporaryFileArgs) r2max_sizerrrrr)r(r*rrrrx|s      zSpooledTemporaryFile.__init__cCs<|jr dS|j}|r8|j|kr8|jdS)N)rrtellrollover)r2rqrrrr_checks   zSpooledTemporaryFile._checkcCsh|jr dS|j}t|j}|_|`|j|j|j|jdd|_dS)NrT)rrrrrZgetvalueseekr)r2rqZnewfilerrrrs  zSpooledTemporaryFile.rollovercCs|jjrtd|S)Nz%Cannot enter context with closed file)rclosed ValueError)r2rrrrs  zSpooledTemporaryFile.__enter__cCs|jjdS)N)rr)r2rrrrrrrszSpooledTemporaryFile.__exit__cCs |jjS)N)rr4)r2rrrr4szSpooledTemporaryFile.__iter__cCs|jjdS)N)rr)r2rrrrszSpooledTemporaryFile.closecCs |jjS)N)rr)r2rrrrszSpooledTemporaryFile.closedc CsHy|jjSWn3tk rCd|jdkr4|jdSYnXdS)Nrrr)rrrMr)r2rrrrs  zSpooledTemporaryFile.encodingcCs|j|jjS)N)rrfileno)r2rrrrs zSpooledTemporaryFile.filenocCs|jjdS)N)rflush)r2rrrrszSpooledTemporaryFile.flushcCs |jjS)N)risatty)r2rrrrszSpooledTemporaryFile.isattyc Cs2y|jjSWntk r-|jdSYnXdS)Nr)rrrMr)r2rrrrs zSpooledTemporaryFile.modec Cs+y|jjSWntk r&dSYnXdS)N)rrJrM)r2rrrrJs zSpooledTemporaryFile.namec CsHy|jjSWn3tk rCd|jdkr4|jdSYnXdS)Nrrr)rnewlinesrMr)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.tellcCsI|dkr|jjn)||jkr5|j|jj|dS)N)rtruncaterr)r2sizerrrrs   zSpooledTemporaryFile.truncatecCs)|j}|j|}|j||S)N)rrZr)r2srqrvrrrrZs  zSpooledTemporaryFile.writecCs)|j}|j|}|j||S)N)r writelinesr)r2iterablerqrrrrrs  zSpooledTemporaryFile.writelines)r?r@rArBrrxrrrrr4rrCrrrrrrrJrrrrrrrrrZrrrrrrus8                 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})rrJ_weakreffinalize_cleanupformat _finalizer)r2r)r(r*rrrrxszTemporaryDirectory.__init__cCs!tj|tj|tdS)N)_shutilrmtree _warningswarnResourceWarning)clsrJrrrrrs zTemporaryDirectory._cleanupcCsdj|jj|jS)Nz <{} {!r}>)r __class__r?rJ)r2rrr__repr__!szTemporaryDirectory.__repr__cCs|jS)N)rJ)r2rrrr$szTemporaryDirectory.__enter__cCs|jdS)N)cleanup)r2rrrrrrr'szTemporaryDirectory.__exit__cCs#|jjrtj|jdS)N)rdetachrrrJ)r2rrrr*szTemporaryDirectory.cleanup) r?r@rArBrx classmethodrrrrrrrrrr s    rr)BrB__all__ functoolsrwarningsriorYosrZshutilrerrnorbZrandomrr1weakrefr_thread ImportErrorZ _dummy_thread allocate_lockZ_allocate_lockO_RDWRrO_EXCLrsrrrXrrr&rirrrrr%r,r-rQrgrhrlrrr r r r r rrrrvr{rrJsysplatformrrrobjectrrrrrs                     -     (' +?  $!   8