##// END OF EJS Templates
Remove string module use from external modules.
Thomas Kluyver -
Show More
@@ -1,275 +1,274 b''
1 1 # -*- coding: utf-8 -*-
2 2 """String interpolation for Python (by Ka-Ping Yee, 14 Feb 2000).
3 3
4 4 This module lets you quickly and conveniently interpolate values into
5 5 strings (in the flavour of Perl or Tcl, but with less extraneous
6 6 punctuation). You get a bit more power than in the other languages,
7 7 because this module allows subscripting, slicing, function calls,
8 8 attribute lookup, or arbitrary expressions. Variables and expressions
9 9 are evaluated in the namespace of the caller.
10 10
11 11 The itpl() function returns the result of interpolating a string, and
12 12 printpl() prints out an interpolated string. Here are some examples:
13 13
14 14 from Itpl import printpl
15 15 printpl("Here is a $string.")
16 16 printpl("Here is a $module.member.")
17 17 printpl("Here is an $object.member.")
18 18 printpl("Here is a $functioncall(with, arguments).")
19 19 printpl("Here is an ${arbitrary + expression}.")
20 20 printpl("Here is an $array[3] member.")
21 21 printpl("Here is a $dictionary['member'].")
22 22
23 23 The filter() function filters a file object so that output through it
24 24 is interpolated. This lets you produce the illusion that Python knows
25 25 how to do interpolation:
26 26
27 27 import Itpl
28 28 sys.stdout = Itpl.filter()
29 29 f = "fancy"
30 30 print "Is this not $f?"
31 31 print "Standard output has been replaced with a $sys.stdout object."
32 32 sys.stdout = Itpl.unfilter()
33 33 print "Okay, back $to $normal."
34 34
35 35 Under the hood, the Itpl class represents a string that knows how to
36 36 interpolate values. An instance of the class parses the string once
37 37 upon initialization; the evaluation and substitution can then be done
38 38 each time the instance is evaluated with str(instance). For example:
39 39
40 40 from Itpl import Itpl
41 41 s = Itpl("Here is $foo.")
42 42 foo = 5
43 43 print str(s)
44 44 foo = "bar"
45 45 print str(s)
46 46 """
47 47
48 48 #*****************************************************************************
49 49 #
50 50 # Copyright (c) 2001 Ka-Ping Yee <ping@lfw.org>
51 51 #
52 52 #
53 53 # Published under the terms of the MIT license, hereby reproduced:
54 54 #
55 55 # Permission is hereby granted, free of charge, to any person obtaining a copy
56 56 # of this software and associated documentation files (the "Software"), to
57 57 # deal in the Software without restriction, including without limitation the
58 58 # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
59 59 # sell copies of the Software, and to permit persons to whom the Software is
60 60 # furnished to do so, subject to the following conditions:
61 61 #
62 62 # The above copyright notice and this permission notice shall be included in
63 63 # all copies or substantial portions of the Software.
64 64 #
65 65 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
66 66 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
67 67 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
68 68 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
69 69 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
70 70 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
71 71 # IN THE SOFTWARE.
72 72 #
73 73 #*****************************************************************************
74 74
75 75 __author__ = 'Ka-Ping Yee <ping@lfw.org>'
76 76 __license__ = 'MIT'
77 77
78 import string
79 78 import sys
80 79 from tokenize import tokenprog
81 80
82 81 class ItplError(ValueError):
83 82 def __init__(self, text, pos):
84 83 self.text = text
85 84 self.pos = pos
86 85 def __str__(self):
87 86 return "unfinished expression in %s at char %d" % (
88 87 repr(self.text), self.pos)
89 88
90 89 def matchorfail(text, pos):
91 90 match = tokenprog.match(text, pos)
92 91 if match is None:
93 92 raise ItplError(text, pos)
94 93 return match, match.end()
95 94
96 95 class Itpl:
97 96 """Class representing a string with interpolation abilities.
98 97
99 98 Upon creation, an instance works out what parts of the format
100 99 string are literal and what parts need to be evaluated. The
101 100 evaluation and substitution happens in the namespace of the
102 101 caller when str(instance) is called."""
103 102
104 103 def __init__(self, format,codec='utf_8',encoding_errors='backslashreplace'):
105 104 """The single mandatory argument to this constructor is a format
106 105 string.
107 106
108 107 The format string is parsed according to the following rules:
109 108
110 109 1. A dollar sign and a name, possibly followed by any of:
111 110 - an open-paren, and anything up to the matching paren
112 111 - an open-bracket, and anything up to the matching bracket
113 112 - a period and a name
114 113 any number of times, is evaluated as a Python expression.
115 114
116 115 2. A dollar sign immediately followed by an open-brace, and
117 116 anything up to the matching close-brace, is evaluated as
118 117 a Python expression.
119 118
120 119 3. Outside of the expressions described in the above two rules,
121 120 two dollar signs in a row give you one literal dollar sign.
122 121
123 122 Optional arguments:
124 123
125 124 - codec('utf_8'): a string containing the name of a valid Python
126 125 codec.
127 126
128 127 - encoding_errors('backslashreplace'): a string with a valid error handling
129 128 policy. See the codecs module documentation for details.
130 129
131 130 These are used to encode the format string if a call to str() fails on
132 131 the expanded result."""
133 132
134 133 if not isinstance(format,basestring):
135 134 raise TypeError, "needs string initializer"
136 135 self.format = format
137 136 self.codec = codec
138 137 self.encoding_errors = encoding_errors
139 138
140 139 namechars = "abcdefghijklmnopqrstuvwxyz" \
141 140 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
142 141 chunks = []
143 142 pos = 0
144 143
145 144 while 1:
146 145 dollar = format.find("$", pos)
147 146 if dollar < 0: break
148 147 nextchar = format[dollar+1]
149 148
150 149 if nextchar == "{":
151 150 chunks.append((0, format[pos:dollar]))
152 151 pos, level = dollar+2, 1
153 152 while level:
154 153 match, pos = matchorfail(format, pos)
155 154 tstart, tend = match.regs[3]
156 155 token = format[tstart:tend]
157 156 if token == "{": level = level+1
158 157 elif token == "}": level = level-1
159 158 chunks.append((1, format[dollar+2:pos-1]))
160 159
161 160 elif nextchar in namechars:
162 161 chunks.append((0, format[pos:dollar]))
163 162 match, pos = matchorfail(format, dollar+1)
164 163 while pos < len(format):
165 164 if format[pos] == "." and \
166 165 pos+1 < len(format) and format[pos+1] in namechars:
167 166 match, pos = matchorfail(format, pos+1)
168 167 elif format[pos] in "([":
169 168 pos, level = pos+1, 1
170 169 while level:
171 170 match, pos = matchorfail(format, pos)
172 171 tstart, tend = match.regs[3]
173 172 token = format[tstart:tend]
174 173 if token[0] in "([": level = level+1
175 174 elif token[0] in ")]": level = level-1
176 175 else: break
177 176 chunks.append((1, format[dollar+1:pos]))
178 177
179 178 else:
180 179 chunks.append((0, format[pos:dollar+1]))
181 180 pos = dollar + 1 + (nextchar == "$")
182 181
183 182 if pos < len(format): chunks.append((0, format[pos:]))
184 183 self.chunks = chunks
185 184
186 185 def __repr__(self):
187 186 return "<Itpl %s >" % repr(self.format)
188 187
189 188 def _str(self,glob,loc):
190 189 """Evaluate to a string in the given globals/locals.
191 190
192 191 The final output is built by calling str(), but if this fails, the
193 192 result is encoded with the instance's codec and error handling policy,
194 193 via a call to out.encode(self.codec,self.encoding_errors)"""
195 194 result = []
196 195 app = result.append
197 196 for live, chunk in self.chunks:
198 197 if live: app(str(eval(chunk,glob,loc)))
199 198 else: app(chunk)
200 199 out = ''.join(result)
201 200 try:
202 201 return str(out)
203 202 except UnicodeError:
204 203 return out.encode(self.codec,self.encoding_errors)
205 204
206 205 def __str__(self):
207 206 """Evaluate and substitute the appropriate parts of the string."""
208 207
209 208 # We need to skip enough frames to get to the actual caller outside of
210 209 # Itpl.
211 210 frame = sys._getframe(1)
212 211 while frame.f_globals["__name__"] == __name__: frame = frame.f_back
213 212 loc, glob = frame.f_locals, frame.f_globals
214 213
215 214 return self._str(glob,loc)
216 215
217 216 class ItplNS(Itpl):
218 217 """Class representing a string with interpolation abilities.
219 218
220 219 This inherits from Itpl, but at creation time a namespace is provided
221 220 where the evaluation will occur. The interpolation becomes a bit more
222 221 efficient, as no traceback needs to be extracte. It also allows the
223 222 caller to supply a different namespace for the interpolation to occur than
224 223 its own."""
225 224
226 225 def __init__(self, format,globals,locals=None,
227 226 codec='utf_8',encoding_errors='backslashreplace'):
228 227 """ItplNS(format,globals[,locals]) -> interpolating string instance.
229 228
230 229 This constructor, besides a format string, takes a globals dictionary
231 230 and optionally a locals (which defaults to globals if not provided).
232 231
233 232 For further details, see the Itpl constructor."""
234 233
235 234 if locals is None:
236 235 locals = globals
237 236 self.globals = globals
238 237 self.locals = locals
239 238 Itpl.__init__(self,format,codec,encoding_errors)
240 239
241 240 def __str__(self):
242 241 """Evaluate and substitute the appropriate parts of the string."""
243 242 return self._str(self.globals,self.locals)
244 243
245 244 def __repr__(self):
246 245 return "<ItplNS %s >" % repr(self.format)
247 246
248 247 # utilities for fast printing
249 248 def itpl(text): return str(Itpl(text))
250 249 def printpl(text): print itpl(text)
251 250 # versions with namespace
252 251 def itplns(text,globals,locals=None): return str(ItplNS(text,globals,locals))
253 252 def printplns(text,globals,locals=None): print itplns(text,globals,locals)
254 253
255 254 class ItplFile:
256 255 """A file object that filters each write() through an interpolator."""
257 256 def __init__(self, file): self.file = file
258 257 def __repr__(self): return "<interpolated " + repr(self.file) + ">"
259 258 def __getattr__(self, attr): return getattr(self.file, attr)
260 259 def write(self, text): self.file.write(str(Itpl(text)))
261 260
262 261 def filter(file=sys.stdout):
263 262 """Return an ItplFile that filters writes to the given file object.
264 263
265 264 'file = filter(file)' replaces 'file' with a filtered object that
266 265 has a write() method. When called with no argument, this creates
267 266 a filter to sys.stdout."""
268 267 return ItplFile(file)
269 268
270 269 def unfilter(ifile=None):
271 270 """Return the original file that corresponds to the given ItplFile.
272 271
273 272 'file = unfilter(file)' undoes the effect of 'file = filter(file)'.
274 273 'sys.stdout = unfilter()' undoes the effect of 'sys.stdout = filter()'."""
275 274 return ifile and ifile.file or sys.stdout.file
@@ -1,1845 +1,1843 b''
1 1 """Pexpect is a Python module for spawning child applications and controlling
2 2 them automatically. Pexpect can be used for automating interactive applications
3 3 such as ssh, ftp, passwd, telnet, etc. It can be used to a automate setup
4 4 scripts for duplicating software package installations on different servers. It
5 5 can be used for automated software testing. Pexpect is in the spirit of Don
6 6 Libes' Expect, but Pexpect is pure Python. Other Expect-like modules for Python
7 7 require TCL and Expect or require C extensions to be compiled. Pexpect does not
8 8 use C, Expect, or TCL extensions. It should work on any platform that supports
9 9 the standard Python pty module. The Pexpect interface focuses on ease of use so
10 10 that simple tasks are easy.
11 11
12 12 There are two main interfaces to Pexpect -- the function, run() and the class,
13 13 spawn. You can call the run() function to execute a command and return the
14 14 output. This is a handy replacement for os.system().
15 15
16 16 For example::
17 17
18 18 pexpect.run('ls -la')
19 19
20 20 The more powerful interface is the spawn class. You can use this to spawn an
21 21 external child command and then interact with the child by sending lines and
22 22 expecting responses.
23 23
24 24 For example::
25 25
26 26 child = pexpect.spawn('scp foo myname@host.example.com:.')
27 27 child.expect ('Password:')
28 28 child.sendline (mypassword)
29 29
30 30 This works even for commands that ask for passwords or other input outside of
31 31 the normal stdio streams.
32 32
33 33 Credits: Noah Spurrier, Richard Holden, Marco Molteni, Kimberley Burchett,
34 34 Robert Stone, Hartmut Goebel, Chad Schroeder, Erick Tryzelaar, Dave Kirby, Ids
35 35 vander Molen, George Todd, Noel Taylor, Nicolas D. Cesar, Alexander Gattin,
36 36 Geoffrey Marshall, Francisco Lourenco, Glen Mabey, Karthik Gurusamy, Fernando
37 37 Perez, Corey Minyard, Jon Cohen, Guillaume Chazarain, Andrew Ryan, Nick
38 38 Craig-Wood, Andrew Stone, Jorgen Grahn (Let me know if I forgot anyone.)
39 39
40 40 Free, open source, and all that good stuff.
41 41
42 42 Permission is hereby granted, free of charge, to any person obtaining a copy of
43 43 this software and associated documentation files (the "Software"), to deal in
44 44 the Software without restriction, including without limitation the rights to
45 45 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
46 46 of the Software, and to permit persons to whom the Software is furnished to do
47 47 so, subject to the following conditions:
48 48
49 49 The above copyright notice and this permission notice shall be included in all
50 50 copies or substantial portions of the Software.
51 51
52 52 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
53 53 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
54 54 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
55 55 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
56 56 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
57 57 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
58 58 SOFTWARE.
59 59
60 60 Pexpect Copyright (c) 2008 Noah Spurrier
61 61 http://pexpect.sourceforge.net/
62 62
63 63 $Id: pexpect.py 507 2007-12-27 02:40:52Z noah $
64 64 """
65 65
66 66 try:
67 67 import os, sys, time
68 68 import select
69 import string
70 69 import re
71 70 import struct
72 71 import resource
73 72 import types
74 73 import pty
75 74 import tty
76 75 import termios
77 76 import fcntl
78 77 import errno
79 78 import traceback
80 79 import signal
81 80 except ImportError, e:
82 81 raise ImportError (str(e) + """
83 82
84 83 A critical module was not found. Probably this operating system does not
85 84 support it. Pexpect is intended for UNIX-like operating systems.""")
86 85
87 86 __version__ = '2.3'
88 87 __revision__ = '$Revision: 399 $'
89 88 __all__ = ['ExceptionPexpect', 'EOF', 'TIMEOUT', 'spawn', 'run', 'which',
90 89 'split_command_line', '__version__', '__revision__']
91 90
92 91 # Exception classes used by this module.
93 92 class ExceptionPexpect(Exception):
94 93
95 94 """Base class for all exceptions raised by this module.
96 95 """
97 96
98 97 def __init__(self, value):
99 98
100 99 self.value = value
101 100
102 101 def __str__(self):
103 102
104 103 return str(self.value)
105 104
106 105 def get_trace(self):
107 106
108 107 """This returns an abbreviated stack trace with lines that only concern
109 108 the caller. In other words, the stack trace inside the Pexpect module
110 109 is not included. """
111 110
112 111 tblist = traceback.extract_tb(sys.exc_info()[2])
113 112 #tblist = filter(self.__filter_not_pexpect, tblist)
114 113 tblist = [item for item in tblist if self.__filter_not_pexpect(item)]
115 114 tblist = traceback.format_list(tblist)
116 115 return ''.join(tblist)
117 116
118 117 def __filter_not_pexpect(self, trace_list_item):
119 118
120 119 """This returns True if list item 0 the string 'pexpect.py' in it. """
121 120
122 121 if trace_list_item[0].find('pexpect.py') == -1:
123 122 return True
124 123 else:
125 124 return False
126 125
127 126 class EOF(ExceptionPexpect):
128 127
129 128 """Raised when EOF is read from a child. This usually means the child has exited."""
130 129
131 130 class TIMEOUT(ExceptionPexpect):
132 131
133 132 """Raised when a read time exceeds the timeout. """
134 133
135 134 ##class TIMEOUT_PATTERN(TIMEOUT):
136 135 ## """Raised when the pattern match time exceeds the timeout.
137 136 ## This is different than a read TIMEOUT because the child process may
138 137 ## give output, thus never give a TIMEOUT, but the output
139 138 ## may never match a pattern.
140 139 ## """
141 140 ##class MAXBUFFER(ExceptionPexpect):
142 141 ## """Raised when a scan buffer fills before matching an expected pattern."""
143 142
144 143 def run (command, timeout=-1, withexitstatus=False, events=None, extra_args=None, logfile=None, cwd=None, env=None):
145 144
146 145 """
147 146 This function runs the given command; waits for it to finish; then
148 147 returns all output as a string. STDERR is included in output. If the full
149 148 path to the command is not given then the path is searched.
150 149
151 150 Note that lines are terminated by CR/LF (\\r\\n) combination even on
152 151 UNIX-like systems because this is the standard for pseudo ttys. If you set
153 152 'withexitstatus' to true, then run will return a tuple of (command_output,
154 153 exitstatus). If 'withexitstatus' is false then this returns just
155 154 command_output.
156 155
157 156 The run() function can often be used instead of creating a spawn instance.
158 157 For example, the following code uses spawn::
159 158
160 159 from pexpect import *
161 160 child = spawn('scp foo myname@host.example.com:.')
162 161 child.expect ('(?i)password')
163 162 child.sendline (mypassword)
164 163
165 164 The previous code can be replace with the following::
166 165
167 166 from pexpect import *
168 167 run ('scp foo myname@host.example.com:.', events={'(?i)password': mypassword})
169 168
170 169 Examples
171 170 ========
172 171
173 172 Start the apache daemon on the local machine::
174 173
175 174 from pexpect import *
176 175 run ("/usr/local/apache/bin/apachectl start")
177 176
178 177 Check in a file using SVN::
179 178
180 179 from pexpect import *
181 180 run ("svn ci -m 'automatic commit' my_file.py")
182 181
183 182 Run a command and capture exit status::
184 183
185 184 from pexpect import *
186 185 (command_output, exitstatus) = run ('ls -l /bin', withexitstatus=1)
187 186
188 187 Tricky Examples
189 188 ===============
190 189
191 190 The following will run SSH and execute 'ls -l' on the remote machine. The
192 191 password 'secret' will be sent if the '(?i)password' pattern is ever seen::
193 192
194 193 run ("ssh username@machine.example.com 'ls -l'", events={'(?i)password':'secret\\n'})
195 194
196 195 This will start mencoder to rip a video from DVD. This will also display
197 196 progress ticks every 5 seconds as it runs. For example::
198 197
199 198 from pexpect import *
200 199 def print_ticks(d):
201 200 print d['event_count'],
202 201 run ("mencoder dvd://1 -o video.avi -oac copy -ovc copy", events={TIMEOUT:print_ticks}, timeout=5)
203 202
204 203 The 'events' argument should be a dictionary of patterns and responses.
205 204 Whenever one of the patterns is seen in the command out run() will send the
206 205 associated response string. Note that you should put newlines in your
207 206 string if Enter is necessary. The responses may also contain callback
208 207 functions. Any callback is function that takes a dictionary as an argument.
209 208 The dictionary contains all the locals from the run() function, so you can
210 209 access the child spawn object or any other variable defined in run()
211 210 (event_count, child, and extra_args are the most useful). A callback may
212 211 return True to stop the current run process otherwise run() continues until
213 212 the next event. A callback may also return a string which will be sent to
214 213 the child. 'extra_args' is not used by directly run(). It provides a way to
215 214 pass data to a callback function through run() through the locals
216 215 dictionary passed to a callback. """
217 216
218 217 if timeout == -1:
219 218 child = spawn(command, maxread=2000, logfile=logfile, cwd=cwd, env=env)
220 219 else:
221 220 child = spawn(command, timeout=timeout, maxread=2000, logfile=logfile, cwd=cwd, env=env)
222 221 if events is not None:
223 222 patterns = events.keys()
224 223 responses = events.values()
225 224 else:
226 225 patterns=None # We assume that EOF or TIMEOUT will save us.
227 226 responses=None
228 227 child_result_list = []
229 228 event_count = 0
230 229 while 1:
231 230 try:
232 231 index = child.expect (patterns)
233 232 if type(child.after) in types.StringTypes:
234 233 child_result_list.append(child.before + child.after)
235 234 else: # child.after may have been a TIMEOUT or EOF, so don't cat those.
236 235 child_result_list.append(child.before)
237 236 if type(responses[index]) in types.StringTypes:
238 237 child.send(responses[index])
239 238 elif type(responses[index]) is types.FunctionType:
240 239 callback_result = responses[index](locals())
241 240 sys.stdout.flush()
242 241 if type(callback_result) in types.StringTypes:
243 242 child.send(callback_result)
244 243 elif callback_result:
245 244 break
246 245 else:
247 246 raise TypeError ('The callback must be a string or function type.')
248 247 event_count = event_count + 1
249 248 except TIMEOUT, e:
250 249 child_result_list.append(child.before)
251 250 break
252 251 except EOF, e:
253 252 child_result_list.append(child.before)
254 253 break
255 254 child_result = ''.join(child_result_list)
256 255 if withexitstatus:
257 256 child.close()
258 257 return (child_result, child.exitstatus)
259 258 else:
260 259 return child_result
261 260
262 261 class spawn (object):
263 262
264 263 """This is the main class interface for Pexpect. Use this class to start
265 264 and control child applications. """
266 265
267 266 def __init__(self, command, args=[], timeout=30, maxread=2000, searchwindowsize=None, logfile=None, cwd=None, env=None):
268 267
269 268 """This is the constructor. The command parameter may be a string that
270 269 includes a command and any arguments to the command. For example::
271 270
272 271 child = pexpect.spawn ('/usr/bin/ftp')
273 272 child = pexpect.spawn ('/usr/bin/ssh user@example.com')
274 273 child = pexpect.spawn ('ls -latr /tmp')
275 274
276 275 You may also construct it with a list of arguments like so::
277 276
278 277 child = pexpect.spawn ('/usr/bin/ftp', [])
279 278 child = pexpect.spawn ('/usr/bin/ssh', ['user@example.com'])
280 279 child = pexpect.spawn ('ls', ['-latr', '/tmp'])
281 280
282 281 After this the child application will be created and will be ready to
283 282 talk to. For normal use, see expect() and send() and sendline().
284 283
285 284 Remember that Pexpect does NOT interpret shell meta characters such as
286 285 redirect, pipe, or wild cards (>, |, or *). This is a common mistake.
287 286 If you want to run a command and pipe it through another command then
288 287 you must also start a shell. For example::
289 288
290 289 child = pexpect.spawn('/bin/bash -c "ls -l | grep LOG > log_list.txt"')
291 290 child.expect(pexpect.EOF)
292 291
293 292 The second form of spawn (where you pass a list of arguments) is useful
294 293 in situations where you wish to spawn a command and pass it its own
295 294 argument list. This can make syntax more clear. For example, the
296 295 following is equivalent to the previous example::
297 296
298 297 shell_cmd = 'ls -l | grep LOG > log_list.txt'
299 298 child = pexpect.spawn('/bin/bash', ['-c', shell_cmd])
300 299 child.expect(pexpect.EOF)
301 300
302 301 The maxread attribute sets the read buffer size. This is maximum number
303 302 of bytes that Pexpect will try to read from a TTY at one time. Setting
304 303 the maxread size to 1 will turn off buffering. Setting the maxread
305 304 value higher may help performance in cases where large amounts of
306 305 output are read back from the child. This feature is useful in
307 306 conjunction with searchwindowsize.
308 307
309 308 The searchwindowsize attribute sets the how far back in the incomming
310 309 seach buffer Pexpect will search for pattern matches. Every time
311 310 Pexpect reads some data from the child it will append the data to the
312 311 incomming buffer. The default is to search from the beginning of the
313 312 imcomming buffer each time new data is read from the child. But this is
314 313 very inefficient if you are running a command that generates a large
315 314 amount of data where you want to match The searchwindowsize does not
316 315 effect the size of the incomming data buffer. You will still have
317 316 access to the full buffer after expect() returns.
318 317
319 318 The logfile member turns on or off logging. All input and output will
320 319 be copied to the given file object. Set logfile to None to stop
321 320 logging. This is the default. Set logfile to sys.stdout to echo
322 321 everything to standard output. The logfile is flushed after each write.
323 322
324 323 Example log input and output to a file::
325 324
326 325 child = pexpect.spawn('some_command')
327 326 fout = file('mylog.txt','w')
328 327 child.logfile = fout
329 328
330 329 Example log to stdout::
331 330
332 331 child = pexpect.spawn('some_command')
333 332 child.logfile = sys.stdout
334 333
335 334 The logfile_read and logfile_send members can be used to separately log
336 335 the input from the child and output sent to the child. Sometimes you
337 336 don't want to see everything you write to the child. You only want to
338 337 log what the child sends back. For example::
339 338
340 339 child = pexpect.spawn('some_command')
341 340 child.logfile_read = sys.stdout
342 341
343 342 To separately log output sent to the child use logfile_send::
344 343
345 344 self.logfile_send = fout
346 345
347 346 The delaybeforesend helps overcome a weird behavior that many users
348 347 were experiencing. The typical problem was that a user would expect() a
349 348 "Password:" prompt and then immediately call sendline() to send the
350 349 password. The user would then see that their password was echoed back
351 350 to them. Passwords don't normally echo. The problem is caused by the
352 351 fact that most applications print out the "Password" prompt and then
353 352 turn off stdin echo, but if you send your password before the
354 353 application turned off echo, then you get your password echoed.
355 354 Normally this wouldn't be a problem when interacting with a human at a
356 355 real keyboard. If you introduce a slight delay just before writing then
357 356 this seems to clear up the problem. This was such a common problem for
358 357 many users that I decided that the default pexpect behavior should be
359 358 to sleep just before writing to the child application. 1/20th of a
360 359 second (50 ms) seems to be enough to clear up the problem. You can set
361 360 delaybeforesend to 0 to return to the old behavior. Most Linux machines
362 361 don't like this to be below 0.03. I don't know why.
363 362
364 363 Note that spawn is clever about finding commands on your path.
365 364 It uses the same logic that "which" uses to find executables.
366 365
367 366 If you wish to get the exit status of the child you must call the
368 367 close() method. The exit or signal status of the child will be stored
369 368 in self.exitstatus or self.signalstatus. If the child exited normally
370 369 then exitstatus will store the exit return code and signalstatus will
371 370 be None. If the child was terminated abnormally with a signal then
372 371 signalstatus will store the signal value and exitstatus will be None.
373 372 If you need more detail you can also read the self.status member which
374 373 stores the status returned by os.waitpid. You can interpret this using
375 374 os.WIFEXITED/os.WEXITSTATUS or os.WIFSIGNALED/os.TERMSIG. """
376 375
377 376 self.STDIN_FILENO = pty.STDIN_FILENO
378 377 self.STDOUT_FILENO = pty.STDOUT_FILENO
379 378 self.STDERR_FILENO = pty.STDERR_FILENO
380 379 self.stdin = sys.stdin
381 380 self.stdout = sys.stdout
382 381 self.stderr = sys.stderr
383 382
384 383 self.searcher = None
385 384 self.ignorecase = False
386 385 self.before = None
387 386 self.after = None
388 387 self.match = None
389 388 self.match_index = None
390 389 self.terminated = True
391 390 self.exitstatus = None
392 391 self.signalstatus = None
393 392 self.status = None # status returned by os.waitpid
394 393 self.flag_eof = False
395 394 self.pid = None
396 395 self.child_fd = -1 # initially closed
397 396 self.timeout = timeout
398 397 self.delimiter = EOF
399 398 self.logfile = logfile
400 399 self.logfile_read = None # input from child (read_nonblocking)
401 400 self.logfile_send = None # output to send (send, sendline)
402 401 self.maxread = maxread # max bytes to read at one time into buffer
403 402 self.buffer = '' # This is the read buffer. See maxread.
404 403 self.searchwindowsize = searchwindowsize # Anything before searchwindowsize point is preserved, but not searched.
405 404 # Most Linux machines don't like delaybeforesend to be below 0.03 (30 ms).
406 405 self.delaybeforesend = 0.05 # Sets sleep time used just before sending data to child. Time in seconds.
407 406 self.delayafterclose = 0.1 # Sets delay in close() method to allow kernel time to update process status. Time in seconds.
408 407 self.delayafterterminate = 0.1 # Sets delay in terminate() method to allow kernel time to update process status. Time in seconds.
409 408 self.softspace = False # File-like object.
410 409 self.name = '<' + repr(self) + '>' # File-like object.
411 410 self.encoding = None # File-like object.
412 411 self.closed = True # File-like object.
413 412 self.cwd = cwd
414 413 self.env = env
415 414 self.__irix_hack = (sys.platform.lower().find('irix')>=0) # This flags if we are running on irix
416 415 # Solaris uses internal __fork_pty(). All others use pty.fork().
417 416 if (sys.platform.lower().find('solaris')>=0) or (sys.platform.lower().find('sunos5')>=0):
418 417 self.use_native_pty_fork = False
419 418 else:
420 419 self.use_native_pty_fork = True
421 420
422 421
423 422 # allow dummy instances for subclasses that may not use command or args.
424 423 if command is None:
425 424 self.command = None
426 425 self.args = None
427 426 self.name = '<pexpect factory incomplete>'
428 427 else:
429 428 self._spawn (command, args)
430 429
431 430 def __del__(self):
432 431
433 432 """This makes sure that no system resources are left open. Python only
434 433 garbage collects Python objects. OS file descriptors are not Python
435 434 objects, so they must be handled explicitly. If the child file
436 435 descriptor was opened outside of this class (passed to the constructor)
437 436 then this does not close it. """
438 437
439 438 if not self.closed:
440 439 # It is possible for __del__ methods to execute during the
441 440 # teardown of the Python VM itself. Thus self.close() may
442 441 # trigger an exception because os.close may be None.
443 442 # -- Fernando Perez
444 443 try:
445 444 self.close()
446 445 except AttributeError:
447 446 pass
448 447
449 448 def __str__(self):
450 449
451 450 """This returns a human-readable string that represents the state of
452 451 the object. """
453 452
454 453 s = []
455 454 s.append(repr(self))
456 455 s.append('version: ' + __version__ + ' (' + __revision__ + ')')
457 456 s.append('command: ' + str(self.command))
458 457 s.append('args: ' + str(self.args))
459 458 s.append('searcher: ' + str(self.searcher))
460 459 s.append('buffer (last 100 chars): ' + str(self.buffer)[-100:])
461 460 s.append('before (last 100 chars): ' + str(self.before)[-100:])
462 461 s.append('after: ' + str(self.after))
463 462 s.append('match: ' + str(self.match))
464 463 s.append('match_index: ' + str(self.match_index))
465 464 s.append('exitstatus: ' + str(self.exitstatus))
466 465 s.append('flag_eof: ' + str(self.flag_eof))
467 466 s.append('pid: ' + str(self.pid))
468 467 s.append('child_fd: ' + str(self.child_fd))
469 468 s.append('closed: ' + str(self.closed))
470 469 s.append('timeout: ' + str(self.timeout))
471 470 s.append('delimiter: ' + str(self.delimiter))
472 471 s.append('logfile: ' + str(self.logfile))
473 472 s.append('logfile_read: ' + str(self.logfile_read))
474 473 s.append('logfile_send: ' + str(self.logfile_send))
475 474 s.append('maxread: ' + str(self.maxread))
476 475 s.append('ignorecase: ' + str(self.ignorecase))
477 476 s.append('searchwindowsize: ' + str(self.searchwindowsize))
478 477 s.append('delaybeforesend: ' + str(self.delaybeforesend))
479 478 s.append('delayafterclose: ' + str(self.delayafterclose))
480 479 s.append('delayafterterminate: ' + str(self.delayafterterminate))
481 480 return '\n'.join(s)
482 481
483 482 def _spawn(self,command,args=[]):
484 483
485 484 """This starts the given command in a child process. This does all the
486 485 fork/exec type of stuff for a pty. This is called by __init__. If args
487 486 is empty then command will be parsed (split on spaces) and args will be
488 487 set to parsed arguments. """
489 488
490 489 # The pid and child_fd of this object get set by this method.
491 490 # Note that it is difficult for this method to fail.
492 491 # You cannot detect if the child process cannot start.
493 492 # So the only way you can tell if the child process started
494 493 # or not is to try to read from the file descriptor. If you get
495 494 # EOF immediately then it means that the child is already dead.
496 495 # That may not necessarily be bad because you may haved spawned a child
497 496 # that performs some task; creates no stdout output; and then dies.
498 497
499 498 # If command is an int type then it may represent a file descriptor.
500 499 if type(command) == type(0):
501 500 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.')
502 501
503 502 if type (args) != type([]):
504 503 raise TypeError ('The argument, args, must be a list.')
505 504
506 505 if args == []:
507 506 self.args = split_command_line(command)
508 507 self.command = self.args[0]
509 508 else:
510 509 self.args = args[:] # work with a copy
511 510 self.args.insert (0, command)
512 511 self.command = command
513 512
514 513 command_with_path = which(self.command)
515 514 if command_with_path is None:
516 515 raise ExceptionPexpect ('The command was not found or was not executable: %s.' % self.command)
517 516 self.command = command_with_path
518 517 self.args[0] = self.command
519 518
520 519 self.name = '<' + ' '.join (self.args) + '>'
521 520
522 521 assert self.pid is None, 'The pid member should be None.'
523 522 assert self.command is not None, 'The command member should not be None.'
524 523
525 524 if self.use_native_pty_fork:
526 525 try:
527 526 self.pid, self.child_fd = pty.fork()
528 527 except OSError, e:
529 528 raise ExceptionPexpect('Error! pty.fork() failed: ' + str(e))
530 529 else: # Use internal __fork_pty
531 530 self.pid, self.child_fd = self.__fork_pty()
532 531
533 532 if self.pid == 0: # Child
534 533 try:
535 534 self.child_fd = sys.stdout.fileno() # used by setwinsize()
536 535 self.setwinsize(24, 80)
537 536 except:
538 537 # Some platforms do not like setwinsize (Cygwin).
539 538 # This will cause problem when running applications that
540 539 # are very picky about window size.
541 540 # This is a serious limitation, but not a show stopper.
542 541 pass
543 542 # Do not allow child to inherit open file descriptors from parent.
544 543 max_fd = resource.getrlimit(resource.RLIMIT_NOFILE)[0]
545 544 for i in range (3, max_fd):
546 545 try:
547 546 os.close (i)
548 547 except OSError:
549 548 pass
550 549
551 550 # I don't know why this works, but ignoring SIGHUP fixes a
552 551 # problem when trying to start a Java daemon with sudo
553 552 # (specifically, Tomcat).
554 553 signal.signal(signal.SIGHUP, signal.SIG_IGN)
555 554
556 555 if self.cwd is not None:
557 556 os.chdir(self.cwd)
558 557 if self.env is None:
559 558 os.execv(self.command, self.args)
560 559 else:
561 560 os.execvpe(self.command, self.args, self.env)
562 561
563 562 # Parent
564 563 self.terminated = False
565 564 self.closed = False
566 565
567 566 def __fork_pty(self):
568 567
569 568 """This implements a substitute for the forkpty system call. This
570 569 should be more portable than the pty.fork() function. Specifically,
571 570 this should work on Solaris.
572 571
573 572 Modified 10.06.05 by Geoff Marshall: Implemented __fork_pty() method to
574 573 resolve the issue with Python's pty.fork() not supporting Solaris,
575 574 particularly ssh. Based on patch to posixmodule.c authored by Noah
576 575 Spurrier::
577 576
578 577 http://mail.python.org/pipermail/python-dev/2003-May/035281.html
579 578
580 579 """
581 580
582 581 parent_fd, child_fd = os.openpty()
583 582 if parent_fd < 0 or child_fd < 0:
584 583 raise ExceptionPexpect, "Error! Could not open pty with os.openpty()."
585 584
586 585 pid = os.fork()
587 586 if pid < 0:
588 587 raise ExceptionPexpect, "Error! Failed os.fork()."
589 588 elif pid == 0:
590 589 # Child.
591 590 os.close(parent_fd)
592 591 self.__pty_make_controlling_tty(child_fd)
593 592
594 593 os.dup2(child_fd, 0)
595 594 os.dup2(child_fd, 1)
596 595 os.dup2(child_fd, 2)
597 596
598 597 if child_fd > 2:
599 598 os.close(child_fd)
600 599 else:
601 600 # Parent.
602 601 os.close(child_fd)
603 602
604 603 return pid, parent_fd
605 604
606 605 def __pty_make_controlling_tty(self, tty_fd):
607 606
608 607 """This makes the pseudo-terminal the controlling tty. This should be
609 608 more portable than the pty.fork() function. Specifically, this should
610 609 work on Solaris. """
611 610
612 611 child_name = os.ttyname(tty_fd)
613 612
614 613 # Disconnect from controlling tty if still connected.
615 614 fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY);
616 615 if fd >= 0:
617 616 os.close(fd)
618 617
619 618 os.setsid()
620 619
621 620 # Verify we are disconnected from controlling tty
622 621 try:
623 622 fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY);
624 623 if fd >= 0:
625 624 os.close(fd)
626 625 raise ExceptionPexpect, "Error! We are not disconnected from a controlling tty."
627 626 except:
628 627 # Good! We are disconnected from a controlling tty.
629 628 pass
630 629
631 630 # Verify we can open child pty.
632 631 fd = os.open(child_name, os.O_RDWR);
633 632 if fd < 0:
634 633 raise ExceptionPexpect, "Error! Could not open child pty, " + child_name
635 634 else:
636 635 os.close(fd)
637 636
638 637 # Verify we now have a controlling tty.
639 638 fd = os.open("/dev/tty", os.O_WRONLY)
640 639 if fd < 0:
641 640 raise ExceptionPexpect, "Error! Could not open controlling tty, /dev/tty"
642 641 else:
643 642 os.close(fd)
644 643
645 644 def fileno (self): # File-like object.
646 645
647 646 """This returns the file descriptor of the pty for the child.
648 647 """
649 648
650 649 return self.child_fd
651 650
652 651 def close (self, force=True): # File-like object.
653 652
654 653 """This closes the connection with the child application. Note that
655 654 calling close() more than once is valid. This emulates standard Python
656 655 behavior with files. Set force to True if you want to make sure that
657 656 the child is terminated (SIGKILL is sent if the child ignores SIGHUP
658 657 and SIGINT). """
659 658
660 659 if not self.closed:
661 660 self.flush()
662 661 os.close (self.child_fd)
663 662 time.sleep(self.delayafterclose) # Give kernel time to update process status.
664 663 if self.isalive():
665 664 if not self.terminate(force):
666 665 raise ExceptionPexpect ('close() could not terminate the child using terminate()')
667 666 self.child_fd = -1
668 667 self.closed = True
669 668 #self.pid = None
670 669
671 670 def flush (self): # File-like object.
672 671
673 672 """This does nothing. It is here to support the interface for a
674 673 File-like object. """
675 674
676 675 pass
677 676
678 677 def isatty (self): # File-like object.
679 678
680 679 """This returns True if the file descriptor is open and connected to a
681 680 tty(-like) device, else False. """
682 681
683 682 return os.isatty(self.child_fd)
684 683
685 684 def waitnoecho (self, timeout=-1):
686 685
687 686 """This waits until the terminal ECHO flag is set False. This returns
688 687 True if the echo mode is off. This returns False if the ECHO flag was
689 688 not set False before the timeout. This can be used to detect when the
690 689 child is waiting for a password. Usually a child application will turn
691 690 off echo mode when it is waiting for the user to enter a password. For
692 691 example, instead of expecting the "password:" prompt you can wait for
693 692 the child to set ECHO off::
694 693
695 694 p = pexpect.spawn ('ssh user@example.com')
696 695 p.waitnoecho()
697 696 p.sendline(mypassword)
698 697
699 698 If timeout is None then this method to block forever until ECHO flag is
700 699 False.
701 700
702 701 """
703 702
704 703 if timeout == -1:
705 704 timeout = self.timeout
706 705 if timeout is not None:
707 706 end_time = time.time() + timeout
708 707 while True:
709 708 if not self.getecho():
710 709 return True
711 710 if timeout < 0 and timeout is not None:
712 711 return False
713 712 if timeout is not None:
714 713 timeout = end_time - time.time()
715 714 time.sleep(0.1)
716 715
717 716 def getecho (self):
718 717
719 718 """This returns the terminal echo mode. This returns True if echo is
720 719 on or False if echo is off. Child applications that are expecting you
721 720 to enter a password often set ECHO False. See waitnoecho(). """
722 721
723 722 attr = termios.tcgetattr(self.child_fd)
724 723 if attr[3] & termios.ECHO:
725 724 return True
726 725 return False
727 726
728 727 def setecho (self, state):
729 728
730 729 """This sets the terminal echo mode on or off. Note that anything the
731 730 child sent before the echo will be lost, so you should be sure that
732 731 your input buffer is empty before you call setecho(). For example, the
733 732 following will work as expected::
734 733
735 734 p = pexpect.spawn('cat')
736 735 p.sendline ('1234') # We will see this twice (once from tty echo and again from cat).
737 736 p.expect (['1234'])
738 737 p.expect (['1234'])
739 738 p.setecho(False) # Turn off tty echo
740 739 p.sendline ('abcd') # We will set this only once (echoed by cat).
741 740 p.sendline ('wxyz') # We will set this only once (echoed by cat)
742 741 p.expect (['abcd'])
743 742 p.expect (['wxyz'])
744 743
745 744 The following WILL NOT WORK because the lines sent before the setecho
746 745 will be lost::
747 746
748 747 p = pexpect.spawn('cat')
749 748 p.sendline ('1234') # We will see this twice (once from tty echo and again from cat).
750 749 p.setecho(False) # Turn off tty echo
751 750 p.sendline ('abcd') # We will set this only once (echoed by cat).
752 751 p.sendline ('wxyz') # We will set this only once (echoed by cat)
753 752 p.expect (['1234'])
754 753 p.expect (['1234'])
755 754 p.expect (['abcd'])
756 755 p.expect (['wxyz'])
757 756 """
758 757
759 758 self.child_fd
760 759 attr = termios.tcgetattr(self.child_fd)
761 760 if state:
762 761 attr[3] = attr[3] | termios.ECHO
763 762 else:
764 763 attr[3] = attr[3] & ~termios.ECHO
765 764 # I tried TCSADRAIN and TCSAFLUSH, but these were inconsistent
766 765 # and blocked on some platforms. TCSADRAIN is probably ideal if it worked.
767 766 termios.tcsetattr(self.child_fd, termios.TCSANOW, attr)
768 767
769 768 def read_nonblocking (self, size = 1, timeout = -1):
770 769
771 770 """This reads at most size characters from the child application. It
772 771 includes a timeout. If the read does not complete within the timeout
773 772 period then a TIMEOUT exception is raised. If the end of file is read
774 773 then an EOF exception will be raised. If a log file was set using
775 774 setlog() then all data will also be written to the log file.
776 775
777 776 If timeout is None then the read may block indefinitely. If timeout is -1
778 777 then the self.timeout value is used. If timeout is 0 then the child is
779 778 polled and if there was no data immediately ready then this will raise
780 779 a TIMEOUT exception.
781 780
782 781 The timeout refers only to the amount of time to read at least one
783 782 character. This is not effected by the 'size' parameter, so if you call
784 783 read_nonblocking(size=100, timeout=30) and only one character is
785 784 available right away then one character will be returned immediately.
786 785 It will not wait for 30 seconds for another 99 characters to come in.
787 786
788 787 This is a wrapper around os.read(). It uses select.select() to
789 788 implement the timeout. """
790 789
791 790 if self.closed:
792 791 raise ValueError ('I/O operation on closed file in read_nonblocking().')
793 792
794 793 if timeout == -1:
795 794 timeout = self.timeout
796 795
797 796 # Note that some systems such as Solaris do not give an EOF when
798 797 # the child dies. In fact, you can still try to read
799 798 # from the child_fd -- it will block forever or until TIMEOUT.
800 799 # For this case, I test isalive() before doing any reading.
801 800 # If isalive() is false, then I pretend that this is the same as EOF.
802 801 if not self.isalive():
803 802 r,w,e = self.__select([self.child_fd], [], [], 0) # timeout of 0 means "poll"
804 803 if not r:
805 804 self.flag_eof = True
806 805 raise EOF ('End Of File (EOF) in read_nonblocking(). Braindead platform.')
807 806 elif self.__irix_hack:
808 807 # This is a hack for Irix. It seems that Irix requires a long delay before checking isalive.
809 808 # This adds a 2 second delay, but only when the child is terminated.
810 809 r, w, e = self.__select([self.child_fd], [], [], 2)
811 810 if not r and not self.isalive():
812 811 self.flag_eof = True
813 812 raise EOF ('End Of File (EOF) in read_nonblocking(). Pokey platform.')
814 813
815 814 r,w,e = self.__select([self.child_fd], [], [], timeout)
816 815
817 816 if not r:
818 817 if not self.isalive():
819 818 # Some platforms, such as Irix, will claim that their processes are alive;
820 819 # then timeout on the select; and then finally admit that they are not alive.
821 820 self.flag_eof = True
822 821 raise EOF ('End of File (EOF) in read_nonblocking(). Very pokey platform.')
823 822 else:
824 823 raise TIMEOUT ('Timeout exceeded in read_nonblocking().')
825 824
826 825 if self.child_fd in r:
827 826 try:
828 827 s = os.read(self.child_fd, size)
829 828 except OSError, e: # Linux does this
830 829 self.flag_eof = True
831 830 raise EOF ('End Of File (EOF) in read_nonblocking(). Exception style platform.')
832 831 if s == '': # BSD style
833 832 self.flag_eof = True
834 833 raise EOF ('End Of File (EOF) in read_nonblocking(). Empty string style platform.')
835 834
836 835 if self.logfile is not None:
837 836 self.logfile.write (s)
838 837 self.logfile.flush()
839 838 if self.logfile_read is not None:
840 839 self.logfile_read.write (s)
841 840 self.logfile_read.flush()
842 841
843 842 return s
844 843
845 844 raise ExceptionPexpect ('Reached an unexpected state in read_nonblocking().')
846 845
847 846 def read (self, size = -1): # File-like object.
848 847
849 848 """This reads at most "size" bytes from the file (less if the read hits
850 849 EOF before obtaining size bytes). If the size argument is negative or
851 850 omitted, read all data until EOF is reached. The bytes are returned as
852 851 a string object. An empty string is returned when EOF is encountered
853 852 immediately. """
854 853
855 854 if size == 0:
856 855 return ''
857 856 if size < 0:
858 857 self.expect (self.delimiter) # delimiter default is EOF
859 858 return self.before
860 859
861 860 # I could have done this more directly by not using expect(), but
862 861 # I deliberately decided to couple read() to expect() so that
863 862 # I would catch any bugs early and ensure consistant behavior.
864 863 # It's a little less efficient, but there is less for me to
865 864 # worry about if I have to later modify read() or expect().
866 865 # Note, it's OK if size==-1 in the regex. That just means it
867 866 # will never match anything in which case we stop only on EOF.
868 867 cre = re.compile('.{%d}' % size, re.DOTALL)
869 868 index = self.expect ([cre, self.delimiter]) # delimiter default is EOF
870 869 if index == 0:
871 870 return self.after ### self.before should be ''. Should I assert this?
872 871 return self.before
873 872
874 873 def readline (self, size = -1): # File-like object.
875 874
876 875 """This reads and returns one entire line. A trailing newline is kept
877 876 in the string, but may be absent when a file ends with an incomplete
878 877 line. Note: This readline() looks for a \\r\\n pair even on UNIX
879 878 because this is what the pseudo tty device returns. So contrary to what
880 879 you may expect you will receive the newline as \\r\\n. An empty string
881 880 is returned when EOF is hit immediately. Currently, the size argument is
882 881 mostly ignored, so this behavior is not standard for a file-like
883 882 object. If size is 0 then an empty string is returned. """
884 883
885 884 if size == 0:
886 885 return ''
887 886 index = self.expect (['\r\n', self.delimiter]) # delimiter default is EOF
888 887 if index == 0:
889 888 return self.before + '\r\n'
890 889 else:
891 890 return self.before
892 891
893 892 def __iter__ (self): # File-like object.
894 893
895 894 """This is to support iterators over a file-like object.
896 895 """
897 896
898 897 return self
899 898
900 899 def next (self): # File-like object.
901 900
902 901 """This is to support iterators over a file-like object.
903 902 """
904 903
905 904 result = self.readline()
906 905 if result == "":
907 906 raise StopIteration
908 907 return result
909 908
910 909 def readlines (self, sizehint = -1): # File-like object.
911 910
912 911 """This reads until EOF using readline() and returns a list containing
913 912 the lines thus read. The optional "sizehint" argument is ignored. """
914 913
915 914 lines = []
916 915 while True:
917 916 line = self.readline()
918 917 if not line:
919 918 break
920 919 lines.append(line)
921 920 return lines
922 921
923 922 def write(self, s): # File-like object.
924 923
925 924 """This is similar to send() except that there is no return value.
926 925 """
927 926
928 927 self.send (s)
929 928
930 929 def writelines (self, sequence): # File-like object.
931 930
932 931 """This calls write() for each element in the sequence. The sequence
933 932 can be any iterable object producing strings, typically a list of
934 933 strings. This does not add line separators There is no return value.
935 934 """
936 935
937 936 for s in sequence:
938 937 self.write (s)
939 938
940 939 def send(self, s):
941 940
942 941 """This sends a string to the child process. This returns the number of
943 942 bytes written. If a log file was set then the data is also written to
944 943 the log. """
945 944
946 945 time.sleep(self.delaybeforesend)
947 946 if self.logfile is not None:
948 947 self.logfile.write (s)
949 948 self.logfile.flush()
950 949 if self.logfile_send is not None:
951 950 self.logfile_send.write (s)
952 951 self.logfile_send.flush()
953 952 c = os.write(self.child_fd, s)
954 953 return c
955 954
956 955 def sendline(self, s=''):
957 956
958 957 """This is like send(), but it adds a line feed (os.linesep). This
959 958 returns the number of bytes written. """
960 959
961 960 n = self.send(s)
962 961 n = n + self.send (os.linesep)
963 962 return n
964 963
965 964 def sendcontrol(self, char):
966 965
967 966 """This sends a control character to the child such as Ctrl-C or
968 967 Ctrl-D. For example, to send a Ctrl-G (ASCII 7)::
969 968
970 969 child.sendcontrol('g')
971 970
972 971 See also, sendintr() and sendeof().
973 972 """
974 973
975 974 char = char.lower()
976 975 a = ord(char)
977 976 if a>=97 and a<=122:
978 977 a = a - ord('a') + 1
979 978 return self.send (chr(a))
980 979 d = {'@':0, '`':0,
981 980 '[':27, '{':27,
982 981 '\\':28, '|':28,
983 982 ']':29, '}': 29,
984 983 '^':30, '~':30,
985 984 '_':31,
986 985 '?':127}
987 986 if char not in d:
988 987 return 0
989 988 return self.send (chr(d[char]))
990 989
991 990 def sendeof(self):
992 991
993 992 """This sends an EOF to the child. This sends a character which causes
994 993 the pending parent output buffer to be sent to the waiting child
995 994 program without waiting for end-of-line. If it is the first character
996 995 of the line, the read() in the user program returns 0, which signifies
997 996 end-of-file. This means to work as expected a sendeof() has to be
998 997 called at the beginning of a line. This method does not send a newline.
999 998 It is the responsibility of the caller to ensure the eof is sent at the
1000 999 beginning of a line. """
1001 1000
1002 1001 ### Hmmm... how do I send an EOF?
1003 1002 ###C if ((m = write(pty, *buf, p - *buf)) < 0)
1004 1003 ###C return (errno == EWOULDBLOCK) ? n : -1;
1005 1004 #fd = sys.stdin.fileno()
1006 1005 #old = termios.tcgetattr(fd) # remember current state
1007 1006 #attr = termios.tcgetattr(fd)
1008 1007 #attr[3] = attr[3] | termios.ICANON # ICANON must be set to recognize EOF
1009 1008 #try: # use try/finally to ensure state gets restored
1010 1009 # termios.tcsetattr(fd, termios.TCSADRAIN, attr)
1011 1010 # if hasattr(termios, 'CEOF'):
1012 1011 # os.write (self.child_fd, '%c' % termios.CEOF)
1013 1012 # else:
1014 1013 # # Silly platform does not define CEOF so assume CTRL-D
1015 1014 # os.write (self.child_fd, '%c' % 4)
1016 1015 #finally: # restore state
1017 1016 # termios.tcsetattr(fd, termios.TCSADRAIN, old)
1018 1017 if hasattr(termios, 'VEOF'):
1019 1018 char = termios.tcgetattr(self.child_fd)[6][termios.VEOF]
1020 1019 else:
1021 1020 # platform does not define VEOF so assume CTRL-D
1022 1021 char = chr(4)
1023 1022 self.send(char)
1024 1023
1025 1024 def sendintr(self):
1026 1025
1027 1026 """This sends a SIGINT to the child. It does not require
1028 1027 the SIGINT to be the first character on a line. """
1029 1028
1030 1029 if hasattr(termios, 'VINTR'):
1031 1030 char = termios.tcgetattr(self.child_fd)[6][termios.VINTR]
1032 1031 else:
1033 1032 # platform does not define VINTR so assume CTRL-C
1034 1033 char = chr(3)
1035 1034 self.send (char)
1036 1035
1037 1036 def eof (self):
1038 1037
1039 1038 """This returns True if the EOF exception was ever raised.
1040 1039 """
1041 1040
1042 1041 return self.flag_eof
1043 1042
1044 1043 def terminate(self, force=False):
1045 1044
1046 1045 """This forces a child process to terminate. It starts nicely with
1047 1046 SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This
1048 1047 returns True if the child was terminated. This returns False if the
1049 1048 child could not be terminated. """
1050 1049
1051 1050 if not self.isalive():
1052 1051 return True
1053 1052 try:
1054 1053 self.kill(signal.SIGHUP)
1055 1054 time.sleep(self.delayafterterminate)
1056 1055 if not self.isalive():
1057 1056 return True
1058 1057 self.kill(signal.SIGCONT)
1059 1058 time.sleep(self.delayafterterminate)
1060 1059 if not self.isalive():
1061 1060 return True
1062 1061 self.kill(signal.SIGINT)
1063 1062 time.sleep(self.delayafterterminate)
1064 1063 if not self.isalive():
1065 1064 return True
1066 1065 if force:
1067 1066 self.kill(signal.SIGKILL)
1068 1067 time.sleep(self.delayafterterminate)
1069 1068 if not self.isalive():
1070 1069 return True
1071 1070 else:
1072 1071 return False
1073 1072 return False
1074 1073 except OSError, e:
1075 1074 # I think there are kernel timing issues that sometimes cause
1076 1075 # this to happen. I think isalive() reports True, but the
1077 1076 # process is dead to the kernel.
1078 1077 # Make one last attempt to see if the kernel is up to date.
1079 1078 time.sleep(self.delayafterterminate)
1080 1079 if not self.isalive():
1081 1080 return True
1082 1081 else:
1083 1082 return False
1084 1083
1085 1084 def wait(self):
1086 1085
1087 1086 """This waits until the child exits. This is a blocking call. This will
1088 1087 not read any data from the child, so this will block forever if the
1089 1088 child has unread output and has terminated. In other words, the child
1090 1089 may have printed output then called exit(); but, technically, the child
1091 1090 is still alive until its output is read. """
1092 1091
1093 1092 if self.isalive():
1094 1093 pid, status = os.waitpid(self.pid, 0)
1095 1094 else:
1096 1095 raise ExceptionPexpect ('Cannot wait for dead child process.')
1097 1096 self.exitstatus = os.WEXITSTATUS(status)
1098 1097 if os.WIFEXITED (status):
1099 1098 self.status = status
1100 1099 self.exitstatus = os.WEXITSTATUS(status)
1101 1100 self.signalstatus = None
1102 1101 self.terminated = True
1103 1102 elif os.WIFSIGNALED (status):
1104 1103 self.status = status
1105 1104 self.exitstatus = None
1106 1105 self.signalstatus = os.WTERMSIG(status)
1107 1106 self.terminated = True
1108 1107 elif os.WIFSTOPPED (status):
1109 1108 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?')
1110 1109 return self.exitstatus
1111 1110
1112 1111 def isalive(self):
1113 1112
1114 1113 """This tests if the child process is running or not. This is
1115 1114 non-blocking. If the child was terminated then this will read the
1116 1115 exitstatus or signalstatus of the child. This returns True if the child
1117 1116 process appears to be running or False if not. It can take literally
1118 1117 SECONDS for Solaris to return the right status. """
1119 1118
1120 1119 if self.terminated:
1121 1120 return False
1122 1121
1123 1122 if self.flag_eof:
1124 1123 # This is for Linux, which requires the blocking form of waitpid to get
1125 1124 # status of a defunct process. This is super-lame. The flag_eof would have
1126 1125 # been set in read_nonblocking(), so this should be safe.
1127 1126 waitpid_options = 0
1128 1127 else:
1129 1128 waitpid_options = os.WNOHANG
1130 1129
1131 1130 try:
1132 1131 pid, status = os.waitpid(self.pid, waitpid_options)
1133 1132 except OSError, e: # No child processes
1134 1133 if e[0] == errno.ECHILD:
1135 1134 raise ExceptionPexpect ('isalive() encountered condition where "terminated" is 0, but there was no child process. Did someone else call waitpid() on our process?')
1136 1135 else:
1137 1136 raise e
1138 1137
1139 1138 # I have to do this twice for Solaris. I can't even believe that I figured this out...
1140 1139 # If waitpid() returns 0 it means that no child process wishes to
1141 1140 # report, and the value of status is undefined.
1142 1141 if pid == 0:
1143 1142 try:
1144 1143 pid, status = os.waitpid(self.pid, waitpid_options) ### os.WNOHANG) # Solaris!
1145 1144 except OSError, e: # This should never happen...
1146 1145 if e[0] == errno.ECHILD:
1147 1146 raise ExceptionPexpect ('isalive() encountered condition that should never happen. There was no child process. Did someone else call waitpid() on our process?')
1148 1147 else:
1149 1148 raise e
1150 1149
1151 1150 # If pid is still 0 after two calls to waitpid() then
1152 1151 # the process really is alive. This seems to work on all platforms, except
1153 1152 # for Irix which seems to require a blocking call on waitpid or select, so I let read_nonblocking
1154 1153 # take care of this situation (unfortunately, this requires waiting through the timeout).
1155 1154 if pid == 0:
1156 1155 return True
1157 1156
1158 1157 if pid == 0:
1159 1158 return True
1160 1159
1161 1160 if os.WIFEXITED (status):
1162 1161 self.status = status
1163 1162 self.exitstatus = os.WEXITSTATUS(status)
1164 1163 self.signalstatus = None
1165 1164 self.terminated = True
1166 1165 elif os.WIFSIGNALED (status):
1167 1166 self.status = status
1168 1167 self.exitstatus = None
1169 1168 self.signalstatus = os.WTERMSIG(status)
1170 1169 self.terminated = True
1171 1170 elif os.WIFSTOPPED (status):
1172 1171 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?')
1173 1172 return False
1174 1173
1175 1174 def kill(self, sig):
1176 1175
1177 1176 """This sends the given signal to the child application. In keeping
1178 1177 with UNIX tradition it has a misleading name. It does not necessarily
1179 1178 kill the child unless you send the right signal. """
1180 1179
1181 1180 # Same as os.kill, but the pid is given for you.
1182 1181 if self.isalive():
1183 1182 os.kill(self.pid, sig)
1184 1183
1185 1184 def compile_pattern_list(self, patterns):
1186 1185
1187 1186 """This compiles a pattern-string or a list of pattern-strings.
1188 1187 Patterns must be a StringType, EOF, TIMEOUT, SRE_Pattern, or a list of
1189 1188 those. Patterns may also be None which results in an empty list (you
1190 1189 might do this if waiting for an EOF or TIMEOUT condition without
1191 1190 expecting any pattern).
1192 1191
1193 1192 This is used by expect() when calling expect_list(). Thus expect() is
1194 1193 nothing more than::
1195 1194
1196 1195 cpl = self.compile_pattern_list(pl)
1197 1196 return self.expect_list(cpl, timeout)
1198 1197
1199 1198 If you are using expect() within a loop it may be more
1200 1199 efficient to compile the patterns first and then call expect_list().
1201 1200 This avoid calls in a loop to compile_pattern_list()::
1202 1201
1203 1202 cpl = self.compile_pattern_list(my_pattern)
1204 1203 while some_condition:
1205 1204 ...
1206 1205 i = self.expect_list(clp, timeout)
1207 1206 ...
1208 1207 """
1209 1208
1210 1209 if patterns is None:
1211 1210 return []
1212 1211 if type(patterns) is not types.ListType:
1213 1212 patterns = [patterns]
1214 1213
1215 1214 compile_flags = re.DOTALL # Allow dot to match \n
1216 1215 if self.ignorecase:
1217 1216 compile_flags = compile_flags | re.IGNORECASE
1218 1217 compiled_pattern_list = []
1219 1218 for p in patterns:
1220 1219 if type(p) in types.StringTypes:
1221 1220 compiled_pattern_list.append(re.compile(p, compile_flags))
1222 1221 elif p is EOF:
1223 1222 compiled_pattern_list.append(EOF)
1224 1223 elif p is TIMEOUT:
1225 1224 compiled_pattern_list.append(TIMEOUT)
1226 1225 elif type(p) is type(re.compile('')):
1227 1226 compiled_pattern_list.append(p)
1228 1227 else:
1229 1228 raise TypeError ('Argument must be one of StringTypes, EOF, TIMEOUT, SRE_Pattern, or a list of those type. %s' % str(type(p)))
1230 1229
1231 1230 return compiled_pattern_list
1232 1231
1233 1232 def expect(self, pattern, timeout = -1, searchwindowsize=None):
1234 1233
1235 1234 """This seeks through the stream until a pattern is matched. The
1236 1235 pattern is overloaded and may take several types. The pattern can be a
1237 1236 StringType, EOF, a compiled re, or a list of any of those types.
1238 1237 Strings will be compiled to re types. This returns the index into the
1239 1238 pattern list. If the pattern was not a list this returns index 0 on a
1240 1239 successful match. This may raise exceptions for EOF or TIMEOUT. To
1241 1240 avoid the EOF or TIMEOUT exceptions add EOF or TIMEOUT to the pattern
1242 1241 list. That will cause expect to match an EOF or TIMEOUT condition
1243 1242 instead of raising an exception.
1244 1243
1245 1244 If you pass a list of patterns and more than one matches, the first match
1246 1245 in the stream is chosen. If more than one pattern matches at that point,
1247 1246 the leftmost in the pattern list is chosen. For example::
1248 1247
1249 1248 # the input is 'foobar'
1250 1249 index = p.expect (['bar', 'foo', 'foobar'])
1251 1250 # returns 1 ('foo') even though 'foobar' is a "better" match
1252 1251
1253 1252 Please note, however, that buffering can affect this behavior, since
1254 1253 input arrives in unpredictable chunks. For example::
1255 1254
1256 1255 # the input is 'foobar'
1257 1256 index = p.expect (['foobar', 'foo'])
1258 1257 # returns 0 ('foobar') if all input is available at once,
1259 1258 # but returs 1 ('foo') if parts of the final 'bar' arrive late
1260 1259
1261 1260 After a match is found the instance attributes 'before', 'after' and
1262 1261 'match' will be set. You can see all the data read before the match in
1263 1262 'before'. You can see the data that was matched in 'after'. The
1264 1263 re.MatchObject used in the re match will be in 'match'. If an error
1265 1264 occurred then 'before' will be set to all the data read so far and
1266 1265 'after' and 'match' will be None.
1267 1266
1268 1267 If timeout is -1 then timeout will be set to the self.timeout value.
1269 1268
1270 1269 A list entry may be EOF or TIMEOUT instead of a string. This will
1271 1270 catch these exceptions and return the index of the list entry instead
1272 1271 of raising the exception. The attribute 'after' will be set to the
1273 1272 exception type. The attribute 'match' will be None. This allows you to
1274 1273 write code like this::
1275 1274
1276 1275 index = p.expect (['good', 'bad', pexpect.EOF, pexpect.TIMEOUT])
1277 1276 if index == 0:
1278 1277 do_something()
1279 1278 elif index == 1:
1280 1279 do_something_else()
1281 1280 elif index == 2:
1282 1281 do_some_other_thing()
1283 1282 elif index == 3:
1284 1283 do_something_completely_different()
1285 1284
1286 1285 instead of code like this::
1287 1286
1288 1287 try:
1289 1288 index = p.expect (['good', 'bad'])
1290 1289 if index == 0:
1291 1290 do_something()
1292 1291 elif index == 1:
1293 1292 do_something_else()
1294 1293 except EOF:
1295 1294 do_some_other_thing()
1296 1295 except TIMEOUT:
1297 1296 do_something_completely_different()
1298 1297
1299 1298 These two forms are equivalent. It all depends on what you want. You
1300 1299 can also just expect the EOF if you are waiting for all output of a
1301 1300 child to finish. For example::
1302 1301
1303 1302 p = pexpect.spawn('/bin/ls')
1304 1303 p.expect (pexpect.EOF)
1305 1304 print p.before
1306 1305
1307 1306 If you are trying to optimize for speed then see expect_list().
1308 1307 """
1309 1308
1310 1309 compiled_pattern_list = self.compile_pattern_list(pattern)
1311 1310 return self.expect_list(compiled_pattern_list, timeout, searchwindowsize)
1312 1311
1313 1312 def expect_list(self, pattern_list, timeout = -1, searchwindowsize = -1):
1314 1313
1315 1314 """This takes a list of compiled regular expressions and returns the
1316 1315 index into the pattern_list that matched the child output. The list may
1317 1316 also contain EOF or TIMEOUT (which are not compiled regular
1318 1317 expressions). This method is similar to the expect() method except that
1319 1318 expect_list() does not recompile the pattern list on every call. This
1320 1319 may help if you are trying to optimize for speed, otherwise just use
1321 1320 the expect() method. This is called by expect(). If timeout==-1 then
1322 1321 the self.timeout value is used. If searchwindowsize==-1 then the
1323 1322 self.searchwindowsize value is used. """
1324 1323
1325 1324 return self.expect_loop(searcher_re(pattern_list), timeout, searchwindowsize)
1326 1325
1327 1326 def expect_exact(self, pattern_list, timeout = -1, searchwindowsize = -1):
1328 1327
1329 1328 """This is similar to expect(), but uses plain string matching instead
1330 1329 of compiled regular expressions in 'pattern_list'. The 'pattern_list'
1331 1330 may be a string; a list or other sequence of strings; or TIMEOUT and
1332 1331 EOF.
1333 1332
1334 1333 This call might be faster than expect() for two reasons: string
1335 1334 searching is faster than RE matching and it is possible to limit the
1336 1335 search to just the end of the input buffer.
1337 1336
1338 1337 This method is also useful when you don't want to have to worry about
1339 1338 escaping regular expression characters that you want to match."""
1340 1339
1341 1340 if type(pattern_list) in types.StringTypes or pattern_list in (TIMEOUT, EOF):
1342 1341 pattern_list = [pattern_list]
1343 1342 return self.expect_loop(searcher_string(pattern_list), timeout, searchwindowsize)
1344 1343
1345 1344 def expect_loop(self, searcher, timeout = -1, searchwindowsize = -1):
1346 1345
1347 1346 """This is the common loop used inside expect. The 'searcher' should be
1348 1347 an instance of searcher_re or searcher_string, which describes how and what
1349 1348 to search for in the input.
1350 1349
1351 1350 See expect() for other arguments, return value and exceptions. """
1352 1351
1353 1352 self.searcher = searcher
1354 1353
1355 1354 if timeout == -1:
1356 1355 timeout = self.timeout
1357 1356 if timeout is not None:
1358 1357 end_time = time.time() + timeout
1359 1358 if searchwindowsize == -1:
1360 1359 searchwindowsize = self.searchwindowsize
1361 1360
1362 1361 try:
1363 1362 incoming = self.buffer
1364 1363 freshlen = len(incoming)
1365 1364 while True: # Keep reading until exception or return.
1366 1365 index = searcher.search(incoming, freshlen, searchwindowsize)
1367 1366 if index >= 0:
1368 1367 self.buffer = incoming[searcher.end : ]
1369 1368 self.before = incoming[ : searcher.start]
1370 1369 self.after = incoming[searcher.start : searcher.end]
1371 1370 self.match = searcher.match
1372 1371 self.match_index = index
1373 1372 return self.match_index
1374 1373 # No match at this point
1375 1374 if timeout < 0 and timeout is not None:
1376 1375 raise TIMEOUT ('Timeout exceeded in expect_any().')
1377 1376 # Still have time left, so read more data
1378 1377 c = self.read_nonblocking (self.maxread, timeout)
1379 1378 freshlen = len(c)
1380 1379 time.sleep (0.0001)
1381 1380 incoming = incoming + c
1382 1381 if timeout is not None:
1383 1382 timeout = end_time - time.time()
1384 1383 except EOF, e:
1385 1384 self.buffer = ''
1386 1385 self.before = incoming
1387 1386 self.after = EOF
1388 1387 index = searcher.eof_index
1389 1388 if index >= 0:
1390 1389 self.match = EOF
1391 1390 self.match_index = index
1392 1391 return self.match_index
1393 1392 else:
1394 1393 self.match = None
1395 1394 self.match_index = None
1396 1395 raise EOF (str(e) + '\n' + str(self))
1397 1396 except TIMEOUT, e:
1398 1397 self.buffer = incoming
1399 1398 self.before = incoming
1400 1399 self.after = TIMEOUT
1401 1400 index = searcher.timeout_index
1402 1401 if index >= 0:
1403 1402 self.match = TIMEOUT
1404 1403 self.match_index = index
1405 1404 return self.match_index
1406 1405 else:
1407 1406 self.match = None
1408 1407 self.match_index = None
1409 1408 raise TIMEOUT (str(e) + '\n' + str(self))
1410 1409 except:
1411 1410 self.before = incoming
1412 1411 self.after = None
1413 1412 self.match = None
1414 1413 self.match_index = None
1415 1414 raise
1416 1415
1417 1416 def getwinsize(self):
1418 1417
1419 1418 """This returns the terminal window size of the child tty. The return
1420 1419 value is a tuple of (rows, cols). """
1421 1420
1422 1421 TIOCGWINSZ = getattr(termios, 'TIOCGWINSZ', 1074295912L)
1423 1422 s = struct.pack('HHHH', 0, 0, 0, 0)
1424 1423 x = fcntl.ioctl(self.fileno(), TIOCGWINSZ, s)
1425 1424 return struct.unpack('HHHH', x)[0:2]
1426 1425
1427 1426 def setwinsize(self, r, c):
1428 1427
1429 1428 """This sets the terminal window size of the child tty. This will cause
1430 1429 a SIGWINCH signal to be sent to the child. This does not change the
1431 1430 physical window size. It changes the size reported to TTY-aware
1432 1431 applications like vi or curses -- applications that respond to the
1433 1432 SIGWINCH signal. """
1434 1433
1435 1434 # Check for buggy platforms. Some Python versions on some platforms
1436 1435 # (notably OSF1 Alpha and RedHat 7.1) truncate the value for
1437 1436 # termios.TIOCSWINSZ. It is not clear why this happens.
1438 1437 # These platforms don't seem to handle the signed int very well;
1439 1438 # yet other platforms like OpenBSD have a large negative value for
1440 1439 # TIOCSWINSZ and they don't have a truncate problem.
1441 1440 # Newer versions of Linux have totally different values for TIOCSWINSZ.
1442 1441 # Note that this fix is a hack.
1443 1442 TIOCSWINSZ = getattr(termios, 'TIOCSWINSZ', -2146929561)
1444 1443 if TIOCSWINSZ == 2148037735L: # L is not required in Python >= 2.2.
1445 1444 TIOCSWINSZ = -2146929561 # Same bits, but with sign.
1446 1445 # Note, assume ws_xpixel and ws_ypixel are zero.
1447 1446 s = struct.pack('HHHH', r, c, 0, 0)
1448 1447 fcntl.ioctl(self.fileno(), TIOCSWINSZ, s)
1449 1448
1450 1449 def interact(self, escape_character = chr(29), input_filter = None, output_filter = None):
1451 1450
1452 1451 """This gives control of the child process to the interactive user (the
1453 1452 human at the keyboard). Keystrokes are sent to the child process, and
1454 1453 the stdout and stderr output of the child process is printed. This
1455 1454 simply echos the child stdout and child stderr to the real stdout and
1456 1455 it echos the real stdin to the child stdin. When the user types the
1457 1456 escape_character this method will stop. The default for
1458 1457 escape_character is ^]. This should not be confused with ASCII 27 --
1459 1458 the ESC character. ASCII 29 was chosen for historical merit because
1460 1459 this is the character used by 'telnet' as the escape character. The
1461 1460 escape_character will not be sent to the child process.
1462 1461
1463 1462 You may pass in optional input and output filter functions. These
1464 1463 functions should take a string and return a string. The output_filter
1465 1464 will be passed all the output from the child process. The input_filter
1466 1465 will be passed all the keyboard input from the user. The input_filter
1467 1466 is run BEFORE the check for the escape_character.
1468 1467
1469 1468 Note that if you change the window size of the parent the SIGWINCH
1470 1469 signal will not be passed through to the child. If you want the child
1471 1470 window size to change when the parent's window size changes then do
1472 1471 something like the following example::
1473 1472
1474 1473 import pexpect, struct, fcntl, termios, signal, sys
1475 1474 def sigwinch_passthrough (sig, data):
1476 1475 s = struct.pack("HHHH", 0, 0, 0, 0)
1477 1476 a = struct.unpack('hhhh', fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ , s))
1478 1477 global p
1479 1478 p.setwinsize(a[0],a[1])
1480 1479 p = pexpect.spawn('/bin/bash') # Note this is global and used in sigwinch_passthrough.
1481 1480 signal.signal(signal.SIGWINCH, sigwinch_passthrough)
1482 1481 p.interact()
1483 1482 """
1484 1483
1485 1484 # Flush the buffer.
1486 1485 self.stdout.write (self.buffer)
1487 1486 self.stdout.flush()
1488 1487 self.buffer = ''
1489 1488 mode = tty.tcgetattr(self.STDIN_FILENO)
1490 1489 tty.setraw(self.STDIN_FILENO)
1491 1490 try:
1492 1491 self.__interact_copy(escape_character, input_filter, output_filter)
1493 1492 finally:
1494 1493 tty.tcsetattr(self.STDIN_FILENO, tty.TCSAFLUSH, mode)
1495 1494
1496 1495 def __interact_writen(self, fd, data):
1497 1496
1498 1497 """This is used by the interact() method.
1499 1498 """
1500 1499
1501 1500 while data != '' and self.isalive():
1502 1501 n = os.write(fd, data)
1503 1502 data = data[n:]
1504 1503
1505 1504 def __interact_read(self, fd):
1506 1505
1507 1506 """This is used by the interact() method.
1508 1507 """
1509 1508
1510 1509 return os.read(fd, 1000)
1511 1510
1512 1511 def __interact_copy(self, escape_character = None, input_filter = None, output_filter = None):
1513 1512
1514 1513 """This is used by the interact() method.
1515 1514 """
1516 1515
1517 1516 while self.isalive():
1518 1517 r,w,e = self.__select([self.child_fd, self.STDIN_FILENO], [], [])
1519 1518 if self.child_fd in r:
1520 1519 data = self.__interact_read(self.child_fd)
1521 1520 if output_filter: data = output_filter(data)
1522 1521 if self.logfile is not None:
1523 1522 self.logfile.write (data)
1524 1523 self.logfile.flush()
1525 1524 os.write(self.STDOUT_FILENO, data)
1526 1525 if self.STDIN_FILENO in r:
1527 1526 data = self.__interact_read(self.STDIN_FILENO)
1528 1527 if input_filter: data = input_filter(data)
1529 1528 i = data.rfind(escape_character)
1530 1529 if i != -1:
1531 1530 data = data[:i]
1532 1531 self.__interact_writen(self.child_fd, data)
1533 1532 break
1534 1533 self.__interact_writen(self.child_fd, data)
1535 1534
1536 1535 def __select (self, iwtd, owtd, ewtd, timeout=None):
1537 1536
1538 1537 """This is a wrapper around select.select() that ignores signals. If
1539 1538 select.select raises a select.error exception and errno is an EINTR
1540 1539 error then it is ignored. Mainly this is used to ignore sigwinch
1541 1540 (terminal resize). """
1542 1541
1543 1542 # if select() is interrupted by a signal (errno==EINTR) then
1544 1543 # we loop back and enter the select() again.
1545 1544 if timeout is not None:
1546 1545 end_time = time.time() + timeout
1547 1546 while True:
1548 1547 try:
1549 1548 return select.select (iwtd, owtd, ewtd, timeout)
1550 1549 except select.error, e:
1551 1550 if e[0] == errno.EINTR:
1552 1551 # if we loop back we have to subtract the amount of time we already waited.
1553 1552 if timeout is not None:
1554 1553 timeout = end_time - time.time()
1555 1554 if timeout < 0:
1556 1555 return ([],[],[])
1557 1556 else: # something else caused the select.error, so this really is an exception
1558 1557 raise
1559 1558
1560 1559 ##############################################################################
1561 1560 # The following methods are no longer supported or allowed.
1562 1561
1563 1562 def setmaxread (self, maxread):
1564 1563
1565 1564 """This method is no longer supported or allowed. I don't like getters
1566 1565 and setters without a good reason. """
1567 1566
1568 1567 raise ExceptionPexpect ('This method is no longer supported or allowed. Just assign a value to the maxread member variable.')
1569 1568
1570 1569 def setlog (self, fileobject):
1571 1570
1572 1571 """This method is no longer supported or allowed.
1573 1572 """
1574 1573
1575 1574 raise ExceptionPexpect ('This method is no longer supported or allowed. Just assign a value to the logfile member variable.')
1576 1575
1577 1576 ##############################################################################
1578 1577 # End of spawn class
1579 1578 ##############################################################################
1580 1579
1581 1580 class searcher_string (object):
1582 1581
1583 1582 """This is a plain string search helper for the spawn.expect_any() method.
1584 1583
1585 1584 Attributes:
1586 1585
1587 1586 eof_index - index of EOF, or -1
1588 1587 timeout_index - index of TIMEOUT, or -1
1589 1588
1590 1589 After a successful match by the search() method the following attributes
1591 1590 are available:
1592 1591
1593 1592 start - index into the buffer, first byte of match
1594 1593 end - index into the buffer, first byte after match
1595 1594 match - the matching string itself
1596 1595 """
1597 1596
1598 1597 def __init__(self, strings):
1599 1598
1600 1599 """This creates an instance of searcher_string. This argument 'strings'
1601 1600 may be a list; a sequence of strings; or the EOF or TIMEOUT types. """
1602 1601
1603 1602 self.eof_index = -1
1604 1603 self.timeout_index = -1
1605 1604 self._strings = []
1606 1605 for n, s in zip(range(len(strings)), strings):
1607 1606 if s is EOF:
1608 1607 self.eof_index = n
1609 1608 continue
1610 1609 if s is TIMEOUT:
1611 1610 self.timeout_index = n
1612 1611 continue
1613 1612 self._strings.append((n, s))
1614 1613
1615 1614 def __str__(self):
1616 1615
1617 1616 """This returns a human-readable string that represents the state of
1618 1617 the object."""
1619 1618
1620 1619 ss = [ (ns[0],' %d: "%s"' % ns) for ns in self._strings ]
1621 1620 ss.append((-1,'searcher_string:'))
1622 1621 if self.eof_index >= 0:
1623 1622 ss.append ((self.eof_index,' %d: EOF' % self.eof_index))
1624 1623 if self.timeout_index >= 0:
1625 1624 ss.append ((self.timeout_index,' %d: TIMEOUT' % self.timeout_index))
1626 1625 ss.sort()
1627 1626 ss = zip(*ss)[1]
1628 1627 return '\n'.join(ss)
1629 1628
1630 1629 def search(self, buffer, freshlen, searchwindowsize=None):
1631 1630
1632 1631 """This searches 'buffer' for the first occurence of one of the search
1633 1632 strings. 'freshlen' must indicate the number of bytes at the end of
1634 1633 'buffer' which have not been searched before. It helps to avoid
1635 1634 searching the same, possibly big, buffer over and over again.
1636 1635
1637 1636 See class spawn for the 'searchwindowsize' argument.
1638 1637
1639 1638 If there is a match this returns the index of that string, and sets
1640 1639 'start', 'end' and 'match'. Otherwise, this returns -1. """
1641 1640
1642 1641 absurd_match = len(buffer)
1643 1642 first_match = absurd_match
1644 1643
1645 1644 # 'freshlen' helps a lot here. Further optimizations could
1646 1645 # possibly include:
1647 1646 #
1648 1647 # using something like the Boyer-Moore Fast String Searching
1649 1648 # Algorithm; pre-compiling the search through a list of
1650 1649 # strings into something that can scan the input once to
1651 1650 # search for all N strings; realize that if we search for
1652 1651 # ['bar', 'baz'] and the input is '...foo' we need not bother
1653 1652 # rescanning until we've read three more bytes.
1654 1653 #
1655 1654 # Sadly, I don't know enough about this interesting topic. /grahn
1656 1655
1657 1656 for index, s in self._strings:
1658 1657 if searchwindowsize is None:
1659 1658 # the match, if any, can only be in the fresh data,
1660 1659 # or at the very end of the old data
1661 1660 offset = -(freshlen+len(s))
1662 1661 else:
1663 1662 # better obey searchwindowsize
1664 1663 offset = -searchwindowsize
1665 1664 n = buffer.find(s, offset)
1666 1665 if n >= 0 and n < first_match:
1667 1666 first_match = n
1668 1667 best_index, best_match = index, s
1669 1668 if first_match == absurd_match:
1670 1669 return -1
1671 1670 self.match = best_match
1672 1671 self.start = first_match
1673 1672 self.end = self.start + len(self.match)
1674 1673 return best_index
1675 1674
1676 1675 class searcher_re (object):
1677 1676
1678 1677 """This is regular expression string search helper for the
1679 1678 spawn.expect_any() method.
1680 1679
1681 1680 Attributes:
1682 1681
1683 1682 eof_index - index of EOF, or -1
1684 1683 timeout_index - index of TIMEOUT, or -1
1685 1684
1686 1685 After a successful match by the search() method the following attributes
1687 1686 are available:
1688 1687
1689 1688 start - index into the buffer, first byte of match
1690 1689 end - index into the buffer, first byte after match
1691 1690 match - the re.match object returned by a succesful re.search
1692 1691
1693 1692 """
1694 1693
1695 1694 def __init__(self, patterns):
1696 1695
1697 1696 """This creates an instance that searches for 'patterns' Where
1698 1697 'patterns' may be a list or other sequence of compiled regular
1699 1698 expressions, or the EOF or TIMEOUT types."""
1700 1699
1701 1700 self.eof_index = -1
1702 1701 self.timeout_index = -1
1703 1702 self._searches = []
1704 1703 for n, s in zip(range(len(patterns)), patterns):
1705 1704 if s is EOF:
1706 1705 self.eof_index = n
1707 1706 continue
1708 1707 if s is TIMEOUT:
1709 1708 self.timeout_index = n
1710 1709 continue
1711 1710 self._searches.append((n, s))
1712 1711
1713 1712 def __str__(self):
1714 1713
1715 1714 """This returns a human-readable string that represents the state of
1716 1715 the object."""
1717 1716
1718 1717 ss = [ (n,' %d: re.compile("%s")' % (n,str(s.pattern))) for n,s in self._searches]
1719 1718 ss.append((-1,'searcher_re:'))
1720 1719 if self.eof_index >= 0:
1721 1720 ss.append ((self.eof_index,' %d: EOF' % self.eof_index))
1722 1721 if self.timeout_index >= 0:
1723 1722 ss.append ((self.timeout_index,' %d: TIMEOUT' % self.timeout_index))
1724 1723 ss.sort()
1725 1724 ss = zip(*ss)[1]
1726 1725 return '\n'.join(ss)
1727 1726
1728 1727 def search(self, buffer, freshlen, searchwindowsize=None):
1729 1728
1730 1729 """This searches 'buffer' for the first occurence of one of the regular
1731 1730 expressions. 'freshlen' must indicate the number of bytes at the end of
1732 1731 'buffer' which have not been searched before.
1733 1732
1734 1733 See class spawn for the 'searchwindowsize' argument.
1735 1734
1736 1735 If there is a match this returns the index of that string, and sets
1737 1736 'start', 'end' and 'match'. Otherwise, returns -1."""
1738 1737
1739 1738 absurd_match = len(buffer)
1740 1739 first_match = absurd_match
1741 1740 # 'freshlen' doesn't help here -- we cannot predict the
1742 1741 # length of a match, and the re module provides no help.
1743 1742 if searchwindowsize is None:
1744 1743 searchstart = 0
1745 1744 else:
1746 1745 searchstart = max(0, len(buffer)-searchwindowsize)
1747 1746 for index, s in self._searches:
1748 1747 match = s.search(buffer, searchstart)
1749 1748 if match is None:
1750 1749 continue
1751 1750 n = match.start()
1752 1751 if n < first_match:
1753 1752 first_match = n
1754 1753 the_match = match
1755 1754 best_index = index
1756 1755 if first_match == absurd_match:
1757 1756 return -1
1758 1757 self.start = first_match
1759 1758 self.match = the_match
1760 1759 self.end = self.match.end()
1761 1760 return best_index
1762 1761
1763 1762 def which (filename):
1764 1763
1765 1764 """This takes a given filename; tries to find it in the environment path;
1766 1765 then checks if it is executable. This returns the full path to the filename
1767 1766 if found and executable. Otherwise this returns None."""
1768 1767
1769 1768 # Special case where filename already contains a path.
1770 1769 if os.path.dirname(filename) != '':
1771 1770 if os.access (filename, os.X_OK):
1772 1771 return filename
1773 1772
1774 1773 if not os.environ.has_key('PATH') or os.environ['PATH'] == '':
1775 1774 p = os.defpath
1776 1775 else:
1777 1776 p = os.environ['PATH']
1778 1777
1779 1778 # Oddly enough this was the one line that made Pexpect
1780 1779 # incompatible with Python 1.5.2.
1781 #pathlist = p.split (os.pathsep)
1782 pathlist = string.split (p, os.pathsep)
1780 pathlist = p.split(os.pathsep)
1783 1781
1784 1782 for path in pathlist:
1785 1783 f = os.path.join(path, filename)
1786 1784 if os.access(f, os.X_OK):
1787 1785 return f
1788 1786 return None
1789 1787
1790 1788 def split_command_line(command_line):
1791 1789
1792 1790 """This splits a command line into a list of arguments. It splits arguments
1793 1791 on spaces, but handles embedded quotes, doublequotes, and escaped
1794 1792 characters. It's impossible to do this with a regular expression, so I
1795 1793 wrote a little state machine to parse the command line. """
1796 1794
1797 1795 arg_list = []
1798 1796 arg = ''
1799 1797
1800 1798 # Constants to name the states we can be in.
1801 1799 state_basic = 0
1802 1800 state_esc = 1
1803 1801 state_singlequote = 2
1804 1802 state_doublequote = 3
1805 1803 state_whitespace = 4 # The state of consuming whitespace between commands.
1806 1804 state = state_basic
1807 1805
1808 1806 for c in command_line:
1809 1807 if state == state_basic or state == state_whitespace:
1810 1808 if c == '\\': # Escape the next character
1811 1809 state = state_esc
1812 1810 elif c == r"'": # Handle single quote
1813 1811 state = state_singlequote
1814 1812 elif c == r'"': # Handle double quote
1815 1813 state = state_doublequote
1816 1814 elif c.isspace():
1817 1815 # Add arg to arg_list if we aren't in the middle of whitespace.
1818 1816 if state == state_whitespace:
1819 1817 None # Do nothing.
1820 1818 else:
1821 1819 arg_list.append(arg)
1822 1820 arg = ''
1823 1821 state = state_whitespace
1824 1822 else:
1825 1823 arg = arg + c
1826 1824 state = state_basic
1827 1825 elif state == state_esc:
1828 1826 arg = arg + c
1829 1827 state = state_basic
1830 1828 elif state == state_singlequote:
1831 1829 if c == r"'":
1832 1830 state = state_basic
1833 1831 else:
1834 1832 arg = arg + c
1835 1833 elif state == state_doublequote:
1836 1834 if c == r'"':
1837 1835 state = state_basic
1838 1836 else:
1839 1837 arg = arg + c
1840 1838
1841 1839 if arg != '':
1842 1840 arg_list.append(arg)
1843 1841 return arg_list
1844 1842
1845 1843 # vi:ts=4:sw=4:expandtab:ft=python:
General Comments 0
You need to be logged in to leave comments. Login now