3 KYsx @svddlZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z y ddl Z Wne k rddlZ YnXddlmZmZddlmZe jjZejdpejdZerdZddlmZnd Ze jdd kZerd d Zn(d d ZGdddeZGdddeZ d\a!a"ddZ#Gddde$Z%ddZ&ddZ'Gddde(Z)Gddde)Z*dS)N) STDIN_FILENOCHILD)whichsolarissunosF) _fork_ptyTcCs t|gS)N)bytes)ir /usr/lib/python3.6/ptyprocess.py_byte(srcCst|S)N)chr)r r r r r+sc@s eZdZdS)FileNotFoundErrorN)__name__ __module__ __qualname__r r r r r.src@s eZdZdS) TimeoutErrorN)rrrr r r r r/srcCstdk rtdk rdSynddlm}m}ytjj}Wntk rRtj j}YnXt tj |d|}t tj |d|}Wn\t t tttjfk ryddlm}m}||}}Wnt k rd\}}YnXYnXt|at|adS) zkSet constants _EOF and _INTR. This avoids doing potentially costly operations on module load. Nr)VEOFVINTR)CEOFCINTRr )r r)_EOF_INTRtermiosrrsys __stdin__fileno ValueError __stdout__ord tcgetattr ImportErrorOSErrorIOErrorerrorrrr)rrfdZintreofrrr r r _make_eof_intr3s$r+c@seZdZdZdS)PtyProcessErrorz%Generic error class for this package.N)rrr__doc__r r r r r,Tsr,cCsd}ytj|}WnTtjk rf}z6|jdtjkrTt|jdd|jd|fWYdd}~XnX|r|dtjB|d<n|dtj@|d<ytj|tj |WnRtk r}z6|jdtjkrt|jdd|jd|fWYdd}~XnXdS)Nz,setecho() may not be called on this platformrz%s: %s.rr ) rr$r(argserrnoEINVALr'ECHOZ tcsetattrZTCSANOW)r)stateerrmsgattrerrr r r _setechoZs r6cCs0ttdd}tjd||dd}tj|||dS)N TIOCSWINSZiHHHHrigt)getattrrstructpackfcntlioctl)r)rowscolsr7sr r r _setwinsizers rAc@sPeZdZdZeZer8ejj dZdj dZ e ddZ nejZdZ e jjZ dZdZdZdZddZedCd d ZddZe ddZe ddZddZddZdDddZddZddZdEddZd d!Z d"d#Z!dFd%d&Z"d'd(Z#dGd)d*Z$dHd+d,Zd-d.Z%d/d0Z&d1d2Z'd3d4Z(dId6d7Z)d8d9Z*d:d;Z+dd?Z-d@dAZ.dS)J PtyProcesszThis class represents a process running in a pseudoterminal. The main constructor is the :meth:`spawn` classmethod. asciiz c Cs8ytjjj|Stk r2tjj|jddSXdS)NrCreplace)rstdoutbufferwriteAttributeErrordecode)br r r write_to_stdoutszPtyProcess.write_to_stdoutNcCsvt||_||_tj|ddd}tj|dddd}tj|||_d|_d|_d|_ d|_ d|_ d|_ d|_ d|_dS)Nrbr) bufferingwbF)rMclosefdg?)r+pidr)ioopenBufferedRWPairfileobj terminatedclosed exitstatus signalstatusstatusflag_eofdelayafterclosedelayafterterminate)selfrPr)ZreadfZwritefr r r __init__szPtyProcess.__init__TPcNCst|ttfstd||dd}|d}t|}|dkrNtdd||}||d<tj\} } trxt j \} } n t j \} } | t kryttf|Wn:tk r} z| jdtjtjfkrʂWYdd} ~ XnX|s6yttdWnDttjfk r4} z | jdtjtjfkr$WYdd} ~ XnXtj| tj| tjtjtjtjd}tjd| tj| d||dk rtj ||dk ry |Wnnt!k r}zPt"|j#}d j$|t%|}t&r|j'd }tj(| |tj| tj)dWYdd}~XnXy*|dkr0tj*||ntj+|||Wnht,k r} zJd j$| jt%| }t&rv|j'd }tj(| |tj| tj)tj-WYdd} ~ XnX|| | }||_.|dk r||_/|dk r||_0tj| tj1| d }tj| t2|dkrryL|j3d d\}}}t4t5|j6dt!}||j6d d}|t,krRt7||_Wnt!d|YnX|y|j8|WnBtk r} z$| jdtjtjtj9fkrWYdd} ~ XnX|S)a%Start the given command in a child process in a pseudo terminal. This does all the fork/exec type of stuff for a pty, and returns an instance of PtyProcess. If preexec_fn is supplied, it will be called with no arguments in the child process before exec-ing the specified command. It may, for instance, set signal handlers to SIG_DFL or SIG_IGN. Dimensions of the psuedoterminal used for the subprocess can be specified as a tuple (rows, cols), or the default (24, 80) will be used. z)Expected a list or tuple for argv, got %rNrz%The command was not found or was not zexecutable: %s.Fr rz{}:0:{}zutf-8z OSError:{}:{}i:rCrDz)Subprocess failed, got bad error data: %r): isinstancelisttuple TypeErrorrrospipeuse_native_pty_forkptyforkrZfork_ptyrrArr'r.r/r0ZENOTTYr6rr(closer<ZF_SETFDZ FD_CLOEXECresourceZ getrlimitZ RLIMIT_NOFILE closerangechdir ExceptiontyperformatstrPY3encoderG_exitexecvexecvper&EX_OSERRargvenv launch_dirreadlensplitr9builtinsrIint setwinsizeZENXIO)clsrzcwdr{echoZ preexec_fnZ dimensionsZcommandZcommand_with_pathZexec_err_pipe_readZexec_err_pipe_writerPr)r5Zmax_fdeZenameZtosendZinstZ exec_err_dataZerrclassZerrno_sr3exctypeZ exceptionr r r spawns                           zPtyProcess.spawncCs|t|j}|jdk rft|jg}|jdk r:|jd|j|jdk rT|jd|jdj|dj|Sdj||j |j SdS)Nzenv=%rzcwd=%rz {}.spawn({})z, z{}(pid={}, fd={})) rqrrzreprr{appendr|rrjoinrPr))r]Zclsnamer.r r r __repr__Ms     zPtyProcess.__repr__cCst|ts|jdS|S)Nzutf-8)rcr ru)r@r r r _coerce_send_string[s  zPtyProcess._coerce_send_stringcCs|S)Nr )r@r r r _coerce_read_stringaszPtyProcess._coerce_read_stringc Cs$|js y |jWn YnXdS)aLThis makes sure that no system resources are left open. Python only garbage collects Python objects. OS file descriptors are not Python objects, so they must be handled explicitly. If the child file descriptor was opened outside of this class (passed to the constructor) then this does not close it. N)rVrl)r]r r r __del__es  zPtyProcess.__del__cCs|jS)zCThis returns the file descriptor of the pty for the child. )r))r]r r r r wszPtyProcess.filenocCsN|jsJ|j|jjtj|j|jr>|j|s>t dd|_ d|_dS)a?This closes the connection with the child application. Note that calling close() more than once is valid. This emulates standard Python behavior with files. Set force to True if you want to make sure that the child is terminated (SIGKILL is sent if the child ignores SIGHUP and SIGINT). zCould not terminate the child.rTN) rVflushrTrltimesleepr[isalive terminater,r))r]forcer r r rl|s   zPtyProcess.closecCsdS)zWThis does nothing. It is here to support the interface for a File-like object. Nr )r]r r r rszPtyProcess.flushcCs tj|jS)a^This returns True if the file descriptor is open and connected to a tty(-like) device, else False. On SVR4-style platforms implementing streams, such as SunOS and HP-UX, the child pty may not appear as a terminal device. This means methods such as setecho(), setwinsize(), getwinsize() may raise an IOError. )rgisattyr))r]r r r rs zPtyProcess.isattycCs\|dk rtj|}xB|js"dS|dkr6|dk r6dS|dk rJ|tj}tjdqWdS)aThis waits until the terminal ECHO flag is set False. This returns True if the echo mode is off. This returns False if the ECHO flag was not set False before the timeout. This can be used to detect when the child is waiting for a password. Usually a child application will turn off echo mode when it is waiting for the user to enter a password. For example, instead of expecting the "password:" prompt you can wait for the child to set ECHO off:: p = pexpect.spawn('ssh user@example.com') p.waitnoecho() p.sendline(mypassword) If timeout==None then this method to block until ECHO flag is False. NTrFg?)rgetechor)r]ZtimeoutZend_timer r r waitnoechos  zPtyProcess.waitnoechocCsytj|j}WnXtjk rh}z:d}|jdtjkrVt|jdd|jd|fWYdd}~XnXt|dtj @|_ |j S)aThis returns the terminal echo mode. This returns True if echo is on or False if echo is off. Child applications that are expecting you to enter a password often set ECHO False. See waitnoecho(). Not supported on platforms where ``isatty()`` returns False. z,getecho() may not be called on this platformrz%s: %s.rNr ) rr$r)r(r.r/r0r'boolr1r)r]r4r5r3r r r rszPtyProcess.getechocCst|j|||_dS)aZThis sets the terminal echo mode on or off. Note that anything the child sent before the echo will be lost, so you should be sure that your input buffer is empty before you call setecho(). For example, the following will work as expected:: p = pexpect.spawn('cat') # Echo is on by default. p.sendline('1234') # We expect see this twice from the child... p.expect(['1234']) # ... once from the tty echo... p.expect(['1234']) # ... and again from cat itself. p.setecho(False) # Turn off tty echo p.sendline('abcd') # We will set this only once (echoed by cat). p.sendline('wxyz') # We will set this only once (echoed by cat) p.expect(['abcd']) p.expect(['wxyz']) The following WILL NOT WORK because the lines sent before the setecho will be lost:: p = pexpect.spawn('cat') p.sendline('1234') p.setecho(False) # Turn off tty echo p.sendline('abcd') # We will set this only once (echoed by cat). p.sendline('wxyz') # We will set this only once (echoed by cat) p.expect(['1234']) p.expect(['1234']) p.expect(['abcd']) p.expect(['wxyz']) Not supported on platforms where ``isatty()`` returns False. N)r6r)r)r]r2r r r setechos zPtyProcess.setechocCsry|jj|}WnFttfk rV}z&|jdtjkrDd|_tdWYdd}~XnX|dkrnd|_td|S)aRead and return at most ``size`` bytes from the pty. Can block if there is nothing to read. Raises :exc:`EOFError` if the terminal was closed. Unlike Pexpect's ``read_nonblocking`` method, this doesn't try to deal with the vagaries of EOF on platforms that do strange things, like IRIX or older Solaris systems. It handles the errno=EIO pattern used on Linux, and the empty-string return used on BSD platforms and (seemingly) on recent Solaris. rTz,End Of File (EOF). Exception style platform.Nz/End Of File (EOF). Empty string style platform.) rTread1r&r'r.r/EIOrZEOFError)r]sizer@r5r r r r}s zPtyProcess.readcCspy|jj}WnFttfk rT}z&|jdtjkrBd|_tdWYdd}~XnX|dkrld|_td|S)zRead one line from the pseudoterminal, and return it as unicode. Can block if there is nothing to read. Raises :exc:`EOFError` if the terminal was closed. rTz,End Of File (EOF). Exception style platform.Nrz/End Of File (EOF). Empty string style platform.) rTreadliner&r'r.r/rrZr)r]r@r5r r r r szPtyProcess.readlinecCs|jj|}|r|jj|S)N)rTrGr)r]rJrnr r r _writeb s  zPtyProcess._writebcCs|j||dS)zaWrite bytes to the pseudoterminal. Returns the number of bytes written. )r)r)r]r@rr r r rG&szPtyProcess.writec Cs|j}t|}d|ko"dknrN|tdd}t|}|j||fSddddddddd d d d d }||krxdSt||}|j||fS)aHelper method that wraps send() with mnemonic access for sending control character to the child (such as Ctrl-C or Ctrl-D). For example, to send Ctrl-G (ASCII 7, bell, ''):: child.sendcontrol('g') See also, sendintr() and sendeof(). azarr) @`[{\|]}^~_?r)rr)lowerr#rr)r]charrZbytedr r r sendcontrol-s"  zPtyProcess.sendcontrolcCs|jttfS)a1This sends an EOF to the child. This sends a character which causes the pending parent output buffer to be sent to the waiting child program without waiting for end-of-line. If it is the first character of the line, the read() in the user program returns 0, which signifies end-of-file. This means to work as expected a sendeof() has to be called at the beginning of a line. This method does not send a newline. It is the responsibility of the caller to ensure the eof is sent at the beginning of a line. )rr)r]r r r sendeofIs zPtyProcess.sendeofcCs|jttfS)znThis sends a SIGINT to the child. It does not require the SIGINT to be the first character on a line. )rr)r]r r r sendintrUszPtyProcess.sendintrcCs|jS)z@This returns True if the EOF exception was ever raised. )rZ)r]r r r r*[szPtyProcess.eofFc Cs|js dSy|jtjtj|j|js2dS|jtjtj|j|jsVdS|jtjtj|j|jszdS|r|jtj tj|j|jsdSdSdSt k rtj|j|jsdSdSYnXdS)zThis forces a child process to terminate. It starts nicely with SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This returns True if the child was terminated. This returns False if the child could not be terminated. TFN) rkillsignalSIGHUPrrr\SIGCONTSIGINTSIGKILLr&)r]rr r r ras6         zPtyProcess.terminatecCs|jrtj|jd\}}n|jStj||_tj|rX||_tj||_d|_d|_ nr?r r r rszPtyProcess.setwinsizer_r`)NNTNr)T)N)r)T)T)F)/rrrr-r string_typertrglinesepruZcrlf staticmethodrKrrErGencodingrzr{r|r^ classmethodrrrrrr rlrrrrrr}rrrrrr*rrrrrrr r r r rB|sV       $     (M rBcsVeZdZdZereZneZd fdd Zdfdd Z fd d Z fd d Z Z S)PtyProcessUnicodezUnicode wrapper around a process running in a pseudoterminal. This class exposes a similar interface to :class:`PtyProcess`, but its read methods return unicode, and its :meth:`write` accepts unicode. utf-8strictcs4tt|j||||_||_tj||d|_dS)N)errors)superrr^r codec_errorscodecsgetincrementaldecoderdecoder)r]rPr)rr) __class__r r r^szPtyProcessUnicode.__init__cs tt|j|}|jj|ddS)aRead at most ``size`` bytes from the pty, return them as unicode. Can block if there is nothing to read. Raises :exc:`EOFError` if the terminal was closed. The size argument still refers to bytes, not unicode code points. F)final)rrr}rrI)r]rrJ)rr r r}#szPtyProcessUnicode.readcstt|j}|jj|ddS)zRead one line from the pseudoterminal, and return it as unicode. Can block if there is nothing to read. Raises :exc:`EOFError` if the terminal was closed. F)r)rrrrrI)r]rJ)rr r r.szPtyProcessUnicode.readlinecs|j|j}tt|j|S)zlWrite the unicode string ``s`` to the pseudoterminal. Returns the number of bytes written. )rurrrrG)r]r@rJ)rr r rG7s zPtyProcessUnicode.write)rr)r) rrrr-rtrsrZunicoder^r}rrG __classcell__r r )rr rs r)NN)+rr/r<rQrgrjrmrr:rrrrr%Z __builtin__rrutilrplatformrZ _platform startswithZ _is_solarisrir version_infortrr&rrrrr+rpr,r6rAobjectrBrr r r r sT      !