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