1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
|
<!doctype html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html><head><title>Python: module pexpect</title>
</head><body bgcolor="#f0f0f8">
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="heading">
<tr bgcolor="#7799ee">
<td valign=bottom> <br>
<font color="#ffffff" face="helvetica, arial"> <br><big><big><strong>pexpect</strong></big></big> (version 2.1)</font></td
><td align=right valign=bottom
><font color="#ffffff" face="helvetica, arial"><a href=".">index</a><br><a href="file:/home/noah/documents/export/engineering/source/python/pexpect/trunk/pexpect/pexpect.py">/home/noah/documents/export/engineering/source/python/pexpect/trunk/pexpect/pexpect.py</a></font></td></tr></table>
<p><tt>Pexpect is a Python module for spawning child applications and controlling<br>
them automatically. Pexpect can be used for automating interactive applications<br>
such as ssh, ftp, passwd, telnet, etc. It can be used to a automate setup<br>
scripts for duplicating software package installations on different servers. It<br>
can be used for automated software testing. Pexpect is in the spirit of Don<br>
Libes' Expect, but Pexpect is pure Python. Other Expect-like modules for Python<br>
require TCL and Expect or require C extensions to be compiled. Pexpect does not<br>
use C, Expect, or TCL extensions. It should work on any platform that supports<br>
the standard Python pty module. The Pexpect interface focuses on ease of use so<br>
that simple tasks are easy.<br>
<br>
There are two main interfaces to Pexpect -- the function, <a href="#-run">run</a>() and the class,<br>
<a href="#spawn">spawn</a>. You can call the <a href="#-run">run</a>() function to execute a command and return the<br>
output. This is a handy replacement for os.system().<br>
<br>
For example:<br>
pexpect.<a href="#-run">run</a>('ls -la')<br>
<br>
The more powerful interface is the <a href="#spawn">spawn</a> class. You can use this to <a href="#spawn">spawn</a> an<br>
external child command and then interact with the child by sending lines and<br>
expecting responses.<br>
<br>
For example:<br>
child = pexpect.<a href="#spawn">spawn</a>('scp foo myname@host.example.com:.')<br>
child.expect ('Password:')<br>
child.sendline (mypassword)<br>
<br>
This works even for commands that ask for passwords or other input outside of<br>
the normal stdio streams.<br>
<br>
Credits:<br>
Noah Spurrier, Richard Holden, Marco Molteni, Kimberley Burchett, Robert Stone,<br>
Hartmut Goebel, Chad Schroeder, Erick Tryzelaar, Dave Kirby, Ids vander Molen,<br>
George Todd, Noel Taylor, Nicolas D. Cesar, Alexander Gattin,<br>
Geoffrey Marshall, Francisco Lourenco, Glen Mabey, Karthik Gurusamy,<br>
Fernando Perez <br>
(Let me know if I forgot anyone.)<br>
<br>
Free, open source, and all that good stuff.<br>
<br>
Permission is hereby granted, free of charge, to any person obtaining a copy of<br>
this software and associated documentation files (the "Software"), to deal in<br>
the Software without restriction, including without limitation the rights to<br>
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies<br>
of the Software, and to permit persons to whom the Software is furnished to do<br>
so, subject to the following conditions:<br>
<br>
The above copyright notice and this permission notice shall be included in all<br>
copies or substantial portions of the Software.<br>
<br>
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR<br>
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,<br>
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE<br>
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER<br>
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,<br>
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE<br>
SOFTWARE.<br>
<br>
Pexpect Copyright (c) 2006 Noah Spurrier<br>
<a href="http://pexpect.sourceforge.net/">http://pexpect.sourceforge.net/</a><br>
<br>
$Revision: 395 $<br>
$Date: 2006-05-31 20:07:18 -0700 (Wed, 31 May 2006) $</tt></p>
<p>
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#aa55cc">
<td colspan=3 valign=bottom> <br>
<font color="#fffff" face="helvetica, arial"><big><strong>Modules</strong></big></font></td></tr>
<tr><td bgcolor="#aa55cc"><tt> </tt></td><td> </td>
<td width="100%"><table width="100%" summary="list"><tr><td width="25%" valign=top><a href="errno.html">errno</a><br>
<a href="fcntl.html">fcntl</a><br>
<a href="os.html">os</a><br>
<a href="pty.html">pty</a><br>
</td><td width="25%" valign=top><a href="re.html">re</a><br>
<a href="resource.html">resource</a><br>
<a href="select.html">select</a><br>
<a href="signal.html">signal</a><br>
</td><td width="25%" valign=top><a href="string.html">string</a><br>
<a href="struct.html">struct</a><br>
<a href="sys.html">sys</a><br>
<a href="termios.html">termios</a><br>
</td><td width="25%" valign=top><a href="time.html">time</a><br>
<a href="traceback.html">traceback</a><br>
<a href="tty.html">tty</a><br>
<a href="types.html">types</a><br>
</td></tr></table></td></tr></table><p>
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#ee77aa">
<td colspan=3 valign=bottom> <br>
<font color="#ffffff" face="helvetica, arial"><big><strong>Classes</strong></big></font></td></tr>
<tr><td bgcolor="#ee77aa"><tt> </tt></td><td> </td>
<td width="100%"><dl>
<dt><font face="helvetica, arial"><a href="__builtin__.html#object">__builtin__.object</a>
</font></dt><dd>
<dl>
<dt><font face="helvetica, arial"><a href="pexpect.html#spawn">spawn</a>
</font></dt></dl>
</dd>
<dt><font face="helvetica, arial"><a href="exceptions.html#Exception">exceptions.Exception</a>
</font></dt><dd>
<dl>
<dt><font face="helvetica, arial"><a href="pexpect.html#ExceptionPexpect">ExceptionPexpect</a>
</font></dt><dd>
<dl>
<dt><font face="helvetica, arial"><a href="pexpect.html#EOF">EOF</a>
</font></dt><dt><font face="helvetica, arial"><a href="pexpect.html#TIMEOUT">TIMEOUT</a>
</font></dt></dl>
</dd>
</dl>
</dd>
</dl>
<p>
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#ffc8d8">
<td colspan=3 valign=bottom> <br>
<font color="#000000" face="helvetica, arial"><a name="EOF">class <strong>EOF</strong></a>(<a href="pexpect.html#ExceptionPexpect">ExceptionPexpect</a>)</font></td></tr>
<tr bgcolor="#ffc8d8"><td rowspan=2><tt> </tt></td>
<td colspan=2><tt>Raised when <a href="#EOF">EOF</a> is read from a child.<br> </tt></td></tr>
<tr><td> </td>
<td width="100%"><dl><dt>Method resolution order:</dt>
<dd><a href="pexpect.html#EOF">EOF</a></dd>
<dd><a href="pexpect.html#ExceptionPexpect">ExceptionPexpect</a></dd>
<dd><a href="exceptions.html#Exception">exceptions.Exception</a></dd>
</dl>
<hr>
Methods inherited from <a href="pexpect.html#ExceptionPexpect">ExceptionPexpect</a>:<br>
<dl><dt><a name="EOF-__init__"><strong>__init__</strong></a>(self, value)</dt></dl>
<dl><dt><a name="EOF-__str__"><strong>__str__</strong></a>(self)</dt></dl>
<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 the caller.<br>
In other words, the stack trace inside the Pexpect module is not included.</tt></dd></dl>
<hr>
Methods inherited from <a href="exceptions.html#Exception">exceptions.Exception</a>:<br>
<dl><dt><a name="EOF-__getitem__"><strong>__getitem__</strong></a>(...)</dt></dl>
</td></tr></table> <p>
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#ffc8d8">
<td colspan=3 valign=bottom> <br>
<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>
<tr bgcolor="#ffc8d8"><td rowspan=2><tt> </tt></td>
<td colspan=2><tt>Base class for all exceptions raised by this module.<br> </tt></td></tr>
<tr><td> </td>
<td width="100%">Methods defined here:<br>
<dl><dt><a name="ExceptionPexpect-__init__"><strong>__init__</strong></a>(self, value)</dt></dl>
<dl><dt><a name="ExceptionPexpect-__str__"><strong>__str__</strong></a>(self)</dt></dl>
<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 the caller.<br>
In other words, the stack trace inside the Pexpect module is not included.</tt></dd></dl>
<hr>
Methods inherited from <a href="exceptions.html#Exception">exceptions.Exception</a>:<br>
<dl><dt><a name="ExceptionPexpect-__getitem__"><strong>__getitem__</strong></a>(...)</dt></dl>
</td></tr></table> <p>
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#ffc8d8">
<td colspan=3 valign=bottom> <br>
<font color="#000000" face="helvetica, arial"><a name="TIMEOUT">class <strong>TIMEOUT</strong></a>(<a href="pexpect.html#ExceptionPexpect">ExceptionPexpect</a>)</font></td></tr>
<tr bgcolor="#ffc8d8"><td rowspan=2><tt> </tt></td>
<td colspan=2><tt>Raised when a read time exceeds the timeout.<br> </tt></td></tr>
<tr><td> </td>
<td width="100%"><dl><dt>Method resolution order:</dt>
<dd><a href="pexpect.html#TIMEOUT">TIMEOUT</a></dd>
<dd><a href="pexpect.html#ExceptionPexpect">ExceptionPexpect</a></dd>
<dd><a href="exceptions.html#Exception">exceptions.Exception</a></dd>
</dl>
<hr>
Methods inherited from <a href="pexpect.html#ExceptionPexpect">ExceptionPexpect</a>:<br>
<dl><dt><a name="TIMEOUT-__init__"><strong>__init__</strong></a>(self, value)</dt></dl>
<dl><dt><a name="TIMEOUT-__str__"><strong>__str__</strong></a>(self)</dt></dl>
<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 the caller.<br>
In other words, the stack trace inside the Pexpect module is not included.</tt></dd></dl>
<hr>
Methods inherited from <a href="exceptions.html#Exception">exceptions.Exception</a>:<br>
<dl><dt><a name="TIMEOUT-__getitem__"><strong>__getitem__</strong></a>(...)</dt></dl>
</td></tr></table> <p>
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#ffc8d8">
<td colspan=3 valign=bottom> <br>
<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>
<tr bgcolor="#ffc8d8"><td rowspan=2><tt> </tt></td>
<td colspan=2><tt>This is the main class interface for Pexpect.<br>
Use this class to start and control child applications.<br> </tt></td></tr>
<tr><td> </td>
<td width="100%">Methods defined here:<br>
<dl><dt><a name="spawn-__del__"><strong>__del__</strong></a>(self)</dt><dd><tt>This makes sure that no system resources are left open.<br>
Python only garbage collects Python objects. OS file descriptors<br>
are not Python objects, so they must be handled explicitly.<br>
If the child file descriptor was opened outside of this class<br>
(passed to the constructor) then this does not close it.</tt></dd></dl>
<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>, env<font color="#909090">=None</font>)</dt><dd><tt>This is the constructor. The command parameter may be a string<br>
that includes a command and any arguments to the command. For example:<br>
p = pexpect.<a href="#spawn">spawn</a> ('/usr/bin/ftp')<br>
p = pexpect.<a href="#spawn">spawn</a> ('/usr/bin/ssh user@example.com')<br>
p = pexpect.<a href="#spawn">spawn</a> ('ls -latr /tmp')<br>
You may also construct it with a list of arguments like so:<br>
p = pexpect.<a href="#spawn">spawn</a> ('/usr/bin/ftp', [])<br>
p = pexpect.<a href="#spawn">spawn</a> ('/usr/bin/ssh', ['user@example.com'])<br>
p = pexpect.<a href="#spawn">spawn</a> ('ls', ['-latr', '/tmp'])<br>
After this the child application will be created and<br>
will be ready to talk to. For normal use, see <a href="#spawn-expect">expect</a>() and <br>
<a href="#spawn-send">send</a>() and <a href="#spawn-sendline">sendline</a>().<br>
<br>
The maxread attribute sets the read buffer size.<br>
This is maximum number of bytes that Pexpect will try to read<br>
from a TTY at one time.<br>
Seeting the maxread size to 1 will turn off buffering.<br>
Setting the maxread value higher may help performance in cases<br>
where large amounts of output are read back from the child.<br>
This feature is useful in conjunction with searchwindowsize.<br>
<br>
The searchwindowsize attribute sets the how far back in<br>
the incomming seach buffer Pexpect will search for pattern matches.<br>
Every time Pexpect reads some data from the child it will append the data to<br>
the incomming buffer. The default is to search from the beginning of the<br>
imcomming buffer each time new data is read from the child.<br>
But this is very inefficient if you are running a command that<br>
generates a large amount of data where you want to match<br>
The searchwindowsize does not effect the size of the incomming data buffer.<br>
You will still have access to the full buffer after <a href="#spawn-expect">expect</a>() returns.<br>
<br>
The logfile member turns on or off logging.<br>
All input and output will be copied to the given file <a href="__builtin__.html#object">object</a>.<br>
Set logfile to None to stop logging. This is the default.<br>
Set logfile to sys.stdout to echo everything to standard output.<br>
The logfile is flushed after each write.<br>
Example 1:<br>
child = pexpect.<a href="#spawn">spawn</a>('some_command')<br>
fout = file('mylog.txt','w')<br>
child.logfile = fout<br>
Example 2:<br>
child = pexpect.<a href="#spawn">spawn</a>('some_command')<br>
child.logfile = sys.stdout<br>
<br>
The delaybeforesend helps overcome a weird behavior that many users were experiencing.<br>
The typical problem was that a user would <a href="#spawn-expect">expect</a>() a "Password:" prompt and<br>
then immediately call <a href="#spawn-sendline">sendline</a>() to send the password. The user would then<br>
see that their password was echoed back to them. Passwords don't<br>
normally echo. The problem is caused by the fact that most applications<br>
print out the "Password" prompt and then turn off stdin echo, but if you<br>
send your password before the application turned off echo, then you get<br>
your password echoed. Normally this wouldn't be a problem when interacting<br>
with a human at a real heyboard. If you introduce a slight delay just before <br>
writing then this seems to clear up the problem. This was such a common problem <br>
for many users that I decided that the default pexpect behavior<br>
should be to sleep just before writing to the child application.<br>
1/10th of a second (100 ms) seems to be enough to clear up the problem.<br>
You can set delaybeforesend to 0 to return to the old behavior.<br>
<br>
Note that <a href="#spawn">spawn</a> is clever about finding commands on your path.<br>
It uses the same logic that "which" uses to find executables.<br>
<br>
If you wish to get the exit status of the child you must call<br>
the <a href="#spawn-close">close</a>() method. The exit or signal status of the child will be<br>
stored in self.<strong>exitstatus</strong> or self.<strong>signalstatus</strong>.<br>
If the child exited normally then exitstatus will store the exit return code and<br>
signalstatus will be None.<br>
If the child was terminated abnormally with a signal then signalstatus will store<br>
the signal value and exitstatus will be None.<br>
If you need more detail you can also read the self.<strong>status</strong> member which stores<br>
the status returned by os.waitpid. You can interpret this using<br>
os.WIFEXITED/os.WEXITSTATUS or os.WIFSIGNALED/os.TERMSIG.</tt></dd></dl>
<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>
<dl><dt><a name="spawn-__str__"><strong>__str__</strong></a>(self)</dt><dd><tt>This returns the current state of the pexpect <a href="__builtin__.html#object">object</a> as a string.</tt></dd></dl>
<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.<br>
Note that calling <a href="#spawn-close">close</a>() more than once is valid.<br>
This emulates standard Python behavior with files.<br>
Set force to True if you want to make sure that the child is terminated<br>
(SIGKILL is sent if the child ignores SIGHUP and SIGINT).</tt></dd></dl>
<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>
Patterns must be a StringType, <a href="#EOF">EOF</a>, <a href="#TIMEOUT">TIMEOUT</a>, SRE_Pattern, or <br>
a list of those. Patterns may also be None which results in<br>
an empty list.<br>
<br>
This is used by <a href="#spawn-expect">expect</a>() when calling <a href="#spawn-expect_list">expect_list</a>().<br>
Thus <a href="#spawn-expect">expect</a>() is nothing more than::<br>
cpl = <a href="#spawn-compile_pattern_list">compile_pattern_list</a>(pl)<br>
return <a href="#spawn-expect_list">expect_list</a>(clp, timeout)<br>
<br>
If you are using <a href="#spawn-expect">expect</a>() within a loop it may be more<br>
efficient to compile the patterns first and then call <a href="#spawn-expect_list">expect_list</a>().<br>
This avoid calls in a loop to <a href="#spawn-compile_pattern_list">compile_pattern_list</a>():<br>
cpl = <a href="#spawn-compile_pattern_list">compile_pattern_list</a>(my_pattern)<br>
while some_condition:<br>
...<br>
i = <a href="#spawn-expect_list">expect_list</a>(clp, timeout)<br>
...</tt></dd></dl>
<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>
<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.<br>
The pattern is overloaded and may take several types including a list.<br>
The pattern can be a StringType, <a href="#EOF">EOF</a>, a compiled re, or a list of<br>
those types. Strings will be compiled to re types. This returns the<br>
index into the pattern list. If the pattern was not a list this<br>
returns index 0 on a successful match. This may raise exceptions for<br>
<a href="#EOF">EOF</a> or <a href="#TIMEOUT">TIMEOUT</a>. To avoid the <a href="#EOF">EOF</a> or <a href="#TIMEOUT">TIMEOUT</a> exceptions add<br>
<a href="#EOF">EOF</a> or <a href="#TIMEOUT">TIMEOUT</a> to the pattern list.<br>
<br>
After a match is found the instance attributes<br>
'before', 'after' and 'match' will be set.<br>
You can see all the data read before the match in 'before'.<br>
You can see the data that was matched in 'after'.<br>
The re.MatchObject used in the re match will be in 'match'.<br>
If an error occured then 'before' will be set to all the<br>
data read so far and 'after' and 'match' will be None.<br>
<br>
If timeout is -1 then timeout will be set to the self.<strong>timeout</strong> value.<br>
<br>
Note: A list entry may be <a href="#EOF">EOF</a> or <a href="#TIMEOUT">TIMEOUT</a> instead of a string.<br>
This will catch these exceptions and return the index<br>
of the list entry instead of raising the exception.<br>
The attribute 'after' will be set to the exception type.<br>
The attribute 'match' will be None.<br>
This allows you to write code like this:<br>
index = p.expect (['good', 'bad', pexpect.<a href="#EOF">EOF</a>, pexpect.<a href="#TIMEOUT">TIMEOUT</a>])<br>
if index == 0:<br>
do_something()<br>
elif index == 1:<br>
do_something_else()<br>
elif index == 2:<br>
do_some_other_thing()<br>
elif index == 3:<br>
do_something_completely_different()<br>
instead of code like this:<br>
try:<br>
index = p.expect (['good', 'bad'])<br>
if index == 0:<br>
do_something()<br>
elif index == 1:<br>
do_something_else()<br>
except <a href="#EOF">EOF</a>:<br>
do_some_other_thing()<br>
except <a href="#TIMEOUT">TIMEOUT</a>:<br>
do_something_completely_different()<br>
These two forms are equivalent. It all depends on what you want.<br>
You can also just expect the <a href="#EOF">EOF</a> if you are waiting for all output<br>
of a child to finish. For example:<br>
p = pexpect.<a href="#spawn">spawn</a>('/bin/ls')<br>
p.expect (pexpect.<a href="#EOF">EOF</a>)<br>
print p.before<br>
<br>
If you are trying to optimize for speed then see <a href="#spawn-expect_list">expect_list</a>().</tt></dd></dl>
<dl><dt><a name="spawn-expect_exact"><strong>expect_exact</strong></a>(self, pattern_list, timeout<font color="#909090">=-1</font>)</dt><dd><tt>This method is no longer supported or allowed.<br>
It was too hard to maintain and keep it up to date with expect_list.<br>
Few people used this method. Most people favored reliability over speed.<br>
The implementation is left in comments in case anyone needs to hack this<br>
feature back into their copy.<br>
If someone wants to diff this with expect_list and make them work<br>
nearly the same then I will consider adding this make in.</tt></dd></dl>
<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 <br>
the index into the pattern_list that matched the child output.<br>
The list may also contain <a href="#EOF">EOF</a> or <a href="#TIMEOUT">TIMEOUT</a> (which are not<br>
compiled regular expressions). This method is similar to<br>
the <a href="#spawn-expect">expect</a>() method except that <a href="#spawn-expect_list">expect_list</a>() does not<br>
recompile the pattern list on every call.<br>
This may help if you are trying to optimize for speed, otherwise<br>
just use the <a href="#spawn-expect">expect</a>() method. This is called by <a href="#spawn-expect">expect</a>().<br>
If timeout==-1 then the self.<strong>timeout</strong> value is used.<br>
If searchwindowsize==-1 then the self.<strong>searchwindowsize</strong> value is used.</tt></dd></dl>
<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>
<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 File-like <a href="__builtin__.html#object">object</a>.</tt></dd></dl>
<dl><dt><a name="spawn-getwinsize"><strong>getwinsize</strong></a>(self)</dt><dd><tt>This returns the terminal window size of the child tty.<br>
The return value is a tuple of (rows, cols).</tt></dd></dl>
<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<br>
(the human at the keyboard).<br>
Keystrokes are sent to the child process, and the stdout and stderr<br>
output of the child process is printed.<br>
This simply echos the child stdout and child stderr to the real<br>
stdout and it echos the real stdin to the child stdin.<br>
When the user types the escape_character this method will stop.<br>
The default for escape_character is ^]. This should not be confused<br>
with ASCII 27 -- the ESC character. ASCII 29 was chosen<br>
for historical merit because this is the character used<br>
by 'telnet' as the escape character. The escape_character will<br>
not be sent to the child process.<br>
<br>
You may pass in optional input and output filter functions.<br>
These functions should take a string and return a string.<br>
The output_filter will be passed all the output from the child process.<br>
The input_filter will be passed all the keyboard input from the user.<br>
The input_filter is run BEFORE the check for the escape_character.<br>
<br>
Note that if you change the window size of the parent<br>
the SIGWINCH signal will not be passed through to the child.<br>
If you want the child window size to change when the parent's<br>
window size changes then do something like the following example:<br>
import pexpect, struct, fcntl, termios, signal, sys<br>
def sigwinch_passthrough (sig, data):<br>
s = struct.pack("HHHH", 0, 0, 0, 0)<br>
a = struct.unpack('hhhh', fcntl.ioctl(sys.stdout.<a href="#spawn-fileno">fileno</a>(), termios.TIOCGWINSZ , s))<br>
global p<br>
p.<a href="#spawn-setwinsize">setwinsize</a>(a[0],a[1])<br>
p = pexpect.<a href="#spawn">spawn</a>('/bin/bash') # Note this is global and used in sigwinch_passthrough.<br>
signal.signal(signal.SIGWINCH, sigwinch_passthrough)<br>
p.<a href="#spawn-interact">interact</a>()</tt></dd></dl>
<dl><dt><a name="spawn-isalive"><strong>isalive</strong></a>(self)</dt><dd><tt>This tests if the child process is running or not.<br>
This is non-blocking. If the child was terminated then this<br>
will read the exitstatus or signalstatus of the child.<br>
This returns True if the child process appears to be running or False if not.<br>
It can take literally SECONDS for Solaris to return the right status.</tt></dd></dl>
<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 tty(-like) device, else False.</tt></dd></dl>
<dl><dt><a name="spawn-kill"><strong>kill</strong></a>(self, sig)</dt><dd><tt>This sends the given signal to the child application.<br>
In keeping with UNIX tradition it has a misleading name.<br>
It does not necessarily kill the child unless<br>
you send the right signal.</tt></dd></dl>
<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>
<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 <br>
(less if the read hits <a href="#EOF">EOF</a> before obtaining size bytes). <br>
If the size argument is negative or omitted, <br>
read all data until <a href="#EOF">EOF</a> is reached. <br>
The bytes are returned as a string <a href="__builtin__.html#object">object</a>. <br>
An empty string is returned when <a href="#EOF">EOF</a> is encountered immediately.</tt></dd></dl>
<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.<br>
It includes a timeout. If the read does not complete within the<br>
timeout period then a <a href="#TIMEOUT">TIMEOUT</a> exception is raised.<br>
If the end of file is read then an <a href="#EOF">EOF</a> exception will be raised.<br>
If a log file was set using <a href="#spawn-setlog">setlog</a>() then all data will<br>
also be written to the log file.<br>
<br>
If timeout==None then the read may block indefinitely.<br>
If timeout==-1 then the self.<strong>timeout</strong> value is used.<br>
If timeout==0 then the child is polled and <br>
if there was no data immediately ready then this will raise a <a href="#TIMEOUT">TIMEOUT</a> exception.<br>
<br>
The "timeout" refers only to the amount of time to read at least one character.<br>
This is not effected by the 'size' parameter, so if you call<br>
<a href="#spawn-read_nonblocking">read_nonblocking</a>(size=100, timeout=30) and only one character is<br>
available right away then one character will be returned immediately. <br>
It will not wait for 30 seconds for another 99 characters to come in.<br>
<br>
This is a wrapper around os.<a href="#spawn-read">read</a>().<br>
It uses select.select() to implement a timeout.</tt></dd></dl>
<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 in<br>
the string, but may be absent when a file ends with an incomplete line. <br>
Note: This <a href="#spawn-readline">readline</a>() looks for a \r\n pair even on UNIX because<br>
this is what the pseudo tty device returns. So contrary to what you<br>
may expect you will receive the newline as \r\n.<br>
An empty string is returned when <a href="#EOF">EOF</a> is hit immediately.<br>
Currently, the size agument is mostly ignored, so this behavior is not<br>
standard for a file-like <a href="__builtin__.html#object">object</a>. If size is 0 then an empty string<br>
is returned.</tt></dd></dl>
<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>
the lines thus read. The optional "sizehint" argument is ignored.</tt></dd></dl>
<dl><dt><a name="spawn-send"><strong>send</strong></a>(self, str)</dt><dd><tt>This sends a string to the child process.<br>
This returns the number of bytes written.<br>
If a log file was set then the data is also written to the log.</tt></dd></dl>
<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.<br>
This sends a character which causes the pending parent output<br>
buffer to be sent to the waiting child program without<br>
waiting for end-of-line. If it is the first character of the<br>
line, the <a href="#spawn-read">read</a>() in the user program returns 0, which<br>
signifies end-of-file. This means to work as expected <br>
a <a href="#spawn-sendeof">sendeof</a>() has to be called at the begining of a line. <br>
This method does not send a newline. It is the responsibility<br>
of the caller to ensure the eof is sent at the beginning of a line.</tt></dd></dl>
<dl><dt><a name="spawn-sendline"><strong>sendline</strong></a>(self, str<font color="#909090">=''</font>)</dt><dd><tt>This is like <a href="#spawn-send">send</a>(), but it adds a line feed (os.linesep).<br>
This returns the number of bytes written.</tt></dd></dl>
<dl><dt><a name="spawn-setecho"><strong>setecho</strong></a>(self, state)</dt><dd><tt>This sets the terminal echo mode on or off.<br>
Note that anything the child sent before the echo will be lost, so<br>
you should be sure that your input buffer is empty before you setecho.<br>
For example, the following will work as expected.<br>
p = pexpect.<a href="#spawn">spawn</a>('cat')<br>
p.sendline ('1234') # We will see this twice (once from tty echo and again from cat).<br>
p.expect (['1234'])<br>
p.expect (['1234'])<br>
p.<a href="#spawn-setecho">setecho</a>(False) # Turn off tty echo<br>
p.sendline ('abcd') # We will set this only once (echoed by cat).<br>
p.sendline ('wxyz') # We will set this only once (echoed by cat)<br>
p.expect (['abcd'])<br>
p.expect (['wxyz'])<br>
The following WILL NOT WORK because the lines sent before the setecho<br>
will be lost:<br>
p = pexpect.<a href="#spawn">spawn</a>('cat')<br>
p.sendline ('1234') # We will see this twice (once from tty echo and again from cat).<br>
p.<a href="#spawn-setecho">setecho</a>(False) # Turn off tty echo<br>
p.sendline ('abcd') # We will set this only once (echoed by cat).<br>
p.sendline ('wxyz') # We will set this only once (echoed by cat)<br>
p.expect (['1234'])<br>
p.expect (['1234'])<br>
p.expect (['abcd'])<br>
p.expect (['wxyz'])</tt></dd></dl>
<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>
<dl><dt><a name="spawn-setmaxread"><strong>setmaxread</strong></a>(self, maxread)</dt><dd><tt>This method is no longer supported or allowed.<br>
I don't like getters and setters without a good reason.</tt></dd></dl>
<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.<br>
This will cause a SIGWINCH signal to be sent to the child.<br>
This does not change the physical window size.<br>
It changes the size reported to TTY-aware applications like<br>
vi or curses -- applications that respond to the SIGWINCH signal.</tt></dd></dl>
<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.<br>
It starts nicely with SIGHUP and SIGINT. If "force" is True then<br>
moves onto SIGKILL.<br>
This returns True if the child was terminated.<br>
This returns False if the child could not be terminated.</tt></dd></dl>
<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.<br>
This will not read any data from the child, so this will block forever<br>
if the child has unread output and has terminated. In other words, the child<br>
may have printed output then called exit(); but, technically, the child is<br>
still alive until its output is read.</tt></dd></dl>
<dl><dt><a name="spawn-write"><strong>write</strong></a>(self, str)</dt><dd><tt>This is similar to <a href="#spawn-send">send</a>() except that there is no return value.</tt></dd></dl>
<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.<br>
The sequence can be any iterable <a href="__builtin__.html#object">object</a> producing strings, <br>
typically a list of strings. This does not add line separators<br>
There is no return value.</tt></dd></dl>
<hr>
Data and other attributes defined here:<br>
<dl><dt><strong>__dict__</strong> = <dictproxy object><dd><tt>dictionary for instance variables (if defined)</tt></dl>
<dl><dt><strong>__weakref__</strong> = <attribute '__weakref__' of 'spawn' objects><dd><tt>list of weak references to the <a href="__builtin__.html#object">object</a> (if defined)</tt></dl>
</td></tr></table></td></tr></table><p>
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#eeaa77">
<td colspan=3 valign=bottom> <br>
<font color="#ffffff" face="helvetica, arial"><big><strong>Functions</strong></big></font></td></tr>
<tr><td bgcolor="#eeaa77"><tt> </tt></td><td> </td>
<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>)</dt><dd><tt>This function runs the given command; waits for it to finish;<br>
then returns all output as a string. STDERR is included in output.<br>
If the full path to the command is not given then the path is searched.<br>
<br>
Note that lines are terminated by CR/LF (\r\n) combination<br>
even on UNIX-like systems because this is the standard for pseudo ttys.<br>
If you set withexitstatus to true, then run will return a tuple of<br>
(command_output, exitstatus). If withexitstatus is false then this<br>
returns just command_output.<br>
<br>
The <a href="#-run">run</a>() function can often be used instead of creating a <a href="#spawn">spawn</a> instance.<br>
For example, the following code uses <a href="#spawn">spawn</a>:<br>
from pexpect import *<br>
child = <a href="#spawn">spawn</a>('scp foo myname@host.example.com:.')<br>
child.expect ('(?i)password')<br>
child.sendline (mypassword)<br>
The previous code can be replace with the following, which you may<br>
or may not find simpler:<br>
from pexpect import *<br>
run ('scp foo myname@host.example.com:.', events={'(?i)password': mypassword})<br>
<br>
Examples:<br>
Start the apache daemon on the local machine:<br>
from pexpect import *<br>
run ("/usr/local/apache/bin/apachectl start")<br>
Check in a file using SVN:<br>
from pexpect import *<br>
run ("svn ci -m 'automatic commit' my_file.py")<br>
Run a command and capture exit status:<br>
from pexpect import *<br>
(command_output, exitstatus) = run ('ls -l /bin', withexitstatus=1)<br>
<br>
Tricky Examples: <br>
The following will run SSH and execute 'ls -l' on the remote machine.<br>
The password 'secret' will be sent if the '(?i)password' pattern is ever seen.<br>
run ("ssh username@machine.example.com 'ls -l'", events={'(?i)password':'secret<br>
'})<br>
<br>
This will start mencoder to rip a video from DVD. This will also display<br>
progress ticks every 5 seconds as it runs.<br>
from pexpect import *<br>
def print_ticks(d):<br>
print d['event_count'],<br>
run ("mencoder dvd://1 -o video.avi -oac copy -ovc copy", events={<a href="#TIMEOUT">TIMEOUT</a>:print_ticks}, timeout=5)<br>
<br>
The 'events' argument should be a dictionary of patterns and responses.<br>
Whenever one of the patterns is seen in the command out<br>
<a href="#-run">run</a>() will send the associated response string. Note that you should<br>
put newlines in your string if Enter is necessary.<br>
The responses may also contain callback functions.<br>
Any callback is function that takes a dictionary as an argument.<br>
The dictionary contains all the locals from the <a href="#-run">run</a>() function, so<br>
you can access the child <a href="#spawn">spawn</a> <a href="__builtin__.html#object">object</a> or any other variable defined<br>
in <a href="#-run">run</a>() (event_count, child, and extra_args are the most useful).<br>
A callback may return True to stop the current run process otherwise<br>
<a href="#-run">run</a>() continues until the next event.<br>
A callback may also return a string which will be sent to the child.<br>
'extra_args' is not used by directly <a href="#-run">run</a>(). It provides a way to pass data to<br>
a callback function through <a href="#-run">run</a>() through the locals dictionary passed to a callback.</tt></dd></dl>
<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.<br>
It splits arguments on spaces, but handles<br>
embedded quotes, doublequotes, and escaped characters.<br>
It's impossible to do this with a regular expression, so<br>
I wrote a little state machine to parse the command line.</tt></dd></dl>
<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>
then checks if it is executable.<br>
This returns the full path to the filename if found and executable.<br>
Otherwise this returns None.</tt></dd></dl>
</td></tr></table><p>
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#55aa55">
<td colspan=3 valign=bottom> <br>
<font color="#ffffff" face="helvetica, arial"><big><strong>Data</strong></big></font></td></tr>
<tr><td bgcolor="#55aa55"><tt> </tt></td><td> </td>
<td width="100%"><strong>__all__</strong> = ['ExceptionPexpect', 'EOF', 'TIMEOUT', 'spawn', 'run', 'which', 'split_command_line', '__version__', '__revision__']<br>
<strong>__revision__</strong> = '$Revision: 395 $'<br>
<strong>__version__</strong> = '2.1'</td></tr></table>
</body></html>
|