2 <!doctype html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
3 <html><head><title>Python: module pexpect</title>
4 </head><body bgcolor="#f0f0f8">
6 <table width="100%" cellspacing=0 cellpadding=2 border=0 summary="heading">
8 <td valign=bottom> <br>
9 <font color="#ffffff" face="helvetica, arial"> <br><big><big><strong>pexpect</strong></big></big> (version 2.3)</font></td
10 ><td align=right valign=bottom
11 ><font color="#ffffff" face="helvetica, arial"><a href=".">index</a><br><a href="file:/home/noah/pexpect/trunk/pexpect/pexpect.py">/home/noah/pexpect/trunk/pexpect/pexpect.py</a></font></td></tr></table>
12 <p><tt>Pexpect is a Python module for spawning child applications and controlling<br>
13 them automatically. Pexpect can be used for automating interactive applications<br>
14 such as ssh, ftp, passwd, telnet, etc. It can be used to a automate setup<br>
15 scripts for duplicating software package installations on different servers. It<br>
16 can be used for automated software testing. Pexpect is in the spirit of Don<br>
17 Libes' Expect, but Pexpect is pure Python. Other Expect-like modules for Python<br>
18 require TCL and Expect or require C extensions to be compiled. Pexpect does not<br>
19 use C, Expect, or TCL extensions. It should work on any platform that supports<br>
20 the standard Python pty module. The Pexpect interface focuses on ease of use so<br>
21 that simple tasks are easy.<br>
23 There are two main interfaces to Pexpect -- the function, <a href="#-run">run</a>() and the class,<br>
24 <a href="#spawn">spawn</a>. You can call the <a href="#-run">run</a>() function to execute a command and return the<br>
25 output. This is a handy replacement for os.system().<br>
27 For example::<br>
29 pexpect.<a href="#-run">run</a>('ls -la')<br>
31 The more powerful interface is the <a href="#spawn">spawn</a> class. You can use this to <a href="#spawn">spawn</a> an<br>
32 external child command and then interact with the child by sending lines and<br>
33 expecting responses.<br>
35 For example::<br>
37 child = pexpect.<a href="#spawn">spawn</a>('scp foo
[email protected]:.')<br>
38 child.expect ('Password:')<br>
39 child.sendline (mypassword)<br>
41 This works even for commands that ask for passwords or other input outside of<br>
42 the normal stdio streams.<br>
44 Credits: Noah Spurrier, Richard Holden, Marco Molteni, Kimberley Burchett,<br>
45 Robert Stone, Hartmut Goebel, Chad Schroeder, Erick Tryzelaar, Dave Kirby, Ids<br>
46 vander Molen, George Todd, Noel Taylor, Nicolas D. Cesar, Alexander Gattin,<br>
47 Geoffrey Marshall, Francisco Lourenco, Glen Mabey, Karthik Gurusamy, Fernando<br>
48 Perez, Corey Minyard, Jon Cohen, Guillaume Chazarain, Andrew Ryan, Nick<br>
49 Craig-Wood, Andrew Stone, Jorgen Grahn (Let me know if I forgot anyone.)<br>
51 Free, open source, and all that good stuff.<br>
53 Permission is hereby granted, free of charge, to any person obtaining a copy of<br>
54 this software and associated documentation files (the "Software"), to deal in<br>
55 the Software without restriction, including without limitation the rights to<br>
56 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies<br>
57 of the Software, and to permit persons to whom the Software is furnished to do<br>
58 so, subject to the following conditions:<br>
60 The above copyright notice and this permission notice shall be included in all<br>
61 copies or substantial portions of the Software.<br>
63 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR<br>
64 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,<br>
65 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE<br>
66 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER<br>
67 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,<br>
68 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE<br>
71 Pexpect Copyright (c) 2008 Noah Spurrier<br>
72 <a href="http://pexpect.sourceforge.net/">http://pexpect.sourceforge.net/</a><br>
74 $Id: pexpect.py 507 2007-12-27 02:40:52Z noah $</tt></p>
76 <table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
77 <tr bgcolor="#aa55cc">
78 <td colspan=3 valign=bottom> <br>
79 <font color="#fffff" face="helvetica, arial"><big><strong>Modules</strong></big></font></td></tr>
81 <tr><td bgcolor="#aa55cc"><tt> </tt></td><td> </td>
82 <td width="100%"><table width="100%" summary="list"><tr><td width="25%" valign=top><a href="errno.html">errno</a><br>
83 <a href="fcntl.html">fcntl</a><br>
84 <a href="os.html">os</a><br>
85 <a href="pty.html">pty</a><br>
86 </td><td width="25%" valign=top><a href="re.html">re</a><br>
87 <a href="resource.html">resource</a><br>
88 <a href="select.html">select</a><br>
89 <a href="signal.html">signal</a><br>
90 </td><td width="25%" valign=top><a href="string.html">string</a><br>
91 <a href="struct.html">struct</a><br>
92 <a href="sys.html">sys</a><br>
93 <a href="termios.html">termios</a><br>
94 </td><td width="25%" valign=top><a href="time.html">time</a><br>
95 <a href="traceback.html">traceback</a><br>
96 <a href="tty.html">tty</a><br>
97 <a href="types.html">types</a><br>
98 </td></tr></table></td></tr></table><p>
99 <table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
100 <tr bgcolor="#ee77aa">
101 <td colspan=3 valign=bottom> <br>
102 <font color="#ffffff" face="helvetica, arial"><big><strong>Classes</strong></big></font></td></tr>
104 <tr><td bgcolor="#ee77aa"><tt> </tt></td><td> </td>
105 <td width="100%"><dl>
106 <dt><font face="helvetica, arial"><a href="__builtin__.html#object">__builtin__.object</a>
109 <dt><font face="helvetica, arial"><a href="pexpect.html#spawn">spawn</a>
112 <dt><font face="helvetica, arial"><a href="exceptions.html#Exception">exceptions.Exception</a>(<a href="exceptions.html#BaseException">exceptions.BaseException</a>)
115 <dt><font face="helvetica, arial"><a href="pexpect.html#ExceptionPexpect">ExceptionPexpect</a>
118 <dt><font face="helvetica, arial"><a href="pexpect.html#EOF">EOF</a>
119 </font></dt><dt><font face="helvetica, arial"><a href="pexpect.html#TIMEOUT">TIMEOUT</a>
126 <table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
127 <tr bgcolor="#ffc8d8">
128 <td colspan=3 valign=bottom> <br>
129 <font color="#000000" face="helvetica, arial"><a name="EOF">class <strong>EOF</strong></a>(<a href="pexpect.html#ExceptionPexpect">ExceptionPexpect</a>)</font></td></tr>
131 <tr bgcolor="#ffc8d8"><td rowspan=2><tt> </tt></td>
132 <td colspan=2><tt>Raised when <a href="#EOF">EOF</a> is read from a child. This usually means the child has exited.<br> </tt></td></tr>
134 <td width="100%"><dl><dt>Method resolution order:</dt>
135 <dd><a href="pexpect.html#EOF">EOF</a></dd>
136 <dd><a href="pexpect.html#ExceptionPexpect">ExceptionPexpect</a></dd>
137 <dd><a href="exceptions.html#Exception">exceptions.Exception</a></dd>
138 <dd><a href="exceptions.html#BaseException">exceptions.BaseException</a></dd>
139 <dd><a href="__builtin__.html#object">__builtin__.object</a></dd>
142 Methods inherited from <a href="pexpect.html#ExceptionPexpect">ExceptionPexpect</a>:<br>
143 <dl><dt><a name="EOF-__init__"><strong>__init__</strong></a>(self, value)</dt></dl>
145 <dl><dt><a name="EOF-__str__"><strong>__str__</strong></a>(self)</dt></dl>
147 <dl><dt><a name="EOF-get_trace"><strong>get_trace</strong></a>(self)</dt><dd><tt>This returns an abbreviated stack trace with lines that only concern<br>
148 the caller. In other words, the stack trace inside the Pexpect module<br>
149 is not included.</tt></dd></dl>
152 Data descriptors inherited from <a href="pexpect.html#ExceptionPexpect">ExceptionPexpect</a>:<br>
153 <dl><dt><strong>__weakref__</strong></dt>
154 <dd><tt>list of weak references to the object (if defined)</tt></dd>
157 Data and other attributes inherited from <a href="exceptions.html#Exception">exceptions.Exception</a>:<br>
158 <dl><dt><strong>__new__</strong> = <built-in method __new__ of type object at 0x81400e0><dd><tt>T.<a href="#EOF-__new__">__new__</a>(S, ...) -> a new <a href="__builtin__.html#object">object</a> with type S, a subtype of T</tt></dl>
161 Methods inherited from <a href="exceptions.html#BaseException">exceptions.BaseException</a>:<br>
162 <dl><dt><a name="EOF-__delattr__"><strong>__delattr__</strong></a>(...)</dt><dd><tt>x.<a href="#EOF-__delattr__">__delattr__</a>('name') <==> del x.name</tt></dd></dl>
164 <dl><dt><a name="EOF-__getattribute__"><strong>__getattribute__</strong></a>(...)</dt><dd><tt>x.<a href="#EOF-__getattribute__">__getattribute__</a>('name') <==> x.name</tt></dd></dl>
166 <dl><dt><a name="EOF-__getitem__"><strong>__getitem__</strong></a>(...)</dt><dd><tt>x.<a href="#EOF-__getitem__">__getitem__</a>(y) <==> x[y]</tt></dd></dl>
168 <dl><dt><a name="EOF-__getslice__"><strong>__getslice__</strong></a>(...)</dt><dd><tt>x.<a href="#EOF-__getslice__">__getslice__</a>(i, j) <==> x[i:j]<br>
170 Use of negative indices is not supported.</tt></dd></dl>
172 <dl><dt><a name="EOF-__reduce__"><strong>__reduce__</strong></a>(...)</dt></dl>
174 <dl><dt><a name="EOF-__repr__"><strong>__repr__</strong></a>(...)</dt><dd><tt>x.<a href="#EOF-__repr__">__repr__</a>() <==> repr(x)</tt></dd></dl>
176 <dl><dt><a name="EOF-__setattr__"><strong>__setattr__</strong></a>(...)</dt><dd><tt>x.<a href="#EOF-__setattr__">__setattr__</a>('name', value) <==> x.name = value</tt></dd></dl>
178 <dl><dt><a name="EOF-__setstate__"><strong>__setstate__</strong></a>(...)</dt></dl>
181 Data descriptors inherited from <a href="exceptions.html#BaseException">exceptions.BaseException</a>:<br>
182 <dl><dt><strong>__dict__</strong></dt>
184 <dl><dt><strong>args</strong></dt>
186 <dl><dt><strong>message</strong></dt>
187 <dd><tt>exception message</tt></dd>
189 </td></tr></table> <p>
190 <table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
191 <tr bgcolor="#ffc8d8">
192 <td colspan=3 valign=bottom> <br>
193 <font color="#000000" face="helvetica, arial"><a name="ExceptionPexpect">class <strong>ExceptionPexpect</strong></a>(<a href="exceptions.html#Exception">exceptions.Exception</a>)</font></td></tr>
195 <tr bgcolor="#ffc8d8"><td rowspan=2><tt> </tt></td>
196 <td colspan=2><tt>Base class for all exceptions raised by this module.<br> </tt></td></tr>
198 <td width="100%"><dl><dt>Method resolution order:</dt>
199 <dd><a href="pexpect.html#ExceptionPexpect">ExceptionPexpect</a></dd>
200 <dd><a href="exceptions.html#Exception">exceptions.Exception</a></dd>
201 <dd><a href="exceptions.html#BaseException">exceptions.BaseException</a></dd>
202 <dd><a href="__builtin__.html#object">__builtin__.object</a></dd>
205 Methods defined here:<br>
206 <dl><dt><a name="ExceptionPexpect-__init__"><strong>__init__</strong></a>(self, value)</dt></dl>
208 <dl><dt><a name="ExceptionPexpect-__str__"><strong>__str__</strong></a>(self)</dt></dl>
210 <dl><dt><a name="ExceptionPexpect-get_trace"><strong>get_trace</strong></a>(self)</dt><dd><tt>This returns an abbreviated stack trace with lines that only concern<br>
211 the caller. In other words, the stack trace inside the Pexpect module<br>
212 is not included.</tt></dd></dl>
215 Data descriptors defined here:<br>
216 <dl><dt><strong>__weakref__</strong></dt>
217 <dd><tt>list of weak references to the object (if defined)</tt></dd>
220 Data and other attributes inherited from <a href="exceptions.html#Exception">exceptions.Exception</a>:<br>
221 <dl><dt><strong>__new__</strong> = <built-in method __new__ of type object at 0x81400e0><dd><tt>T.<a href="#ExceptionPexpect-__new__">__new__</a>(S, ...) -> a new <a href="__builtin__.html#object">object</a> with type S, a subtype of T</tt></dl>
224 Methods inherited from <a href="exceptions.html#BaseException">exceptions.BaseException</a>:<br>
225 <dl><dt><a name="ExceptionPexpect-__delattr__"><strong>__delattr__</strong></a>(...)</dt><dd><tt>x.<a href="#ExceptionPexpect-__delattr__">__delattr__</a>('name') <==> del x.name</tt></dd></dl>
227 <dl><dt><a name="ExceptionPexpect-__getattribute__"><strong>__getattribute__</strong></a>(...)</dt><dd><tt>x.<a href="#ExceptionPexpect-__getattribute__">__getattribute__</a>('name') <==> x.name</tt></dd></dl>
229 <dl><dt><a name="ExceptionPexpect-__getitem__"><strong>__getitem__</strong></a>(...)</dt><dd><tt>x.<a href="#ExceptionPexpect-__getitem__">__getitem__</a>(y) <==> x[y]</tt></dd></dl>
231 <dl><dt><a name="ExceptionPexpect-__getslice__"><strong>__getslice__</strong></a>(...)</dt><dd><tt>x.<a href="#ExceptionPexpect-__getslice__">__getslice__</a>(i, j) <==> x[i:j]<br>
233 Use of negative indices is not supported.</tt></dd></dl>
235 <dl><dt><a name="ExceptionPexpect-__reduce__"><strong>__reduce__</strong></a>(...)</dt></dl>
237 <dl><dt><a name="ExceptionPexpect-__repr__"><strong>__repr__</strong></a>(...)</dt><dd><tt>x.<a href="#ExceptionPexpect-__repr__">__repr__</a>() <==> repr(x)</tt></dd></dl>
239 <dl><dt><a name="ExceptionPexpect-__setattr__"><strong>__setattr__</strong></a>(...)</dt><dd><tt>x.<a href="#ExceptionPexpect-__setattr__">__setattr__</a>('name', value) <==> x.name = value</tt></dd></dl>
241 <dl><dt><a name="ExceptionPexpect-__setstate__"><strong>__setstate__</strong></a>(...)</dt></dl>
244 Data descriptors inherited from <a href="exceptions.html#BaseException">exceptions.BaseException</a>:<br>
245 <dl><dt><strong>__dict__</strong></dt>
247 <dl><dt><strong>args</strong></dt>
249 <dl><dt><strong>message</strong></dt>
250 <dd><tt>exception message</tt></dd>
252 </td></tr></table> <p>
253 <table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
254 <tr bgcolor="#ffc8d8">
255 <td colspan=3 valign=bottom> <br>
256 <font color="#000000" face="helvetica, arial"><a name="TIMEOUT">class <strong>TIMEOUT</strong></a>(<a href="pexpect.html#ExceptionPexpect">ExceptionPexpect</a>)</font></td></tr>
258 <tr bgcolor="#ffc8d8"><td rowspan=2><tt> </tt></td>
259 <td colspan=2><tt>Raised when a read time exceeds the timeout.<br> </tt></td></tr>
261 <td width="100%"><dl><dt>Method resolution order:</dt>
262 <dd><a href="pexpect.html#TIMEOUT">TIMEOUT</a></dd>
263 <dd><a href="pexpect.html#ExceptionPexpect">ExceptionPexpect</a></dd>
264 <dd><a href="exceptions.html#Exception">exceptions.Exception</a></dd>
265 <dd><a href="exceptions.html#BaseException">exceptions.BaseException</a></dd>
266 <dd><a href="__builtin__.html#object">__builtin__.object</a></dd>
269 Methods inherited from <a href="pexpect.html#ExceptionPexpect">ExceptionPexpect</a>:<br>
270 <dl><dt><a name="TIMEOUT-__init__"><strong>__init__</strong></a>(self, value)</dt></dl>
272 <dl><dt><a name="TIMEOUT-__str__"><strong>__str__</strong></a>(self)</dt></dl>
274 <dl><dt><a name="TIMEOUT-get_trace"><strong>get_trace</strong></a>(self)</dt><dd><tt>This returns an abbreviated stack trace with lines that only concern<br>
275 the caller. In other words, the stack trace inside the Pexpect module<br>
276 is not included.</tt></dd></dl>
279 Data descriptors inherited from <a href="pexpect.html#ExceptionPexpect">ExceptionPexpect</a>:<br>
280 <dl><dt><strong>__weakref__</strong></dt>
281 <dd><tt>list of weak references to the object (if defined)</tt></dd>
284 Data and other attributes inherited from <a href="exceptions.html#Exception">exceptions.Exception</a>:<br>
285 <dl><dt><strong>__new__</strong> = <built-in method __new__ of type object at 0x81400e0><dd><tt>T.<a href="#TIMEOUT-__new__">__new__</a>(S, ...) -> a new <a href="__builtin__.html#object">object</a> with type S, a subtype of T</tt></dl>
288 Methods inherited from <a href="exceptions.html#BaseException">exceptions.BaseException</a>:<br>
289 <dl><dt><a name="TIMEOUT-__delattr__"><strong>__delattr__</strong></a>(...)</dt><dd><tt>x.<a href="#TIMEOUT-__delattr__">__delattr__</a>('name') <==> del x.name</tt></dd></dl>
291 <dl><dt><a name="TIMEOUT-__getattribute__"><strong>__getattribute__</strong></a>(...)</dt><dd><tt>x.<a href="#TIMEOUT-__getattribute__">__getattribute__</a>('name') <==> x.name</tt></dd></dl>
293 <dl><dt><a name="TIMEOUT-__getitem__"><strong>__getitem__</strong></a>(...)</dt><dd><tt>x.<a href="#TIMEOUT-__getitem__">__getitem__</a>(y) <==> x[y]</tt></dd></dl>
295 <dl><dt><a name="TIMEOUT-__getslice__"><strong>__getslice__</strong></a>(...)</dt><dd><tt>x.<a href="#TIMEOUT-__getslice__">__getslice__</a>(i, j) <==> x[i:j]<br>
297 Use of negative indices is not supported.</tt></dd></dl>
299 <dl><dt><a name="TIMEOUT-__reduce__"><strong>__reduce__</strong></a>(...)</dt></dl>
301 <dl><dt><a name="TIMEOUT-__repr__"><strong>__repr__</strong></a>(...)</dt><dd><tt>x.<a href="#TIMEOUT-__repr__">__repr__</a>() <==> repr(x)</tt></dd></dl>
303 <dl><dt><a name="TIMEOUT-__setattr__"><strong>__setattr__</strong></a>(...)</dt><dd><tt>x.<a href="#TIMEOUT-__setattr__">__setattr__</a>('name', value) <==> x.name = value</tt></dd></dl>
305 <dl><dt><a name="TIMEOUT-__setstate__"><strong>__setstate__</strong></a>(...)</dt></dl>
308 Data descriptors inherited from <a href="exceptions.html#BaseException">exceptions.BaseException</a>:<br>
309 <dl><dt><strong>__dict__</strong></dt>
311 <dl><dt><strong>args</strong></dt>
313 <dl><dt><strong>message</strong></dt>
314 <dd><tt>exception message</tt></dd>
316 </td></tr></table> <p>
317 <table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
318 <tr bgcolor="#ffc8d8">
319 <td colspan=3 valign=bottom> <br>
320 <font color="#000000" face="helvetica, arial"><a name="spawn">class <strong>spawn</strong></a>(<a href="__builtin__.html#object">__builtin__.object</a>)</font></td></tr>
322 <tr bgcolor="#ffc8d8"><td rowspan=2><tt> </tt></td>
323 <td colspan=2><tt>This is the main class interface for Pexpect. Use this class to start<br>
324 and control child applications.<br> </tt></td></tr>
326 <td width="100%">Methods defined here:<br>
327 <dl><dt><a name="spawn-__del__"><strong>__del__</strong></a>(self)</dt><dd><tt>This makes sure that no system resources are left open. Python only<br>
328 garbage collects Python objects. OS file descriptors are not Python<br>
329 objects, so they must be handled explicitly. If the child file<br>
330 descriptor was opened outside of this class (passed to the constructor)<br>
331 then this does not close it.</tt></dd></dl>
333 <dl><dt><a name="spawn-__init__"><strong>__init__</strong></a>(self, command, args<font color="#909090">=[]</font>, timeout<font color="#909090">=30</font>, maxread<font color="#909090">=2000</font>, searchwindowsize<font color="#909090">=None</font>, logfile<font color="#909090">=None</font>, cwd<font color="#909090">=None</font>, env<font color="#909090">=None</font>)</dt><dd><tt>This is the constructor. The command parameter may be a string that<br>
334 includes a command and any arguments to the command. For example::<br>
336 child = pexpect.<a href="#spawn">spawn</a> ('/usr/bin/ftp')<br>
337 child = pexpect.<a href="#spawn">spawn</a> ('/usr/bin/ssh
[email protected]')<br>
338 child = pexpect.<a href="#spawn">spawn</a> ('ls -latr /tmp')<br>
340 You may also construct it with a list of arguments like so::<br>
342 child = pexpect.<a href="#spawn">spawn</a> ('/usr/bin/ftp', [])<br>
343 child = pexpect.<a href="#spawn">spawn</a> ('/usr/bin/ssh', ['
[email protected]'])<br>
344 child = pexpect.<a href="#spawn">spawn</a> ('ls', ['-latr', '/tmp'])<br>
346 After this the child application will be created and will be ready to<br>
347 talk to. For normal use, see <a href="#spawn-expect">expect</a>() and <a href="#spawn-send">send</a>() and <a href="#spawn-sendline">sendline</a>().<br>
349 Remember that Pexpect does NOT interpret shell meta characters such as<br>
350 redirect, pipe, or wild cards (>, |, or *). This is a common mistake.<br>
351 If you want to run a command and pipe it through another command then<br>
352 you must also start a shell. For example::<br>
354 child = pexpect.<a href="#spawn">spawn</a>('/bin/bash -c "ls -l | grep LOG > log_list.txt"')<br>
355 child.<a href="#spawn-expect">expect</a>(pexpect.<a href="#EOF">EOF</a>)<br>
357 The second form of <a href="#spawn">spawn</a> (where you pass a list of arguments) is useful<br>
358 in situations where you wish to <a href="#spawn">spawn</a> a command and pass it its own<br>
359 argument list. This can make syntax more clear. For example, the<br>
360 following is equivalent to the previous example::<br>
362 shell_cmd = 'ls -l | grep LOG > log_list.txt'<br>
363 child = pexpect.<a href="#spawn">spawn</a>('/bin/bash', ['-c', shell_cmd])<br>
364 child.<a href="#spawn-expect">expect</a>(pexpect.<a href="#EOF">EOF</a>)<br>
366 The maxread attribute sets the read buffer size. This is maximum number<br>
367 of bytes that Pexpect will try to read from a TTY at one time. Setting<br>
368 the maxread size to 1 will turn off buffering. Setting the maxread<br>
369 value higher may help performance in cases where large amounts of<br>
370 output are read back from the child. This feature is useful in<br>
371 conjunction with searchwindowsize.<br>
373 The searchwindowsize attribute sets the how far back in the incomming<br>
374 seach buffer Pexpect will search for pattern matches. Every time<br>
375 Pexpect reads some data from the child it will append the data to the<br>
376 incomming buffer. The default is to search from the beginning of the<br>
377 imcomming buffer each time new data is read from the child. But this is<br>
378 very inefficient if you are running a command that generates a large<br>
379 amount of data where you want to match The searchwindowsize does not<br>
380 effect the size of the incomming data buffer. You will still have<br>
381 access to the full buffer after <a href="#spawn-expect">expect</a>() returns.<br>
383 The logfile member turns on or off logging. All input and output will<br>
384 be copied to the given file <a href="__builtin__.html#object">object</a>. Set logfile to None to stop<br>
385 logging. This is the default. Set logfile to sys.stdout to echo<br>
386 everything to standard output. The logfile is flushed after each write.<br>
388 Example log input and output to a file::<br>
390 child = pexpect.<a href="#spawn">spawn</a>('some_command')<br>
391 fout = file('mylog.txt','w')<br>
392 child.logfile = fout<br>
394 Example log to stdout::<br>
396 child = pexpect.<a href="#spawn">spawn</a>('some_command')<br>
397 child.logfile = sys.stdout<br>
399 The logfile_read and logfile_send members can be used to separately log<br>
400 the input from the child and output sent to the child. Sometimes you<br>
401 don't want to see everything you write to the child. You only want to<br>
402 log what the child sends back. For example::<br>
404 child = pexpect.<a href="#spawn">spawn</a>('some_command')<br>
405 child.logfile_read = sys.stdout<br>
407 To separately log output sent to the child use logfile_send::<br>
409 self.<strong>logfile_send</strong> = fout<br>
411 The delaybeforesend helps overcome a weird behavior that many users<br>
412 were experiencing. The typical problem was that a user would <a href="#spawn-expect">expect</a>() a<br>
413 "Password:" prompt and then immediately call <a href="#spawn-sendline">sendline</a>() to send the<br>
414 password. The user would then see that their password was echoed back<br>
415 to them. Passwords don't normally echo. The problem is caused by the<br>
416 fact that most applications print out the "Password" prompt and then<br>
417 turn off stdin echo, but if you send your password before the<br>
418 application turned off echo, then you get your password echoed.<br>
419 Normally this wouldn't be a problem when interacting with a human at a<br>
420 real keyboard. If you introduce a slight delay just before writing then<br>
421 this seems to clear up the problem. This was such a common problem for<br>
422 many users that I decided that the default pexpect behavior should be<br>
423 to sleep just before writing to the child application. 1/20th of a<br>
424 second (50 ms) seems to be enough to clear up the problem. You can set<br>
425 delaybeforesend to 0 to return to the old behavior. Most Linux machines<br>
426 don't like this to be below 0.03. I don't know why.<br>
428 Note that <a href="#spawn">spawn</a> is clever about finding commands on your path.<br>
429 It uses the same logic that "which" uses to find executables.<br>
431 If you wish to get the exit status of the child you must call the<br>
432 <a href="#spawn-close">close</a>() method. The exit or signal status of the child will be stored<br>
433 in self.<strong>exitstatus</strong> or self.<strong>signalstatus</strong>. If the child exited normally<br>
434 then exitstatus will store the exit return code and signalstatus will<br>
435 be None. If the child was terminated abnormally with a signal then<br>
436 signalstatus will store the signal value and exitstatus will be None.<br>
437 If you need more detail you can also read the self.<strong>status</strong> member which<br>
438 stores the status returned by os.waitpid. You can interpret this using<br>
439 os.WIFEXITED/os.WEXITSTATUS or os.WIFSIGNALED/os.TERMSIG.</tt></dd></dl>
441 <dl><dt><a name="spawn-__iter__"><strong>__iter__</strong></a>(self)</dt><dd><tt>This is to support iterators over a file-like <a href="__builtin__.html#object">object</a>.</tt></dd></dl>
443 <dl><dt><a name="spawn-__str__"><strong>__str__</strong></a>(self)</dt><dd><tt>This returns a human-readable string that represents the state of<br>
444 the <a href="__builtin__.html#object">object</a>.</tt></dd></dl>
446 <dl><dt><a name="spawn-close"><strong>close</strong></a>(self, force<font color="#909090">=True</font>)</dt><dd><tt>This closes the connection with the child application. Note that<br>
447 calling <a href="#spawn-close">close</a>() more than once is valid. This emulates standard Python<br>
448 behavior with files. Set force to True if you want to make sure that<br>
449 the child is terminated (SIGKILL is sent if the child ignores SIGHUP<br>
450 and SIGINT).</tt></dd></dl>
452 <dl><dt><a name="spawn-compile_pattern_list"><strong>compile_pattern_list</strong></a>(self, patterns)</dt><dd><tt>This compiles a pattern-string or a list of pattern-strings.<br>
453 Patterns must be a StringType, <a href="#EOF">EOF</a>, <a href="#TIMEOUT">TIMEOUT</a>, SRE_Pattern, or a list of<br>
454 those. Patterns may also be None which results in an empty list (you<br>
455 might do this if waiting for an <a href="#EOF">EOF</a> or <a href="#TIMEOUT">TIMEOUT</a> condition without<br>
456 expecting any pattern).<br>
458 This is used by <a href="#spawn-expect">expect</a>() when calling <a href="#spawn-expect_list">expect_list</a>(). Thus <a href="#spawn-expect">expect</a>() is<br>
459 nothing more than::<br>
461 cpl = <a href="#spawn-compile_pattern_list">compile_pattern_list</a>(pl)<br>
462 return <a href="#spawn-expect_list">expect_list</a>(cpl, timeout)<br>
464 If you are using <a href="#spawn-expect">expect</a>() within a loop it may be more<br>
465 efficient to compile the patterns first and then call <a href="#spawn-expect_list">expect_list</a>().<br>
466 This avoid calls in a loop to <a href="#spawn-compile_pattern_list">compile_pattern_list</a>()::<br>
468 cpl = <a href="#spawn-compile_pattern_list">compile_pattern_list</a>(my_pattern)<br>
469 while some_condition:<br>
470 ...<br>
471 i = <a href="#spawn-expect_list">expect_list</a>(clp, timeout)<br>
472 ...</tt></dd></dl>
474 <dl><dt><a name="spawn-eof"><strong>eof</strong></a>(self)</dt><dd><tt>This returns True if the <a href="#EOF">EOF</a> exception was ever raised.</tt></dd></dl>
476 <dl><dt><a name="spawn-expect"><strong>expect</strong></a>(self, pattern, timeout<font color="#909090">=-1</font>, searchwindowsize<font color="#909090">=None</font>)</dt><dd><tt>This seeks through the stream until a pattern is matched. The<br>
477 pattern is overloaded and may take several types. The pattern can be a<br>
478 StringType, <a href="#EOF">EOF</a>, a compiled re, or a list of any of those types.<br>
479 Strings will be compiled to re types. This returns the index into the<br>
480 pattern list. If the pattern was not a list this returns index 0 on a<br>
481 successful match. This may raise exceptions for <a href="#EOF">EOF</a> or <a href="#TIMEOUT">TIMEOUT</a>. To<br>
482 avoid the <a href="#EOF">EOF</a> or <a href="#TIMEOUT">TIMEOUT</a> exceptions add <a href="#EOF">EOF</a> or <a href="#TIMEOUT">TIMEOUT</a> to the pattern<br>
483 list. That will cause expect to match an <a href="#EOF">EOF</a> or <a href="#TIMEOUT">TIMEOUT</a> condition<br>
484 instead of raising an exception.<br>
486 If you pass a list of patterns and more than one matches, the first match<br>
487 in the stream is chosen. If more than one pattern matches at that point,<br>
488 the leftmost in the pattern list is chosen. For example::<br>
490 # the input is 'foobar'<br>
491 index = p.expect (['bar', 'foo', 'foobar'])<br>
492 # returns 1 ('foo') even though 'foobar' is a "better" match<br>
494 Please note, however, that buffering can affect this behavior, since<br>
495 input arrives in unpredictable chunks. For example::<br>
497 # the input is 'foobar'<br>
498 index = p.expect (['foobar', 'foo'])<br>
499 # returns 0 ('foobar') if all input is available at once,<br>
500 # but returs 1 ('foo') if parts of the final 'bar' arrive late<br>
502 After a match is found the instance attributes 'before', 'after' and<br>
503 'match' will be set. You can see all the data read before the match in<br>
504 'before'. You can see the data that was matched in 'after'. The<br>
505 re.MatchObject used in the re match will be in 'match'. If an error<br>
506 occurred then 'before' will be set to all the data read so far and<br>
507 'after' and 'match' will be None.<br>
509 If timeout is -1 then timeout will be set to the self.<strong>timeout</strong> value.<br>
511 A list entry may be <a href="#EOF">EOF</a> or <a href="#TIMEOUT">TIMEOUT</a> instead of a string. This will<br>
512 catch these exceptions and return the index of the list entry instead<br>
513 of raising the exception. The attribute 'after' will be set to the<br>
514 exception type. The attribute 'match' will be None. This allows you to<br>
515 write code like this::<br>
517 index = p.expect (['good', 'bad', pexpect.<a href="#EOF">EOF</a>, pexpect.<a href="#TIMEOUT">TIMEOUT</a>])<br>
518 if index == 0:<br>
519 do_something()<br>
520 elif index == 1:<br>
521 do_something_else()<br>
522 elif index == 2:<br>
523 do_some_other_thing()<br>
524 elif index == 3:<br>
525 do_something_completely_different()<br>
527 instead of code like this::<br>
529 try:<br>
530 index = p.expect (['good', 'bad'])<br>
531 if index == 0:<br>
532 do_something()<br>
533 elif index == 1:<br>
534 do_something_else()<br>
535 except <a href="#EOF">EOF</a>:<br>
536 do_some_other_thing()<br>
537 except <a href="#TIMEOUT">TIMEOUT</a>:<br>
538 do_something_completely_different()<br>
540 These two forms are equivalent. It all depends on what you want. You<br>
541 can also just expect the <a href="#EOF">EOF</a> if you are waiting for all output of a<br>
542 child to finish. For example::<br>
544 p = pexpect.<a href="#spawn">spawn</a>('/bin/ls')<br>
545 p.expect (pexpect.<a href="#EOF">EOF</a>)<br>
546 print p.before<br>
548 If you are trying to optimize for speed then see <a href="#spawn-expect_list">expect_list</a>().</tt></dd></dl>
550 <dl><dt><a name="spawn-expect_exact"><strong>expect_exact</strong></a>(self, pattern_list, timeout<font color="#909090">=-1</font>, searchwindowsize<font color="#909090">=-1</font>)</dt><dd><tt>This is similar to <a href="#spawn-expect">expect</a>(), but uses plain string matching instead<br>
551 of compiled regular expressions in 'pattern_list'. The 'pattern_list'<br>
552 may be a string; a list or other sequence of strings; or <a href="#TIMEOUT">TIMEOUT</a> and<br>
553 <a href="#EOF">EOF</a>.<br>
555 This call might be faster than <a href="#spawn-expect">expect</a>() for two reasons: string<br>
556 searching is faster than RE matching and it is possible to limit the<br>
557 search to just the end of the input buffer.<br>
559 This method is also useful when you don't want to have to worry about<br>
560 escaping regular expression characters that you want to match.</tt></dd></dl>
562 <dl><dt><a name="spawn-expect_list"><strong>expect_list</strong></a>(self, pattern_list, timeout<font color="#909090">=-1</font>, searchwindowsize<font color="#909090">=-1</font>)</dt><dd><tt>This takes a list of compiled regular expressions and returns the<br>
563 index into the pattern_list that matched the child output. The list may<br>
564 also contain <a href="#EOF">EOF</a> or <a href="#TIMEOUT">TIMEOUT</a> (which are not compiled regular<br>
565 expressions). This method is similar to the <a href="#spawn-expect">expect</a>() method except that<br>
566 <a href="#spawn-expect_list">expect_list</a>() does not recompile the pattern list on every call. This<br>
567 may help if you are trying to optimize for speed, otherwise just use<br>
568 the <a href="#spawn-expect">expect</a>() method. This is called by <a href="#spawn-expect">expect</a>(). If timeout==-1 then<br>
569 the self.<strong>timeout</strong> value is used. If searchwindowsize==-1 then the<br>
570 self.<strong>searchwindowsize</strong> value is used.</tt></dd></dl>
572 <dl><dt><a name="spawn-expect_loop"><strong>expect_loop</strong></a>(self, searcher, timeout<font color="#909090">=-1</font>, searchwindowsize<font color="#909090">=-1</font>)</dt><dd><tt>This is the common loop used inside expect. The 'searcher' should be<br>
573 an instance of searcher_re or searcher_string, which describes how and what<br>
574 to search for in the input.<br>
576 See <a href="#spawn-expect">expect</a>() for other arguments, return value and exceptions.</tt></dd></dl>
578 <dl><dt><a name="spawn-fileno"><strong>fileno</strong></a>(self)</dt><dd><tt>This returns the file descriptor of the pty for the child.</tt></dd></dl>
580 <dl><dt><a name="spawn-flush"><strong>flush</strong></a>(self)</dt><dd><tt>This does nothing. It is here to support the interface for a<br>
581 File-like <a href="__builtin__.html#object">object</a>.</tt></dd></dl>
583 <dl><dt><a name="spawn-getecho"><strong>getecho</strong></a>(self)</dt><dd><tt>This returns the terminal echo mode. This returns True if echo is<br>
584 on or False if echo is off. Child applications that are expecting you<br>
585 to enter a password often set ECHO False. See <a href="#spawn-waitnoecho">waitnoecho</a>().</tt></dd></dl>
587 <dl><dt><a name="spawn-getwinsize"><strong>getwinsize</strong></a>(self)</dt><dd><tt>This returns the terminal window size of the child tty. The return<br>
588 value is a tuple of (rows, cols).</tt></dd></dl>
590 <dl><dt><a name="spawn-interact"><strong>interact</strong></a>(self, escape_character<font color="#909090">='<font color="#c040c0">\x1d</font>'</font>, input_filter<font color="#909090">=None</font>, output_filter<font color="#909090">=None</font>)</dt><dd><tt>This gives control of the child process to the interactive user (the<br>
591 human at the keyboard). Keystrokes are sent to the child process, and<br>
592 the stdout and stderr output of the child process is printed. This<br>
593 simply echos the child stdout and child stderr to the real stdout and<br>
594 it echos the real stdin to the child stdin. When the user types the<br>
595 escape_character this method will stop. The default for<br>
596 escape_character is ^]. This should not be confused with ASCII 27 --<br>
597 the ESC character. ASCII 29 was chosen for historical merit because<br>
598 this is the character used by 'telnet' as the escape character. The<br>
599 escape_character will not be sent to the child process.<br>
601 You may pass in optional input and output filter functions. These<br>
602 functions should take a string and return a string. The output_filter<br>
603 will be passed all the output from the child process. The input_filter<br>
604 will be passed all the keyboard input from the user. The input_filter<br>
605 is run BEFORE the check for the escape_character.<br>
607 Note that if you change the window size of the parent the SIGWINCH<br>
608 signal will not be passed through to the child. If you want the child<br>
609 window size to change when the parent's window size changes then do<br>
610 something like the following example::<br>
612 import pexpect, struct, fcntl, termios, signal, sys<br>
613 def sigwinch_passthrough (sig, data):<br>
614 s = struct.pack("HHHH", 0, 0, 0, 0)<br>
615 a = struct.unpack('hhhh', fcntl.ioctl(sys.stdout.<a href="#spawn-fileno">fileno</a>(), termios.TIOCGWINSZ , s))<br>
616 global p<br>
617 p.<a href="#spawn-setwinsize">setwinsize</a>(a[0],a[1])<br>
618 p = pexpect.<a href="#spawn">spawn</a>('/bin/bash') # Note this is global and used in sigwinch_passthrough.<br>
619 signal.signal(signal.SIGWINCH, sigwinch_passthrough)<br>
620 p.<a href="#spawn-interact">interact</a>()</tt></dd></dl>
622 <dl><dt><a name="spawn-isalive"><strong>isalive</strong></a>(self)</dt><dd><tt>This tests if the child process is running or not. This is<br>
623 non-blocking. If the child was terminated then this will read the<br>
624 exitstatus or signalstatus of the child. This returns True if the child<br>
625 process appears to be running or False if not. It can take literally<br>
626 SECONDS for Solaris to return the right status.</tt></dd></dl>
628 <dl><dt><a name="spawn-isatty"><strong>isatty</strong></a>(self)</dt><dd><tt>This returns True if the file descriptor is open and connected to a<br>
629 tty(-like) device, else False.</tt></dd></dl>
631 <dl><dt><a name="spawn-kill"><strong>kill</strong></a>(self, sig)</dt><dd><tt>This sends the given signal to the child application. In keeping<br>
632 with UNIX tradition it has a misleading name. It does not necessarily<br>
633 kill the child unless you send the right signal.</tt></dd></dl>
635 <dl><dt><a name="spawn-next"><strong>next</strong></a>(self)</dt><dd><tt>This is to support iterators over a file-like <a href="__builtin__.html#object">object</a>.</tt></dd></dl>
637 <dl><dt><a name="spawn-read"><strong>read</strong></a>(self, size<font color="#909090">=-1</font>)</dt><dd><tt>This reads at most "size" bytes from the file (less if the read hits<br>
638 <a href="#EOF">EOF</a> before obtaining size bytes). If the size argument is negative or<br>
639 omitted, read all data until <a href="#EOF">EOF</a> is reached. The bytes are returned as<br>
640 a string <a href="__builtin__.html#object">object</a>. An empty string is returned when <a href="#EOF">EOF</a> is encountered<br>
641 immediately.</tt></dd></dl>
643 <dl><dt><a name="spawn-read_nonblocking"><strong>read_nonblocking</strong></a>(self, size<font color="#909090">=1</font>, timeout<font color="#909090">=-1</font>)</dt><dd><tt>This reads at most size characters from the child application. It<br>
644 includes a timeout. If the read does not complete within the timeout<br>
645 period then a <a href="#TIMEOUT">TIMEOUT</a> exception is raised. If the end of file is read<br>
646 then an <a href="#EOF">EOF</a> exception will be raised. If a log file was set using<br>
647 <a href="#spawn-setlog">setlog</a>() then all data will also be written to the log file.<br>
649 If timeout is None then the read may block indefinitely. If timeout is -1<br>
650 then the self.<strong>timeout</strong> value is used. If timeout is 0 then the child is<br>
651 polled and if there was no data immediately ready then this will raise<br>
652 a <a href="#TIMEOUT">TIMEOUT</a> exception.<br>
654 The timeout refers only to the amount of time to read at least one<br>
655 character. This is not effected by the 'size' parameter, so if you call<br>
656 <a href="#spawn-read_nonblocking">read_nonblocking</a>(size=100, timeout=30) and only one character is<br>
657 available right away then one character will be returned immediately.<br>
658 It will not wait for 30 seconds for another 99 characters to come in.<br>
660 This is a wrapper around os.<a href="#spawn-read">read</a>(). It uses select.select() to<br>
661 implement the timeout.</tt></dd></dl>
663 <dl><dt><a name="spawn-readline"><strong>readline</strong></a>(self, size<font color="#909090">=-1</font>)</dt><dd><tt>This reads and returns one entire line. A trailing newline is kept<br>
664 in the string, but may be absent when a file ends with an incomplete<br>
665 line. Note: This <a href="#spawn-readline">readline</a>() looks for a \r\n pair even on UNIX<br>
666 because this is what the pseudo tty device returns. So contrary to what<br>
667 you may expect you will receive the newline as \r\n. An empty string<br>
668 is returned when <a href="#EOF">EOF</a> is hit immediately. Currently, the size argument is<br>
669 mostly ignored, so this behavior is not standard for a file-like<br>
670 <a href="__builtin__.html#object">object</a>. If size is 0 then an empty string is returned.</tt></dd></dl>
672 <dl><dt><a name="spawn-readlines"><strong>readlines</strong></a>(self, sizehint<font color="#909090">=-1</font>)</dt><dd><tt>This reads until <a href="#EOF">EOF</a> using <a href="#spawn-readline">readline</a>() and returns a list containing<br>
673 the lines thus read. The optional "sizehint" argument is ignored.</tt></dd></dl>
675 <dl><dt><a name="spawn-send"><strong>send</strong></a>(self, s)</dt><dd><tt>This sends a string to the child process. This returns the number of<br>
676 bytes written. If a log file was set then the data is also written to<br>
677 the log.</tt></dd></dl>
679 <dl><dt><a name="spawn-sendcontrol"><strong>sendcontrol</strong></a>(self, char)</dt><dd><tt>This sends a control character to the child such as Ctrl-C or<br>
680 Ctrl-D. For example, to send a Ctrl-G (ASCII 7)::<br>
682 child.<a href="#spawn-sendcontrol">sendcontrol</a>('g')<br>
684 See also, <a href="#spawn-sendintr">sendintr</a>() and <a href="#spawn-sendeof">sendeof</a>().</tt></dd></dl>
686 <dl><dt><a name="spawn-sendeof"><strong>sendeof</strong></a>(self)</dt><dd><tt>This sends an <a href="#EOF">EOF</a> to the child. This sends a character which causes<br>
687 the pending parent output buffer to be sent to the waiting child<br>
688 program without waiting for end-of-line. If it is the first character<br>
689 of the line, the <a href="#spawn-read">read</a>() in the user program returns 0, which signifies<br>
690 end-of-file. This means to work as expected a <a href="#spawn-sendeof">sendeof</a>() has to be<br>
691 called at the beginning of a line. This method does not send a newline.<br>
692 It is the responsibility of the caller to ensure the eof is sent at the<br>
693 beginning of a line.</tt></dd></dl>
695 <dl><dt><a name="spawn-sendintr"><strong>sendintr</strong></a>(self)</dt><dd><tt>This sends a SIGINT to the child. It does not require<br>
696 the SIGINT to be the first character on a line.</tt></dd></dl>
698 <dl><dt><a name="spawn-sendline"><strong>sendline</strong></a>(self, s<font color="#909090">=''</font>)</dt><dd><tt>This is like <a href="#spawn-send">send</a>(), but it adds a line feed (os.linesep). This<br>
699 returns the number of bytes written.</tt></dd></dl>
701 <dl><dt><a name="spawn-setecho"><strong>setecho</strong></a>(self, state)</dt><dd><tt>This sets the terminal echo mode on or off. Note that anything the<br>
702 child sent before the echo will be lost, so you should be sure that<br>
703 your input buffer is empty before you call <a href="#spawn-setecho">setecho</a>(). For example, the<br>
704 following will work as expected::<br>
706 p = pexpect.<a href="#spawn">spawn</a>('cat')<br>
707 p.sendline ('1234') # We will see this twice (once from tty echo and again from cat).<br>
708 p.expect (['1234'])<br>
709 p.expect (['1234'])<br>
710 p.<a href="#spawn-setecho">setecho</a>(False) # Turn off tty echo<br>
711 p.sendline ('abcd') # We will set this only once (echoed by cat).<br>
712 p.sendline ('wxyz') # We will set this only once (echoed by cat)<br>
713 p.expect (['abcd'])<br>
714 p.expect (['wxyz'])<br>
716 The following WILL NOT WORK because the lines sent before the setecho<br>
717 will be lost::<br>
719 p = pexpect.<a href="#spawn">spawn</a>('cat')<br>
720 p.sendline ('1234') # We will see this twice (once from tty echo and again from cat).<br>
721 p.<a href="#spawn-setecho">setecho</a>(False) # Turn off tty echo<br>
722 p.sendline ('abcd') # We will set this only once (echoed by cat).<br>
723 p.sendline ('wxyz') # We will set this only once (echoed by cat)<br>
724 p.expect (['1234'])<br>
725 p.expect (['1234'])<br>
726 p.expect (['abcd'])<br>
727 p.expect (['wxyz'])</tt></dd></dl>
729 <dl><dt><a name="spawn-setlog"><strong>setlog</strong></a>(self, fileobject)</dt><dd><tt>This method is no longer supported or allowed.</tt></dd></dl>
731 <dl><dt><a name="spawn-setmaxread"><strong>setmaxread</strong></a>(self, maxread)</dt><dd><tt>This method is no longer supported or allowed. I don't like getters<br>
732 and setters without a good reason.</tt></dd></dl>
734 <dl><dt><a name="spawn-setwinsize"><strong>setwinsize</strong></a>(self, r, c)</dt><dd><tt>This sets the terminal window size of the child tty. This will cause<br>
735 a SIGWINCH signal to be sent to the child. This does not change the<br>
736 physical window size. It changes the size reported to TTY-aware<br>
737 applications like vi or curses -- applications that respond to the<br>
738 SIGWINCH signal.</tt></dd></dl>
740 <dl><dt><a name="spawn-terminate"><strong>terminate</strong></a>(self, force<font color="#909090">=False</font>)</dt><dd><tt>This forces a child process to terminate. It starts nicely with<br>
741 SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This<br>
742 returns True if the child was terminated. This returns False if the<br>
743 child could not be terminated.</tt></dd></dl>
745 <dl><dt><a name="spawn-wait"><strong>wait</strong></a>(self)</dt><dd><tt>This waits until the child exits. This is a blocking call. This will<br>
746 not read any data from the child, so this will block forever if the<br>
747 child has unread output and has terminated. In other words, the child<br>
748 may have printed output then called exit(); but, technically, the child<br>
749 is still alive until its output is read.</tt></dd></dl>
751 <dl><dt><a name="spawn-waitnoecho"><strong>waitnoecho</strong></a>(self, timeout<font color="#909090">=-1</font>)</dt><dd><tt>This waits until the terminal ECHO flag is set False. This returns<br>
752 True if the echo mode is off. This returns False if the ECHO flag was<br>
753 not set False before the timeout. This can be used to detect when the<br>
754 child is waiting for a password. Usually a child application will turn<br>
755 off echo mode when it is waiting for the user to enter a password. For<br>
756 example, instead of expecting the "password:" prompt you can wait for<br>
757 the child to set ECHO off::<br>
759 p = pexpect.<a href="#spawn">spawn</a> ('ssh
[email protected]')<br>
760 p.<a href="#spawn-waitnoecho">waitnoecho</a>()<br>
761 p.<a href="#spawn-sendline">sendline</a>(mypassword)<br>
763 If timeout is None then this method to block forever until ECHO flag is<br>
764 False.</tt></dd></dl>
766 <dl><dt><a name="spawn-write"><strong>write</strong></a>(self, s)</dt><dd><tt>This is similar to <a href="#spawn-send">send</a>() except that there is no return value.</tt></dd></dl>
768 <dl><dt><a name="spawn-writelines"><strong>writelines</strong></a>(self, sequence)</dt><dd><tt>This calls <a href="#spawn-write">write</a>() for each element in the sequence. The sequence<br>
769 can be any iterable <a href="__builtin__.html#object">object</a> producing strings, typically a list of<br>
770 strings. This does not add line separators There is no return value.</tt></dd></dl>
773 Data descriptors defined here:<br>
774 <dl><dt><strong>__dict__</strong></dt>
775 <dd><tt>dictionary for instance variables (if defined)</tt></dd>
777 <dl><dt><strong>__weakref__</strong></dt>
778 <dd><tt>list of weak references to the object (if defined)</tt></dd>
780 </td></tr></table></td></tr></table><p>
781 <table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
782 <tr bgcolor="#eeaa77">
783 <td colspan=3 valign=bottom> <br>
784 <font color="#ffffff" face="helvetica, arial"><big><strong>Functions</strong></big></font></td></tr>
786 <tr><td bgcolor="#eeaa77"><tt> </tt></td><td> </td>
787 <td width="100%"><dl><dt><a name="-run"><strong>run</strong></a>(command, timeout<font color="#909090">=-1</font>, withexitstatus<font color="#909090">=False</font>, events<font color="#909090">=None</font>, extra_args<font color="#909090">=None</font>, logfile<font color="#909090">=None</font>, cwd<font color="#909090">=None</font>, env<font color="#909090">=None</font>)</dt><dd><tt>This function runs the given command; waits for it to finish; then<br>
788 returns all output as a string. STDERR is included in output. If the full<br>
789 path to the command is not given then the path is searched.<br>
791 Note that lines are terminated by CR/LF (\r\n) combination even on<br>
792 UNIX-like systems because this is the standard for pseudo ttys. If you set<br>
793 'withexitstatus' to true, then run will return a tuple of (command_output,<br>
794 exitstatus). If 'withexitstatus' is false then this returns just<br>
797 The <a href="#-run">run</a>() function can often be used instead of creating a <a href="#spawn">spawn</a> instance.<br>
798 For example, the following code uses <a href="#spawn">spawn</a>::<br>
800 from pexpect import *<br>
801 child = <a href="#spawn">spawn</a>('scp foo
[email protected]:.')<br>
802 child.expect ('(?i)password')<br>
803 child.sendline (mypassword)<br>
805 The previous code can be replace with the following::<br>
807 from pexpect import *<br>
808 run ('scp foo
[email protected]:.', events={'(?i)password': mypassword})<br>
813 Start the apache daemon on the local machine::<br>
815 from pexpect import *<br>
816 run ("/usr/local/apache/bin/apachectl start")<br>
818 Check in a file using SVN::<br>
820 from pexpect import *<br>
821 run ("svn ci -m 'automatic commit' my_file.py")<br>
823 Run a command and capture exit status::<br>
825 from pexpect import *<br>
826 (command_output, exitstatus) = run ('ls -l /bin', withexitstatus=1)<br>
828 Tricky Examples<br>
831 The following will run SSH and execute 'ls -l' on the remote machine. The<br>
832 password 'secret' will be sent if the '(?i)password' pattern is ever seen::<br>
834 run ("ssh
[email protected] 'ls -l'", events={'(?i)password':'secret\n'})<br>
836 This will start mencoder to rip a video from DVD. This will also display<br>
837 progress ticks every 5 seconds as it runs. For example::<br>
839 from pexpect import *<br>
840 def print_ticks(d):<br>
841 print d['event_count'],<br>
842 run ("mencoder dvd://1 -o video.avi -oac copy -ovc copy", events={<a href="#TIMEOUT">TIMEOUT</a>:print_ticks}, timeout=5)<br>
844 The 'events' argument should be a dictionary of patterns and responses.<br>
845 Whenever one of the patterns is seen in the command out <a href="#-run">run</a>() will send the<br>
846 associated response string. Note that you should put newlines in your<br>
847 string if Enter is necessary. The responses may also contain callback<br>
848 functions. Any callback is function that takes a dictionary as an argument.<br>
849 The dictionary contains all the locals from the <a href="#-run">run</a>() function, so you can<br>
850 access the child <a href="#spawn">spawn</a> <a href="__builtin__.html#object">object</a> or any other variable defined in <a href="#-run">run</a>()<br>
851 (event_count, child, and extra_args are the most useful). A callback may<br>
852 return True to stop the current run process otherwise <a href="#-run">run</a>() continues until<br>
853 the next event. A callback may also return a string which will be sent to<br>
854 the child. 'extra_args' is not used by directly <a href="#-run">run</a>(). It provides a way to<br>
855 pass data to a callback function through <a href="#-run">run</a>() through the locals<br>
856 dictionary passed to a callback.</tt></dd></dl>
857 <dl><dt><a name="-split_command_line"><strong>split_command_line</strong></a>(command_line)</dt><dd><tt>This splits a command line into a list of arguments. It splits arguments<br>
858 on spaces, but handles embedded quotes, doublequotes, and escaped<br>
859 characters. It's impossible to do this with a regular expression, so I<br>
860 wrote a little state machine to parse the command line.</tt></dd></dl>
861 <dl><dt><a name="-which"><strong>which</strong></a>(filename)</dt><dd><tt>This takes a given filename; tries to find it in the environment path;<br>
862 then checks if it is executable. This returns the full path to the filename<br>
863 if found and executable. Otherwise this returns None.</tt></dd></dl>
864 </td></tr></table><p>
865 <table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
866 <tr bgcolor="#55aa55">
867 <td colspan=3 valign=bottom> <br>
868 <font color="#ffffff" face="helvetica, arial"><big><strong>Data</strong></big></font></td></tr>
870 <tr><td bgcolor="#55aa55"><tt> </tt></td><td> </td>
871 <td width="100%"><strong>__all__</strong> = ['ExceptionPexpect', 'EOF', 'TIMEOUT', 'spawn', 'run', 'which', 'split_command_line', '__version__', '__revision__']<br>
872 <strong>__revision__</strong> = '$Revision: 399 $'<br>
873 <strong>__version__</strong> = '2.3'</td></tr></table>