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