1 """Pexpect is a Python module for spawning child applications and controlling
2 them automatically. Pexpect can be used for automating interactive applications
3 such as ssh, ftp, passwd, telnet, etc. It can be used to a automate setup
4 scripts for duplicating software package installations on different servers. It
5 can be used for automated software testing. Pexpect is in the spirit of Don
6 Libes' Expect, but Pexpect is pure Python. Other Expect-like modules for Python
7 require TCL and Expect or require C extensions to be compiled. Pexpect does not
8 use C, Expect, or TCL extensions. It should work on any platform that supports
9 the standard Python pty module. The Pexpect interface focuses on ease of use so
10 that simple tasks are easy.
12 There are two main interfaces to Pexpect -- the function, run() and the class,
13 spawn. You can call the run() function to execute a command and return the
14 output. This is a handy replacement for os.system().
19 The more powerful interface is the spawn class. You can use this to spawn an
20 external child command and then interact with the child by sending lines and
24 child = pexpect.spawn('scp foo myname@host.example.com:.')
25 child.expect ('Password:')
26 child.sendline (mypassword)
28 This works even for commands that ask for passwords or other input outside of
29 the normal stdio streams.
32 Noah Spurrier, Richard Holden, Marco Molteni, Kimberley Burchett, Robert Stone,
33 Hartmut Goebel, Chad Schroeder, Erick Tryzelaar, Dave Kirby, Ids vander Molen,
34 George Todd, Noel Taylor, Nicolas D. Cesar, Alexander Gattin,
35 Geoffrey Marshall, Francisco Lourenco, Glen Mabey, Karthik Gurusamy,
37 (Let me know if I forgot anyone.)
39 Free, open source, and all that good stuff.
41 Permission is hereby granted, free of charge, to any person obtaining a copy of
42 this software and associated documentation files (the "Software"), to deal in
43 the Software without restriction, including without limitation the rights to
44 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
45 of the Software, and to permit persons to whom the Software is furnished to do
46 so, subject to the following conditions:
48 The above copyright notice and this permission notice shall be included in all
49 copies or substantial portions of the Software.
51 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
52 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
53 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
54 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
55 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
56 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
59 Pexpect Copyright (c) 2006 Noah Spurrier
60 http://pexpect.sourceforge.net/
63 $Date: 2006-05-31 20:07:18 -0700 (Wed, 31 May 2006) $
80 except ImportError, e:
81 raise ImportError (str(e) + """
82 A critical module was not found. Probably this operating system does not support it.
83 Pexpect is intended for UNIX-like operating systems.""")
86 __revision__ = '$Revision: 395 $'
87 __all__ = ['ExceptionPexpect', 'EOF', 'TIMEOUT', 'spawn', 'run', 'which', 'split_command_line',
88 '__version__', '__revision__']
90 # Exception classes used by this module.
91 class ExceptionPexpect(Exception):
92 """Base class for all exceptions raised by this module.
94 def __init__(self, value):
97 return str(self.value)
99 """This returns an abbreviated stack trace with lines that only concern the caller.
100 In other words, the stack trace inside the Pexpect module is not included.
102 tblist = traceback.extract_tb(sys.exc_info()[2])
103 tblist = filter(self.__filter_not_pexpect, tblist)
104 tblist = traceback.format_list(tblist)
105 return ''.join(tblist)
106 def __filter_not_pexpect(self, trace_list_item):
107 if trace_list_item[0].find('pexpect.py') == -1:
111 class EOF(ExceptionPexpect):
112 """Raised when EOF is read from a child.
114 class TIMEOUT(ExceptionPexpect):
115 """Raised when a read time exceeds the timeout.
117 ##class TIMEOUT_PATTERN(TIMEOUT):
118 ## """Raised when the pattern match time exceeds the timeout.
119 ## This is different than a read TIMEOUT because the child process may
120 ## give output, thus never give a TIMEOUT, but the output
121 ## may never match a pattern.
123 ##class MAXBUFFER(ExceptionPexpect):
124 ## """Raised when a scan buffer fills before matching an expected pattern."""
126 def run (command, timeout=-1, withexitstatus=False, events=None, extra_args=None, logfile=None):
127 """This function runs the given command; waits for it to finish;
128 then returns all output as a string. STDERR is included in output.
129 If the full path to the command is not given then the path is searched.
131 Note that lines are terminated by CR/LF (\\r\\n) combination
132 even on UNIX-like systems because this is the standard for pseudo ttys.
133 If you set withexitstatus to true, then run will return a tuple of
134 (command_output, exitstatus). If withexitstatus is false then this
135 returns just command_output.
137 The run() function can often be used instead of creating a spawn instance.
138 For example, the following code uses spawn:
139 from pexpect import *
140 child = spawn('scp foo myname@host.example.com:.')
141 child.expect ('(?i)password')
142 child.sendline (mypassword)
143 The previous code can be replace with the following, which you may
144 or may not find simpler:
145 from pexpect import *
146 run ('scp foo myname@host.example.com:.', events={'(?i)password': mypassword})
149 Start the apache daemon on the local machine:
150 from pexpect import *
151 run ("/usr/local/apache/bin/apachectl start")
152 Check in a file using SVN:
153 from pexpect import *
154 run ("svn ci -m 'automatic commit' my_file.py")
155 Run a command and capture exit status:
156 from pexpect import *
157 (command_output, exitstatus) = run ('ls -l /bin', withexitstatus=1)
160 The following will run SSH and execute 'ls -l' on the remote machine.
161 The password 'secret' will be sent if the '(?i)password' pattern is ever seen.
162 run ("ssh username@machine.example.com 'ls -l'", events={'(?i)password':'secret\n'})
164 This will start mencoder to rip a video from DVD. This will also display
165 progress ticks every 5 seconds as it runs.
166 from pexpect import *
168 print d['event_count'],
169 run ("mencoder dvd://1 -o video.avi -oac copy -ovc copy", events={TIMEOUT:print_ticks}, timeout=5)
171 The 'events' argument should be a dictionary of patterns and responses.
172 Whenever one of the patterns is seen in the command out
173 run() will send the associated response string. Note that you should
174 put newlines in your string if Enter is necessary.
175 The responses may also contain callback functions.
176 Any callback is function that takes a dictionary as an argument.
177 The dictionary contains all the locals from the run() function, so
178 you can access the child spawn object or any other variable defined
179 in run() (event_count, child, and extra_args are the most useful).
180 A callback may return True to stop the current run process otherwise
181 run() continues until the next event.
182 A callback may also return a string which will be sent to the child.
183 'extra_args' is not used by directly run(). It provides a way to pass data to
184 a callback function through run() through the locals dictionary passed to a callback.
187 child = spawn(command, maxread=2000, logfile=logfile)
189 child = spawn(command, timeout=timeout, maxread=2000, logfile=logfile)
190 if events is not None:
191 patterns = events.keys()
192 responses = events.values()
194 patterns=None # We assume that EOF or TIMEOUT will save us.
196 child_result_list = []
200 index = child.expect (patterns)
201 if type(child.after) is types.StringType:
202 child_result_list.append(child.before + child.after)
203 else: # child.after may have been a TIMEOUT or EOF, so don't cat those.
204 child_result_list.append(child.before)
205 if type(responses[index]) is types.StringType:
206 child.send(responses[index])
207 elif type(responses[index]) is types.FunctionType:
208 callback_result = responses[index](locals())
210 if type(callback_result) is types.StringType:
211 child.send(callback_result)
212 elif callback_result:
215 raise TypeError ('The callback must be a string or function type.')
216 event_count = event_count + 1
218 child_result_list.append(child.before)
221 child_result_list.append(child.before)
223 child_result = ''.join(child_result_list)
226 return (child_result, child.exitstatus)
230 class spawn (object):
231 """This is the main class interface for Pexpect.
232 Use this class to start and control child applications.
235 def __init__(self, command, args=[], timeout=30, maxread=2000, searchwindowsize=None, logfile=None, env=None):
236 """This is the constructor. The command parameter may be a string
237 that includes a command and any arguments to the command. For example:
238 p = pexpect.spawn ('/usr/bin/ftp')
239 p = pexpect.spawn ('/usr/bin/ssh user@example.com')
240 p = pexpect.spawn ('ls -latr /tmp')
241 You may also construct it with a list of arguments like so:
242 p = pexpect.spawn ('/usr/bin/ftp', [])
243 p = pexpect.spawn ('/usr/bin/ssh', ['user@example.com'])
244 p = pexpect.spawn ('ls', ['-latr', '/tmp'])
245 After this the child application will be created and
246 will be ready to talk to. For normal use, see expect() and
247 send() and sendline().
249 The maxread attribute sets the read buffer size.
250 This is maximum number of bytes that Pexpect will try to read
251 from a TTY at one time.
252 Seeting the maxread size to 1 will turn off buffering.
253 Setting the maxread value higher may help performance in cases
254 where large amounts of output are read back from the child.
255 This feature is useful in conjunction with searchwindowsize.
257 The searchwindowsize attribute sets the how far back in
258 the incomming seach buffer Pexpect will search for pattern matches.
259 Every time Pexpect reads some data from the child it will append the data to
260 the incomming buffer. The default is to search from the beginning of the
261 imcomming buffer each time new data is read from the child.
262 But this is very inefficient if you are running a command that
263 generates a large amount of data where you want to match
264 The searchwindowsize does not effect the size of the incomming data buffer.
265 You will still have access to the full buffer after expect() returns.
267 The logfile member turns on or off logging.
268 All input and output will be copied to the given file object.
269 Set logfile to None to stop logging. This is the default.
270 Set logfile to sys.stdout to echo everything to standard output.
271 The logfile is flushed after each write.
273 child = pexpect.spawn('some_command')
274 fout = file('mylog.txt','w')
277 child = pexpect.spawn('some_command')
278 child.logfile = sys.stdout
280 The delaybeforesend helps overcome a weird behavior that many users were experiencing.
281 The typical problem was that a user would expect() a "Password:" prompt and
282 then immediately call sendline() to send the password. The user would then
283 see that their password was echoed back to them. Passwords don't
284 normally echo. The problem is caused by the fact that most applications
285 print out the "Password" prompt and then turn off stdin echo, but if you
286 send your password before the application turned off echo, then you get
287 your password echoed. Normally this wouldn't be a problem when interacting
288 with a human at a real heyboard. If you introduce a slight delay just before
289 writing then this seems to clear up the problem. This was such a common problem
290 for many users that I decided that the default pexpect behavior
291 should be to sleep just before writing to the child application.
292 1/10th of a second (100 ms) seems to be enough to clear up the problem.
293 You can set delaybeforesend to 0 to return to the old behavior.
295 Note that spawn is clever about finding commands on your path.
296 It uses the same logic that "which" uses to find executables.
298 If you wish to get the exit status of the child you must call
299 the close() method. The exit or signal status of the child will be
300 stored in self.exitstatus or self.signalstatus.
301 If the child exited normally then exitstatus will store the exit return code and
302 signalstatus will be None.
303 If the child was terminated abnormally with a signal then signalstatus will store
304 the signal value and exitstatus will be None.
305 If you need more detail you can also read the self.status member which stores
306 the status returned by os.waitpid. You can interpret this using
307 os.WIFEXITED/os.WEXITSTATUS or os.WIFSIGNALED/os.TERMSIG.
309 self.STDIN_FILENO = pty.STDIN_FILENO
310 self.STDOUT_FILENO = pty.STDOUT_FILENO
311 self.STDERR_FILENO = pty.STDERR_FILENO
312 self.stdin = sys.stdin
313 self.stdout = sys.stdout
314 self.stderr = sys.stderr
317 self.ignorecase = False
321 self.match_index = None
322 self.terminated = True
323 self.exitstatus = None
324 self.signalstatus = None
325 self.status = None # status returned by os.waitpid
326 self.flag_eof = False
328 self.child_fd = -1 # initially closed
329 self.timeout = timeout
331 self.logfile = logfile
332 self.maxread = maxread # Max bytes to read at one time into buffer.
333 self.buffer = '' # This is the read buffer. See maxread.
334 self.searchwindowsize = searchwindowsize # Anything before searchwindowsize point is preserved, but not searched.
335 self.delaybeforesend = 0.1 # Sets sleep time used just before sending data to child.
336 self.delayafterclose = 0.1 # Sets delay in close() method to allow kernel time to update process status.
337 self.delayafterterminate = 0.1 # Sets delay in terminate() method to allow kernel time to update process status.
338 self.softspace = False # File-like object.
339 self.name = '<' + repr(self) + '>' # File-like object.
340 self.encoding = None # File-like object.
341 self.closed = True # File-like object.
343 self.__irix_hack = sys.platform.lower().find('irix') >= 0 # This flags if we are running on irix
344 self.use_native_pty_fork = not (sys.platform.lower().find('solaris') >= 0) # Solaris uses internal __fork_pty(). All other use pty.fork().
346 # allow dummy instances for subclasses that may not use command or args.
350 self.name = '<pexpect factory incomplete>'
353 # If command is an int type then it may represent a file descriptor.
354 if type(command) == type(0):
355 raise ExceptionPexpect ('Command is an int type. If this is a file descriptor then maybe you want to use fdpexpect.fdspawn which takes an existing file descriptor instead of a command string.')
357 if type (args) != type([]):
358 raise TypeError ('The argument, args, must be a list.')
361 self.args = split_command_line(command)
362 self.command = self.args[0]
364 self.args = args[:] # work with a copy
365 self.args.insert (0, command)
366 self.command = command
368 command_with_path = which(self.command)
369 if command_with_path is None:
370 raise ExceptionPexpect ('The command was not found or was not executable: %s.' % self.command)
371 self.command = command_with_path
372 self.args[0] = self.command
374 self.name = '<' + ' '.join (self.args) + '>'
378 """This makes sure that no system resources are left open.
379 Python only garbage collects Python objects. OS file descriptors
380 are not Python objects, so they must be handled explicitly.
381 If the child file descriptor was opened outside of this class
382 (passed to the constructor) then this does not close it.
388 """This returns the current state of the pexpect object as a string.
392 s.append('version: ' + __version__ + ' (' + __revision__ + ')')
393 s.append('command: ' + str(self.command))
394 s.append('args: ' + str(self.args))
395 if self.patterns is None:
396 s.append('patterns: None')
398 s.append('patterns:')
399 for p in self.patterns:
400 if type(p) is type(re.compile('')):
401 s.append(' ' + str(p.pattern))
403 s.append(' ' + str(p))
404 s.append('buffer (last 100 chars): ' + str(self.buffer)[-100:])
405 s.append('before (last 100 chars): ' + str(self.before)[-100:])
406 s.append('after: ' + str(self.after))
407 s.append('match: ' + str(self.match))
408 s.append('match_index: ' + str(self.match_index))
409 s.append('exitstatus: ' + str(self.exitstatus))
410 s.append('flag_eof: ' + str(self.flag_eof))
411 s.append('pid: ' + str(self.pid))
412 s.append('child_fd: ' + str(self.child_fd))
413 s.append('closed: ' + str(self.closed))
414 s.append('timeout: ' + str(self.timeout))
415 s.append('delimiter: ' + str(self.delimiter))
416 s.append('logfile: ' + str(self.logfile))
417 s.append('maxread: ' + str(self.maxread))
418 s.append('ignorecase: ' + str(self.ignorecase))
419 s.append('searchwindowsize: ' + str(self.searchwindowsize))
420 s.append('delaybeforesend: ' + str(self.delaybeforesend))
421 s.append('delayafterclose: ' + str(self.delayafterclose))
422 s.append('delayafterterminate: ' + str(self.delayafterterminate))
426 """This starts the given command in a child process.
427 This does all the fork/exec type of stuff for a pty.
428 This is called by __init__.
430 # The pid and child_fd of this object get set by this method.
431 # Note that it is difficult for this method to fail.
432 # You cannot detect if the child process cannot start.
433 # So the only way you can tell if the child process started
434 # or not is to try to read from the file descriptor. If you get
435 # EOF immediately then it means that the child is already dead.
436 # That may not necessarily be bad because you may haved spawned a child
437 # that performs some task; creates no stdout output; and then dies.
439 assert self.pid is None, 'The pid member should be None.'
440 assert self.command is not None, 'The command member should not be None.'
442 if self.use_native_pty_fork:
444 self.pid, self.child_fd = pty.fork()
446 raise ExceptionPexpect('Error! pty.fork() failed: ' + str(e))
447 else: # Use internal __fork_pty
448 self.pid, self.child_fd = self.__fork_pty()
450 if self.pid == 0: # Child
452 self.child_fd = sys.stdout.fileno() # used by setwinsize()
453 self.setwinsize(24, 80)
455 # Some platforms do not like setwinsize (Cygwin).
456 # This will cause problem when running applications that
457 # are very picky about window size.
458 # This is a serious limitation, but not a show stopper.
460 # Do not allow child to inherit open file descriptors from parent.
461 max_fd = resource.getrlimit(resource.RLIMIT_NOFILE)[0]
462 for i in range (3, max_fd):
468 # I don't know why this works, but ignoring SIGHUP fixes a
469 # problem when trying to start a Java daemon with sudo
470 # (specifically, Tomcat).
471 signal.signal(signal.SIGHUP, signal.SIG_IGN)
474 os.execv(self.command, self.args)
476 os.execvpe(self.command, self.args, self.env)
479 self.terminated = False
482 def __fork_pty(self):
483 """This implements a substitute for the forkpty system call.
484 This should be more portable than the pty.fork() function.
485 Specifically, this should work on Solaris.
487 Modified 10.06.05 by Geoff Marshall:
488 Implemented __fork_pty() method to resolve the issue with Python's
489 pty.fork() not supporting Solaris, particularly ssh.
490 Based on patch to posixmodule.c authored by Noah Spurrier:
491 http://mail.python.org/pipermail/python-dev/2003-May/035281.html
493 parent_fd, child_fd = os.openpty()
494 if parent_fd < 0 or child_fd < 0:
495 raise ExceptionPexpect, "Error! Could not open pty with os.openpty()."
499 raise ExceptionPexpect, "Error! Failed os.fork()."
503 self.__pty_make_controlling_tty(child_fd)
515 return pid, parent_fd
517 def __pty_make_controlling_tty(self, tty_fd):
518 """This makes the pseudo-terminal the controlling tty.
519 This should be more portable than the pty.fork() function.
520 Specifically, this should work on Solaris.
522 child_name = os.ttyname(tty_fd)
524 # Disconnect from controlling tty if still connected.
525 fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY);
531 # Verify we are disconnected from controlling tty
533 fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY);
536 raise ExceptionPexpect, "Error! We are not disconnected from a controlling tty."
538 # Good! We are disconnected from a controlling tty.
541 # Verify we can open child pty.
542 fd = os.open(child_name, os.O_RDWR);
544 raise ExceptionPexpect, "Error! Could not open child pty, " + child_name
548 # Verify we now have a controlling tty.
549 fd = os.open("/dev/tty", os.O_WRONLY)
551 raise ExceptionPexpect, "Error! Could not open controlling tty, /dev/tty"
555 def fileno (self): # File-like object.
556 """This returns the file descriptor of the pty for the child.
560 def close (self, force=True): # File-like object.
561 """This closes the connection with the child application.
562 Note that calling close() more than once is valid.
563 This emulates standard Python behavior with files.
564 Set force to True if you want to make sure that the child is terminated
565 (SIGKILL is sent if the child ignores SIGHUP and SIGINT).
569 os.close (self.child_fd)
572 time.sleep(self.delayafterclose) # Give kernel time to update process status.
574 if not self.terminate(force):
575 raise ExceptionPexpect ('close() could not terminate the child using terminate()')
577 def flush (self): # File-like object.
578 """This does nothing. It is here to support the interface for a File-like object.
582 def isatty (self): # File-like object.
583 """This returns True if the file descriptor is open and connected to a tty(-like) device, else False.
585 return os.isatty(self.child_fd)
587 def setecho (self, state):
588 """This sets the terminal echo mode on or off.
589 Note that anything the child sent before the echo will be lost, so
590 you should be sure that your input buffer is empty before you setecho.
591 For example, the following will work as expected.
592 p = pexpect.spawn('cat')
593 p.sendline ('1234') # We will see this twice (once from tty echo and again from cat).
596 p.setecho(False) # Turn off tty echo
597 p.sendline ('abcd') # We will set this only once (echoed by cat).
598 p.sendline ('wxyz') # We will set this only once (echoed by cat)
601 The following WILL NOT WORK because the lines sent before the setecho
603 p = pexpect.spawn('cat')
604 p.sendline ('1234') # We will see this twice (once from tty echo and again from cat).
605 p.setecho(False) # Turn off tty echo
606 p.sendline ('abcd') # We will set this only once (echoed by cat).
607 p.sendline ('wxyz') # We will set this only once (echoed by cat)
614 new = termios.tcgetattr(self.child_fd)
616 new[3] = new[3] | termios.ECHO
618 new[3] = new[3] & ~termios.ECHO
619 # I tried TCSADRAIN and TCSAFLUSH, but these were inconsistent
620 # and blocked on some platforms. TCSADRAIN is probably ideal if it worked.
621 termios.tcsetattr(self.child_fd, termios.TCSANOW, new)
623 def read_nonblocking (self, size = 1, timeout = -1):
624 """This reads at most size characters from the child application.
625 It includes a timeout. If the read does not complete within the
626 timeout period then a TIMEOUT exception is raised.
627 If the end of file is read then an EOF exception will be raised.
628 If a log file was set using setlog() then all data will
629 also be written to the log file.
631 If timeout==None then the read may block indefinitely.
632 If timeout==-1 then the self.timeout value is used.
633 If timeout==0 then the child is polled and
634 if there was no data immediately ready then this will raise a TIMEOUT exception.
636 The "timeout" refers only to the amount of time to read at least one character.
637 This is not effected by the 'size' parameter, so if you call
638 read_nonblocking(size=100, timeout=30) and only one character is
639 available right away then one character will be returned immediately.
640 It will not wait for 30 seconds for another 99 characters to come in.
642 This is a wrapper around os.read().
643 It uses select.select() to implement a timeout.
646 raise ValueError ('I/O operation on closed file in read_nonblocking().')
649 timeout = self.timeout
651 # Note that some systems such as Solaris do not give an EOF when
652 # the child dies. In fact, you can still try to read
653 # from the child_fd -- it will block forever or until TIMEOUT.
654 # For this case, I test isalive() before doing any reading.
655 # If isalive() is false, then I pretend that this is the same as EOF.
656 if not self.isalive():
657 r,w,e = self.__select([self.child_fd], [], [], 0) # timeout of 0 means "poll"
660 raise EOF ('End Of File (EOF) in read_nonblocking(). Braindead platform.')
661 elif self.__irix_hack:
662 # This is a hack for Irix. It seems that Irix requires a long delay before checking isalive.
663 # This adds a 2 second delay, but only when the child is terminated.
664 r, w, e = self.__select([self.child_fd], [], [], 2)
665 if not r and not self.isalive():
667 raise EOF ('End Of File (EOF) in read_nonblocking(). Pokey platform.')
669 r,w,e = self.__select([self.child_fd], [], [], timeout)
672 if not self.isalive():
673 # Some platforms, such as Irix, will claim that their processes are alive;
674 # then timeout on the select; and then finally admit that they are not alive.
676 raise EOF ('End of File (EOF) in read_nonblocking(). Very pokey platform.')
678 raise TIMEOUT ('Timeout exceeded in read_nonblocking().')
680 if self.child_fd in r:
682 s = os.read(self.child_fd, size)
683 except OSError, e: # Linux does this
685 raise EOF ('End Of File (EOF) in read_nonblocking(). Exception style platform.')
686 if s == '': # BSD style
688 raise EOF ('End Of File (EOF) in read_nonblocking(). Empty string style platform.')
690 if self.logfile is not None:
691 self.logfile.write (s)
696 raise ExceptionPexpect ('Reached an unexpected state in read_nonblocking().')
698 def read (self, size = -1): # File-like object.
699 """This reads at most "size" bytes from the file
700 (less if the read hits EOF before obtaining size bytes).
701 If the size argument is negative or omitted,
702 read all data until EOF is reached.
703 The bytes are returned as a string object.
704 An empty string is returned when EOF is encountered immediately.
709 self.expect (self.delimiter) # delimiter default is EOF
712 # I could have done this more directly by not using expect(), but
713 # I deliberately decided to couple read() to expect() so that
714 # I would catch any bugs early and ensure consistant behavior.
715 # It's a little less efficient, but there is less for me to
716 # worry about if I have to later modify read() or expect().
717 # Note, it's OK if size==-1 in the regex. That just means it
718 # will never match anything in which case we stop only on EOF.
719 cre = re.compile('.{%d}' % size, re.DOTALL)
720 index = self.expect ([cre, self.delimiter]) # delimiter default is EOF
722 return self.after ### self.before should be ''. Should I assert this?
725 def readline (self, size = -1): # File-like object.
726 """This reads and returns one entire line. A trailing newline is kept in
727 the string, but may be absent when a file ends with an incomplete line.
728 Note: This readline() looks for a \\r\\n pair even on UNIX because
729 this is what the pseudo tty device returns. So contrary to what you
730 may expect you will receive the newline as \\r\\n.
731 An empty string is returned when EOF is hit immediately.
732 Currently, the size agument is mostly ignored, so this behavior is not
733 standard for a file-like object. If size is 0 then an empty string
738 index = self.expect (['\r\n', self.delimiter]) # delimiter default is EOF
740 return self.before + '\r\n'
744 def __iter__ (self): # File-like object.
745 """This is to support iterators over a file-like object.
749 def next (self): # File-like object.
750 """This is to support iterators over a file-like object.
752 result = self.readline()
757 def readlines (self, sizehint = -1): # File-like object.
758 """This reads until EOF using readline() and returns a list containing
759 the lines thus read. The optional "sizehint" argument is ignored.
763 line = self.readline()
769 def write(self, str): # File-like object.
770 """This is similar to send() except that there is no return value.
774 def writelines (self, sequence): # File-like object.
775 """This calls write() for each element in the sequence.
776 The sequence can be any iterable object producing strings,
777 typically a list of strings. This does not add line separators
778 There is no return value.
784 """This sends a string to the child process.
785 This returns the number of bytes written.
786 If a log file was set then the data is also written to the log.
788 time.sleep(self.delaybeforesend)
789 if self.logfile is not None:
790 self.logfile.write (str)
792 c = os.write(self.child_fd, str)
795 def sendline(self, str=''):
796 """This is like send(), but it adds a line feed (os.linesep).
797 This returns the number of bytes written.
800 n = n + self.send (os.linesep)
804 """This sends an EOF to the child.
805 This sends a character which causes the pending parent output
806 buffer to be sent to the waiting child program without
807 waiting for end-of-line. If it is the first character of the
808 line, the read() in the user program returns 0, which
809 signifies end-of-file. This means to work as expected
810 a sendeof() has to be called at the begining of a line.
811 This method does not send a newline. It is the responsibility
812 of the caller to ensure the eof is sent at the beginning of a line.
814 ### Hmmm... how do I send an EOF?
815 ###C if ((m = write(pty, *buf, p - *buf)) < 0)
816 ###C return (errno == EWOULDBLOCK) ? n : -1;
817 fd = sys.stdin.fileno()
818 old = termios.tcgetattr(fd) # remember current state
819 new = termios.tcgetattr(fd)
820 new[3] = new[3] | termios.ICANON # ICANON must be set to recognize EOF
821 try: # use try/finally to ensure state gets restored
822 termios.tcsetattr(fd, termios.TCSADRAIN, new)
823 if 'CEOF' in dir(termios):
824 os.write (self.child_fd, '%c' % termios.CEOF)
826 os.write (self.child_fd, '%c' % 4) # Silly platform does not define CEOF so assume CTRL-D
827 finally: # restore state
828 termios.tcsetattr(fd, termios.TCSADRAIN, old)
831 """This returns True if the EOF exception was ever raised.
835 def terminate(self, force=False):
836 """This forces a child process to terminate.
837 It starts nicely with SIGHUP and SIGINT. If "force" is True then
839 This returns True if the child was terminated.
840 This returns False if the child could not be terminated.
842 if not self.isalive():
844 self.kill(signal.SIGHUP)
845 time.sleep(self.delayafterterminate)
846 if not self.isalive():
848 self.kill(signal.SIGCONT)
849 time.sleep(self.delayafterterminate)
850 if not self.isalive():
852 self.kill(signal.SIGINT)
853 time.sleep(self.delayafterterminate)
854 if not self.isalive():
857 self.kill(signal.SIGKILL)
858 time.sleep(self.delayafterterminate)
859 if not self.isalive():
864 #raise ExceptionPexpect ('terminate() could not terminate child process. Try terminate(force=True)?')
867 """This waits until the child exits. This is a blocking call.
868 This will not read any data from the child, so this will block forever
869 if the child has unread output and has terminated. In other words, the child
870 may have printed output then called exit(); but, technically, the child is
871 still alive until its output is read.
874 pid, status = os.waitpid(self.pid, 0)
876 raise ExceptionPexpect ('Cannot wait for dead child process.')
877 self.exitstatus = os.WEXITSTATUS(status)
878 if os.WIFEXITED (status):
880 self.exitstatus = os.WEXITSTATUS(status)
881 self.signalstatus = None
882 self.terminated = True
883 elif os.WIFSIGNALED (status):
885 self.exitstatus = None
886 self.signalstatus = os.WTERMSIG(status)
887 self.terminated = True
888 elif os.WIFSTOPPED (status):
889 raise ExceptionPexpect ('Wait was called for a child process that is stopped. This is not supported. Is some other process attempting job control with our child pid?')
890 return self.exitstatus
893 """This tests if the child process is running or not.
894 This is non-blocking. If the child was terminated then this
895 will read the exitstatus or signalstatus of the child.
896 This returns True if the child process appears to be running or False if not.
897 It can take literally SECONDS for Solaris to return the right status.
903 # This is for Linux, which requires the blocking form of waitpid to get
904 # status of a defunct process. This is super-lame. The flag_eof would have
905 # been set in read_nonblocking(), so this should be safe.
908 waitpid_options = os.WNOHANG
911 pid, status = os.waitpid(self.pid, waitpid_options)
912 except OSError, e: # No child processes
913 if e[0] == errno.ECHILD:
914 raise ExceptionPexpect ('isalive() encountered condition where "terminated" is 0, but there was no child process. Did someone else call waitpid() on our process?')
918 # I have to do this twice for Solaris. I can't even believe that I figured this out...
919 # If waitpid() returns 0 it means that no child process wishes to
920 # report, and the value of status is undefined.
923 pid, status = os.waitpid(self.pid, waitpid_options) ### os.WNOHANG) # Solaris!
924 except OSError, e: # This should never happen...
925 if e[0] == errno.ECHILD:
926 raise ExceptionPexpect ('isalive() encountered condition that should never happen. There was no child process. Did someone else call waitpid() on our process?')
930 # If pid is still 0 after two calls to waitpid() then
931 # the process really is alive. This seems to work on all platforms, except
932 # for Irix which seems to require a blocking call on waitpid or select, so I let read_nonblocking
933 # take care of this situation (unfortunately, this requires waiting through the timeout).
940 if os.WIFEXITED (status):
942 self.exitstatus = os.WEXITSTATUS(status)
943 self.signalstatus = None
944 self.terminated = True
945 elif os.WIFSIGNALED (status):
947 self.exitstatus = None
948 self.signalstatus = os.WTERMSIG(status)
949 self.terminated = True
950 elif os.WIFSTOPPED (status):
951 raise ExceptionPexpect ('isalive() encountered condition where child process is stopped. This is not supported. Is some other process attempting job control with our child pid?')
955 """This sends the given signal to the child application.
956 In keeping with UNIX tradition it has a misleading name.
957 It does not necessarily kill the child unless
958 you send the right signal.
960 # Same as os.kill, but the pid is given for you.
962 os.kill(self.pid, sig)
964 def compile_pattern_list(self, patterns):
965 """This compiles a pattern-string or a list of pattern-strings.
966 Patterns must be a StringType, EOF, TIMEOUT, SRE_Pattern, or
967 a list of those. Patterns may also be None which results in
970 This is used by expect() when calling expect_list().
971 Thus expect() is nothing more than::
972 cpl = self.compile_pattern_list(pl)
973 return self.expect_list(clp, timeout)
975 If you are using expect() within a loop it may be more
976 efficient to compile the patterns first and then call expect_list().
977 This avoid calls in a loop to compile_pattern_list():
978 cpl = self.compile_pattern_list(my_pattern)
979 while some_condition:
981 i = self.expect_list(clp, timeout)
986 if type(patterns) is not types.ListType:
987 patterns = [patterns]
989 compile_flags = re.DOTALL # Allow dot to match \n
991 compile_flags = compile_flags | re.IGNORECASE
992 compiled_pattern_list = []
994 if type(p) is types.StringType:
995 compiled_pattern_list.append(re.compile(p, compile_flags))
997 compiled_pattern_list.append(EOF)
999 compiled_pattern_list.append(TIMEOUT)
1000 elif type(p) is type(re.compile('')):
1001 compiled_pattern_list.append(p)
1003 raise TypeError ('Argument must be one of StringType, EOF, TIMEOUT, SRE_Pattern, or a list of those type. %s' % str(type(p)))
1005 return compiled_pattern_list
1007 def expect(self, pattern, timeout = -1, searchwindowsize=None):
1009 """This seeks through the stream until a pattern is matched.
1010 The pattern is overloaded and may take several types including a list.
1011 The pattern can be a StringType, EOF, a compiled re, or a list of
1012 those types. Strings will be compiled to re types. This returns the
1013 index into the pattern list. If the pattern was not a list this
1014 returns index 0 on a successful match. This may raise exceptions for
1015 EOF or TIMEOUT. To avoid the EOF or TIMEOUT exceptions add
1016 EOF or TIMEOUT to the pattern list.
1018 After a match is found the instance attributes
1019 'before', 'after' and 'match' will be set.
1020 You can see all the data read before the match in 'before'.
1021 You can see the data that was matched in 'after'.
1022 The re.MatchObject used in the re match will be in 'match'.
1023 If an error occured then 'before' will be set to all the
1024 data read so far and 'after' and 'match' will be None.
1026 If timeout is -1 then timeout will be set to the self.timeout value.
1028 Note: A list entry may be EOF or TIMEOUT instead of a string.
1029 This will catch these exceptions and return the index
1030 of the list entry instead of raising the exception.
1031 The attribute 'after' will be set to the exception type.
1032 The attribute 'match' will be None.
1033 This allows you to write code like this:
1034 index = p.expect (['good', 'bad', pexpect.EOF, pexpect.TIMEOUT])
1040 do_some_other_thing()
1042 do_something_completely_different()
1043 instead of code like this:
1045 index = p.expect (['good', 'bad'])
1051 do_some_other_thing()
1053 do_something_completely_different()
1054 These two forms are equivalent. It all depends on what you want.
1055 You can also just expect the EOF if you are waiting for all output
1056 of a child to finish. For example:
1057 p = pexpect.spawn('/bin/ls')
1058 p.expect (pexpect.EOF)
1061 If you are trying to optimize for speed then see expect_list().
1063 compiled_pattern_list = self.compile_pattern_list(pattern)
1064 return self.expect_list(compiled_pattern_list, timeout, searchwindowsize)
1066 def expect_list(self, pattern_list, timeout = -1, searchwindowsize = -1):
1067 """This takes a list of compiled regular expressions and returns
1068 the index into the pattern_list that matched the child output.
1069 The list may also contain EOF or TIMEOUT (which are not
1070 compiled regular expressions). This method is similar to
1071 the expect() method except that expect_list() does not
1072 recompile the pattern list on every call.
1073 This may help if you are trying to optimize for speed, otherwise
1074 just use the expect() method. This is called by expect().
1075 If timeout==-1 then the self.timeout value is used.
1076 If searchwindowsize==-1 then the self.searchwindowsize value is used.
1079 self.patterns = pattern_list
1082 timeout = self.timeout
1083 if timeout is not None:
1084 end_time = time.time() + timeout
1085 if searchwindowsize == -1:
1086 searchwindowsize = self.searchwindowsize
1089 incoming = self.buffer
1090 while True: # Keep reading until exception or return.
1091 # Sequence through the list of patterns looking for a match.
1093 for cre in pattern_list:
1094 if cre is EOF or cre is TIMEOUT:
1095 continue # The patterns for PexpectExceptions are handled differently.
1096 if searchwindowsize is None: # search everything
1097 match = cre.search(incoming)
1099 startpos = max(0, len(incoming) - searchwindowsize)
1100 match = cre.search(incoming, startpos)
1103 if first_match > match.start() or first_match == -1:
1104 first_match = match.start()
1106 self.match_index = pattern_list.index(cre)
1107 if first_match > -1:
1108 self.buffer = incoming[self.match.end() : ]
1109 self.before = incoming[ : self.match.start()]
1110 self.after = incoming[self.match.start() : self.match.end()]
1111 return self.match_index
1112 # No match at this point
1113 if timeout < 0 and timeout is not None:
1114 raise TIMEOUT ('Timeout exceeded in expect_list().')
1115 # Still have time left, so read more data
1116 c = self.read_nonblocking (self.maxread, timeout)
1118 incoming = incoming + c
1119 if timeout is not None:
1120 timeout = end_time - time.time()
1123 self.before = incoming
1125 if EOF in pattern_list:
1127 self.match_index = pattern_list.index(EOF)
1128 return self.match_index
1131 self.match_index = None
1132 raise EOF (str(e) + '\n' + str(self))
1134 self.before = incoming
1135 self.after = TIMEOUT
1136 if TIMEOUT in pattern_list:
1137 self.match = TIMEOUT
1138 self.match_index = pattern_list.index(TIMEOUT)
1139 return self.match_index
1142 self.match_index = None
1143 raise TIMEOUT (str(e) + '\n' + str(self))
1145 self.before = incoming
1148 self.match_index = None
1151 def getwinsize(self):
1152 """This returns the terminal window size of the child tty.
1153 The return value is a tuple of (rows, cols).
1155 if 'TIOCGWINSZ' in dir(termios):
1156 TIOCGWINSZ = termios.TIOCGWINSZ
1158 TIOCGWINSZ = 1074295912L # assume if not defined
1159 s = struct.pack('HHHH', 0, 0, 0, 0)
1160 x = fcntl.ioctl(self.fileno(), TIOCGWINSZ, s)
1161 return struct.unpack('HHHH', x)[0:2]
1163 def setwinsize(self, r, c):
1164 """This sets the terminal window size of the child tty.
1165 This will cause a SIGWINCH signal to be sent to the child.
1166 This does not change the physical window size.
1167 It changes the size reported to TTY-aware applications like
1168 vi or curses -- applications that respond to the SIGWINCH signal.
1170 # Check for buggy platforms. Some Python versions on some platforms
1171 # (notably OSF1 Alpha and RedHat 7.1) truncate the value for
1172 # termios.TIOCSWINSZ. It is not clear why this happens.
1173 # These platforms don't seem to handle the signed int very well;
1174 # yet other platforms like OpenBSD have a large negative value for
1175 # TIOCSWINSZ and they don't have a truncate problem.
1176 # Newer versions of Linux have totally different values for TIOCSWINSZ.
1177 # Note that this fix is a hack.
1178 if 'TIOCSWINSZ' in dir(termios):
1179 TIOCSWINSZ = termios.TIOCSWINSZ
1181 TIOCSWINSZ = -2146929561
1182 if TIOCSWINSZ == 2148037735L: # L is not required in Python >= 2.2.
1183 TIOCSWINSZ = -2146929561 # Same bits, but with sign.
1184 # Note, assume ws_xpixel and ws_ypixel are zero.
1185 s = struct.pack('HHHH', r, c, 0, 0)
1186 fcntl.ioctl(self.fileno(), TIOCSWINSZ, s)
1188 def interact(self, escape_character = chr(29), input_filter = None, output_filter = None):
1189 """This gives control of the child process to the interactive user
1190 (the human at the keyboard).
1191 Keystrokes are sent to the child process, and the stdout and stderr
1192 output of the child process is printed.
1193 This simply echos the child stdout and child stderr to the real
1194 stdout and it echos the real stdin to the child stdin.
1195 When the user types the escape_character this method will stop.
1196 The default for escape_character is ^]. This should not be confused
1197 with ASCII 27 -- the ESC character. ASCII 29 was chosen
1198 for historical merit because this is the character used
1199 by 'telnet' as the escape character. The escape_character will
1200 not be sent to the child process.
1202 You may pass in optional input and output filter functions.
1203 These functions should take a string and return a string.
1204 The output_filter will be passed all the output from the child process.
1205 The input_filter will be passed all the keyboard input from the user.
1206 The input_filter is run BEFORE the check for the escape_character.
1208 Note that if you change the window size of the parent
1209 the SIGWINCH signal will not be passed through to the child.
1210 If you want the child window size to change when the parent's
1211 window size changes then do something like the following example:
1212 import pexpect, struct, fcntl, termios, signal, sys
1213 def sigwinch_passthrough (sig, data):
1214 s = struct.pack("HHHH", 0, 0, 0, 0)
1215 a = struct.unpack('hhhh', fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ , s))
1217 p.setwinsize(a[0],a[1])
1218 p = pexpect.spawn('/bin/bash') # Note this is global and used in sigwinch_passthrough.
1219 signal.signal(signal.SIGWINCH, sigwinch_passthrough)
1223 self.stdout.write (self.buffer)
1226 mode = tty.tcgetattr(self.STDIN_FILENO)
1227 tty.setraw(self.STDIN_FILENO)
1229 self.__interact_copy(escape_character, input_filter, output_filter)
1231 tty.tcsetattr(self.STDIN_FILENO, tty.TCSAFLUSH, mode)
1233 def __interact_writen(self, fd, data):
1234 """This is used by the interact() method.
1236 while data != '' and self.isalive():
1237 n = os.write(fd, data)
1239 def __interact_read(self, fd):
1240 """This is used by the interact() method.
1242 return os.read(fd, 1000)
1243 def __interact_copy(self, escape_character = None, input_filter = None, output_filter = None):
1244 """This is used by the interact() method.
1246 while self.isalive():
1247 r,w,e = self.__select([self.child_fd, self.STDIN_FILENO], [], [])
1248 if self.child_fd in r:
1249 data = self.__interact_read(self.child_fd)
1250 if output_filter: data = output_filter(data)
1251 if self.logfile is not None:
1252 self.logfile.write (data)
1253 self.logfile.flush()
1254 os.write(self.STDOUT_FILENO, data)
1255 if self.STDIN_FILENO in r:
1256 data = self.__interact_read(self.STDIN_FILENO)
1257 if input_filter: data = input_filter(data)
1258 i = data.rfind(escape_character)
1261 self.__interact_writen(self.child_fd, data)
1263 self.__interact_writen(self.child_fd, data)
1264 def __select (self, iwtd, owtd, ewtd, timeout=None):
1265 """This is a wrapper around select.select() that ignores signals.
1266 If select.select raises a select.error exception and errno is an EINTR error then
1267 it is ignored. Mainly this is used to ignore sigwinch (terminal resize).
1269 # if select() is interrupted by a signal (errno==EINTR) then
1270 # we loop back and enter the select() again.
1271 if timeout is not None:
1272 end_time = time.time() + timeout
1275 return select.select (iwtd, owtd, ewtd, timeout)
1276 except select.error, e:
1277 if e[0] == errno.EINTR:
1278 # if we loop back we have to subtract the amount of time we already waited.
1279 if timeout is not None:
1280 timeout = end_time - time.time()
1283 else: # something else caused the select.error, so this really is an exception
1286 ##############################################################################
1287 # The following methods are no longer supported or allowed..
1288 def setmaxread (self, maxread):
1289 """This method is no longer supported or allowed.
1290 I don't like getters and setters without a good reason.
1292 raise ExceptionPexpect ('This method is no longer supported or allowed. Just assign a value to the maxread member variable.')
1293 def expect_exact (self, pattern_list, timeout = -1):
1294 """This method is no longer supported or allowed.
1295 It was too hard to maintain and keep it up to date with expect_list.
1296 Few people used this method. Most people favored reliability over speed.
1297 The implementation is left in comments in case anyone needs to hack this
1298 feature back into their copy.
1299 If someone wants to diff this with expect_list and make them work
1300 nearly the same then I will consider adding this make in.
1302 raise ExceptionPexpect ('This method is no longer supported or allowed.')
1303 def setlog (self, fileobject):
1304 """This method is no longer supported or allowed.
1306 raise ExceptionPexpect ('This method is no longer supported or allowed. Just assign a value to the logfile member variable.')
1308 ##############################################################################
1309 # End of spawn class
1310 ##############################################################################
1312 def which (filename):
1313 """This takes a given filename; tries to find it in the environment path;
1314 then checks if it is executable.
1315 This returns the full path to the filename if found and executable.
1316 Otherwise this returns None.
1318 # Special case where filename already contains a path.
1319 if os.path.dirname(filename) != '':
1320 if os.access (filename, os.X_OK):
1323 if not os.environ.has_key('PATH') or os.environ['PATH'] == '':
1326 p = os.environ['PATH']
1328 # Oddly enough this was the one line that made Pexpect
1329 # incompatible with Python 1.5.2.
1330 #pathlist = p.split (os.pathsep)
1331 pathlist = string.split (p, os.pathsep)
1333 for path in pathlist:
1334 f = os.path.join(path, filename)
1335 if os.access(f, os.X_OK):
1339 def split_command_line(command_line):
1340 """This splits a command line into a list of arguments.
1341 It splits arguments on spaces, but handles
1342 embedded quotes, doublequotes, and escaped characters.
1343 It's impossible to do this with a regular expression, so
1344 I wrote a little state machine to parse the command line.
1349 # Constants to name the states we can be in.
1352 state_singlequote = 2
1353 state_doublequote = 3
1354 state_whitespace = 4 # The state of consuming whitespace between commands.
1357 for c in command_line:
1358 if state == state_basic or state == state_whitespace:
1359 if c == '\\': # Escape the next character
1361 elif c == r"'": # Handle single quote
1362 state = state_singlequote
1363 elif c == r'"': # Handle double quote
1364 state = state_doublequote
1366 # Add arg to arg_list if we aren't in the middle of whitespace.
1367 if state == state_whitespace:
1370 arg_list.append(arg)
1372 state = state_whitespace
1376 elif state == state_esc:
1379 elif state == state_singlequote:
1384 elif state == state_doublequote:
1391 arg_list.append(arg)