o !^R@sddlmZmZddlZddlZddlZddlZddlZddlm Z m Z m Z ddl m Z mZmZejddkZer;eneZGdddeZGd d d eZdS) )StringIOBytesION)ExceptionPexpectEOFTIMEOUT)Expectersearcher_string searcher_rec@s,eZdZdZedddZedddZdS) _NullCoderzPass bytes through unchanged.FcC|SNbfinalrr3/usr/lib/python3/dist-packages/pexpect/spawnbase.pyencodez_NullCoder.encodecCr rrrrrrdecoderz_NullCoder.decodeN)F)__name__ __module__ __qualname____doc__ staticmethodrrrrrrr s  r c@seZdZdZdZdZdZ  d5ddZd d Zd d Z d dZ ddZ ddZ e e e Zd6ddZddZddZd7ddZ  d7ddZ  d7dd Zd8d!d"Zd9d#d$Zd9d%d&Zd'd(Zd9d)d*Zd+d,Zd-d.Zd/d0Zd1d2Zd3d4ZdS): SpawnBasezA base class providing the backwards-compatible spawn API for Pexpect. This should not be instantiated directly: use :class:`pexpect.spawn` or :class:`pexpect.fdpexpect.fdspawn`. NFstrictcCstj|_tj|_tj|_d|_d|_d|_d|_d|_d|_ d|_ d|_ d|_ d|_ d|_||_t|_||_d|_d|_||_||_d|_d|_d|_d|_d|_dt|d|_d|_||_||_ |durt!|_"|_#t$|_%t&|_'d |_(t)rt$t*f|_+t,j-.d |_-d d }||_/n>t0f|_+t,j-|_-tjj1|_/n0t23|||_"t24|||_#t5|_%t6|_'d |_(t5f|_+t)rt,j-|_-nt,j-7d |_-tjj1|_/d|_8|'|_9|'|_:dS)NFTg?g?g-C6?<>s asciic Ss8ztjj|WStytj|ddYSw)Nr#replace)sysstdoutbufferwriteAttributeErrorr)rrrrwrite_to_stdout^s  z+SpawnBase.__init__..write_to_stdoutz );r%stdinr&stderrsearcher ignorecasebeforeaftermatch match_index terminated exitstatus signalstatusstatuschild_fdtimeoutr delimiterlogfile logfile_read logfile_sendmaxreadsearchwindowsizedelaybeforesenddelayafterclosedelayafterterminatedelayafterread softspacereprnameclosedencoding codec_errorsr _encoder_decoderbytes string_typer buffer_typecrlfPY3strallowed_string_typesoslineseprr* basestringr(codecsgetincrementalencodergetincrementaldecoder text_typerrasync_pw_transport_buffer_before)selfr8r=r>r:rGrHr*rrr__init__!sp     zSpawnBase.__init__cCsV|jdur|j||j|dkr|jn|j}|dur)|||dSdS)Nsend)r:r(flushr<r;)r\s direction second_logrrr_logs     zSpawnBase._logcC"|jdurt|ts|dS|S)Nr#rG isinstancerKrr\r`rrr_coerce_expect_string zSpawnBase._coerce_expect_stringcCrd)Nzutf-8rergrrr_coerce_send_stringrizSpawnBase._coerce_send_stringcCs |jSr)rZgetvaluer\rrr _get_buffers zSpawnBase._get_buffercCs||_|j|dSr)rMrZr()r\valuerrr _set_buffers zSpawnBase._set_bufferrc Csz t|j|}Wnty%}z|jdtjkr d|_tdd}~ww|dkr1d|_td|j j |dd}| |d |S) zThis reads data from the file descriptor. This is a simple implementation suitable for a regular file. Subclasses using ptys or pipes should override it. The timeout parameter is ignored. rTz,End Of File (EOF). Exception style platform.Nz/End Of File (EOF). Empty string style platform.F)rread) rRrqr7OSErrorargserrnoEIOflag_eofrrJrrc)r\sizer8r`errrrrread_nonblockings zSpawnBase.read_nonblockingcCs*tdjt||ddd|jDd)Nz`got {badtype} ({badobj!r}) as pattern, must be one of: {goodtypes}, pexpect.EOF, pexpect.TIMEOUTz, cSsg|]}t|qSr)rP).0astrrr s z/SpawnBase._pattern_type_err..)badtypebadobj goodtypes) TypeErrorformattypejoinrQ)r\patternrrr_pattern_type_errs zSpawnBase._pattern_type_errcCs|durgSt|ts|g}tj}|jr|tjB}g}t|D]B\}}t||jr8||}| t ||q|t urB| t q|t urL| t qt|t t dr\| |q||q|S)aThis compiles a pattern-string or a list of pattern-strings. Patterns must be a StringType, EOF, TIMEOUT, SRE_Pattern, or a list of those. Patterns may also be None which results in an empty list (you might do this if waiting for an EOF or TIMEOUT condition without expecting any pattern). This is used by expect() when calling expect_list(). Thus expect() is nothing more than:: cpl = self.compile_pattern_list(pl) return self.expect_list(cpl, timeout) If you are using expect() within a loop it may be more efficient to compile the patterns first and then call expect_list(). This avoid calls in a loop to compile_pattern_list():: cpl = self.compile_pattern_list(my_pattern) while some_condition: ... i = self.expect_list(cpl, timeout) ... N)rflistreDOTALLr. IGNORECASE enumeraterQrhappendcompilerrrr)r\patterns compile_flagscompiled_pattern_listidxprrrcompile_pattern_lists(        zSpawnBase.compile_pattern_listr cKs>d|vr |d}|rtd|||}|||||S)aThis seeks through the stream until a pattern is matched. The pattern is overloaded and may take several types. The pattern can be a StringType, EOF, a compiled re, or a list of any of those types. Strings will be compiled to re types. This returns the index into the pattern list. If the pattern was not a list this returns index 0 on a successful match. This may raise exceptions for EOF or TIMEOUT. To avoid the EOF or TIMEOUT exceptions add EOF or TIMEOUT to the pattern list. That will cause expect to match an EOF or TIMEOUT condition instead of raising an exception. If you pass a list of patterns and more than one matches, the first match in the stream is chosen. If more than one pattern matches at that point, the leftmost in the pattern list is chosen. For example:: # the input is 'foobar' index = p.expect(['bar', 'foo', 'foobar']) # returns 1('foo') even though 'foobar' is a "better" match Please note, however, that buffering can affect this behavior, since input arrives in unpredictable chunks. For example:: # the input is 'foobar' index = p.expect(['foobar', 'foo']) # returns 0('foobar') if all input is available at once, # but returns 1('foo') if parts of the final 'bar' arrive late When a match is found for the given pattern, the class instance attribute *match* becomes an re.MatchObject result. Should an EOF or TIMEOUT pattern match, then the match attribute will be an instance of that exception class. The pairing before and after class instance attributes are views of the data preceding and following the matching pattern. On general exception, class attribute *before* is all data received up to the exception, while *match* and *after* attributes are value None. When the keyword argument timeout is -1 (default), then TIMEOUT will raise after the default value specified by the class timeout attribute. When None, TIMEOUT will not be raised and may block indefinitely until match. When the keyword argument searchwindowsize is -1 (default), then the value specified by the class maxread attribute is used. A list entry may be EOF or TIMEOUT instead of a string. This will catch these exceptions and return the index of the list entry instead of raising the exception. The attribute 'after' will be set to the exception type. The attribute 'match' will be None. This allows you to write code like this:: index = p.expect(['good', 'bad', pexpect.EOF, pexpect.TIMEOUT]) if index == 0: do_something() elif index == 1: do_something_else() elif index == 2: do_some_other_thing() elif index == 3: do_something_completely_different() instead of code like this:: try: index = p.expect(['good', 'bad']) if index == 0: do_something() elif index == 1: do_something_else() except EOF: do_some_other_thing() except TIMEOUT: do_something_completely_different() These two forms are equivalent. It all depends on what you want. You can also just expect the EOF if you are waiting for all output of a child to finish. For example:: p = pexpect.spawn('/bin/ls') p.expect(pexpect.EOF) print p.before If you are trying to optimize for speed then see expect_list(). On Python 3.4, or Python 3.3 with asyncio installed, passing ``async_=True`` will make this return an :mod:`asyncio` coroutine, which you can yield from to get the same result that this method would normally give directly. So, inside a coroutine, you can replace this code:: index = p.expect(patterns) With this non-blocking form:: index = yield from p.expect(patterns, async_=True) asyncUnknown keyword arguments: {})poprrr expect_list)r\rr8r>async_kwrrrrexpects^  zSpawnBase.expectcKsf|dkr|j}d|vr|d}|rtd|t|t||}|r.ddlm}|||S||S)amThis takes a list of compiled regular expressions and returns the index into the pattern_list that matched the child output. The list may also contain EOF or TIMEOUT(which are not compiled regular expressions). This method is similar to the expect() method except that expect_list() does not recompile the pattern list on every call. This may help if you are trying to optimize for speed, otherwise just use the expect() method. This is called by expect(). Like :meth:`expect`, passing ``async_=True`` will make this return an asyncio coroutine. r rrr expect_async) r8rrrrr _asyncr expect_loopr\ pattern_listr8r>rrexprrrrrZs    zSpawnBase.expect_listc s|dkrj}d|vr|d}|rtd|t|js%|ttfvr(|g}fddzt|}WntyB |Ynwfdd|D}t t ||}|radd l m }|||S||S) aThis is similar to expect(), but uses plain string matching instead of compiled regular expressions in 'pattern_list'. The 'pattern_list' may be a string; a list or other sequence of strings; or TIMEOUT and EOF. This call might be faster than expect() for two reasons: string searching is faster than RE matching and it is possible to limit the search to just the end of the input buffer. This method is also useful when you don't want to have to worry about escaping regular expression characters that you want to match. Like :meth:`expect`, passing ``async_=True`` will make this return an asyncio coroutine. r rrcs4|ttfvr|St|jr|S|dSr)rrrfrQrhr)rrlrrprepare_patterns   z/SpawnBase.expect_exact..prepare_patterncsg|]}|qSrr)rzr)rrrr|sz*SpawnBase.expect_exact..rr)r8rrrrfrQrriterrrr rrrrr)rr\r expect_exactvs*         zSpawnBase.expect_exactcCst|||}||S)aThis is the common loop used inside expect. The 'searcher' should be an instance of searcher_re or searcher_string, which describes how and what to search for in the input. See expect() for other arguments, return value and exceptions. )rr)r\r-r8r>rrrrrs  zSpawnBase.expect_loopcCsf|dkr|S|dkr||j|jSt|d|tj}|||jg}|dkr0|jS|jS)aDThis reads at most "size" bytes from the file (less if the read hits EOF before obtaining size bytes). If the size argument is negative or omitted, read all data until EOF is reached. The bytes are returned as a string object. An empty string is returned when EOF is encountered immediately. rz.{%d}) rLrr9r/rrrhrr0)r\rwcreindexrrrrqs  zSpawnBase.readcCs<|dkr|S||j|jg}|dkr|j|jS|jS)alThis reads and returns one entire line. The newline at the end of line is returned as part of the string, unless the file ends without a newline. An empty string is returned if EOF is encountered immediately. This looks for a newline as a CR/LF pair (\r\n) even on UNIX because this is what the pseudotty device returns. So contrary to what you may expect you will receive newlines as \r\n. If the size argument is 0 then an empty string is returned. In all other cases the size argument is ignored, which is not standard behavior for a file-like object. r)rLrrNr9r/)r\rwrrrrreadlines   zSpawnBase.readlinecCst|j|S)z>This is to support iterators over a file-like object. )rrrLrlrrr__iter__szSpawnBase.__iter__cCs$g} |}|s |S||q)aThis reads until EOF using readline() and returns a list containing the lines thus read. The optional 'sizehint' argument is ignored. Remember, because this reads until EOF that means the child process should have closed its stdout. If you run this method on a child that is still running with its stdout open then this method will block until it timesout.)rr)r\sizehintlineslinerrr readliness zSpawnBase.readlinescCs|jS)z9Expose file descriptor for a file-like interface )r7rlrrrfilenoszSpawnBase.filenocCdS)zWThis does nothing. It is here to support the interface for a File-like object. Nrrlrrrr_szSpawnBase.flushcCr)z Overridden in subclass using ttyFrrlrrrisattyrzSpawnBase.isattycCr rrrlrrr __enter__szSpawnBase.__enter__cCs |dSr)close)r\etypeevaluetbrrr__exit__ s zSpawnBase.__exit__)rrNNNr)rN)r r F)r r )r )rrrrrGpidrvr]rcrhrjrmropropertyr'ryrrrrrrrqrrrrr_rrrrrrrrsD ^    0g  1   r)iorrrUrRr%rrt exceptionsrrrrrr r version_inforOrPunicoderXobjectr rrrrrs