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