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