Show More
@@ -1,1609 +1,1645 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | General purpose utilities. |
|
4 | 4 | |
|
5 | 5 | This is a grab-bag of stuff I find useful in most programs I write. Some of |
|
6 | 6 | these things are also convenient when working at the command line. |
|
7 | 7 | |
|
8 |
$Id: genutils.py 96 |
|
|
8 | $Id: genutils.py 967 2005-12-29 09:02:13Z fperez $""" | |
|
9 | 9 | |
|
10 | 10 | #***************************************************************************** |
|
11 | 11 | # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu> |
|
12 | 12 | # |
|
13 | 13 | # Distributed under the terms of the BSD License. The full license is in |
|
14 | 14 | # the file COPYING, distributed as part of this software. |
|
15 | 15 | #***************************************************************************** |
|
16 | 16 | |
|
17 | 17 | from __future__ import generators # 2.2 compatibility |
|
18 | 18 | |
|
19 | 19 | from IPython import Release |
|
20 | 20 | __author__ = '%s <%s>' % Release.authors['Fernando'] |
|
21 | 21 | __license__ = Release.license |
|
22 | 22 | |
|
23 | 23 | #**************************************************************************** |
|
24 | 24 | # required modules from the Python standard library |
|
25 | 25 | import __main__ |
|
26 | 26 | import commands |
|
27 | 27 | import os |
|
28 | 28 | import re |
|
29 | 29 | import shlex |
|
30 | 30 | import shutil |
|
31 | 31 | import sys |
|
32 | 32 | import tempfile |
|
33 | 33 | import time |
|
34 | 34 | import types |
|
35 | 35 | |
|
36 | 36 | # Other IPython utilities |
|
37 | 37 | from IPython.Itpl import Itpl,itpl,printpl |
|
38 | 38 | from IPython import DPyGetOpt |
|
39 | 39 | |
|
40 | 40 | # Build objects which appeared in Python 2.3 for 2.2, to make ipython |
|
41 | 41 | # 2.2-friendly |
|
42 | 42 | try: |
|
43 | 43 | basestring |
|
44 | 44 | except NameError: |
|
45 | 45 | import types |
|
46 | 46 | basestring = (types.StringType, types.UnicodeType) |
|
47 | 47 | True = 1==1 |
|
48 | 48 | False = 1==0 |
|
49 | 49 | |
|
50 | 50 | def enumerate(obj): |
|
51 | 51 | i = -1 |
|
52 | 52 | for item in obj: |
|
53 | 53 | i += 1 |
|
54 | 54 | yield i, item |
|
55 | 55 | |
|
56 | 56 | # add these to the builtin namespace, so that all modules find them |
|
57 | 57 | import __builtin__ |
|
58 | 58 | __builtin__.basestring = basestring |
|
59 | 59 | __builtin__.True = True |
|
60 | 60 | __builtin__.False = False |
|
61 | 61 | __builtin__.enumerate = enumerate |
|
62 | 62 | |
|
63 | 63 | # Try to use shlex.split for converting an input string into a sys.argv-type |
|
64 | 64 | # list. This appeared in Python 2.3, so here's a quick backport for 2.2. |
|
65 | 65 | try: |
|
66 | 66 | shlex_split = shlex.split |
|
67 | 67 | except AttributeError: |
|
68 | 68 | _quotesre = re.compile(r'[\'"](.*)[\'"]') |
|
69 | 69 | _wordchars = ('abcdfeghijklmnopqrstuvwxyz' |
|
70 | 70 | 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.~*?' |
|
71 | 71 | 'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ' |
|
72 | 72 | 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ%s' |
|
73 | 73 | % os.sep) |
|
74 | 74 | |
|
75 | 75 | def shlex_split(s): |
|
76 | 76 | """Simplified backport to Python 2.2 of shlex.split(). |
|
77 | 77 | |
|
78 | 78 | This is a quick and dirty hack, since the shlex module under 2.2 lacks |
|
79 | 79 | several of the features needed to really match the functionality of |
|
80 | 80 | shlex.split() in 2.3.""" |
|
81 | 81 | |
|
82 | 82 | lex = shlex.shlex(StringIO(s)) |
|
83 | 83 | # Try to get options, extensions and path separators as characters |
|
84 | 84 | lex.wordchars = _wordchars |
|
85 | 85 | lex.commenters = '' |
|
86 | 86 | # Make a list out of the lexer by hand, since in 2.2 it's not an |
|
87 | 87 | # iterator. |
|
88 | 88 | lout = [] |
|
89 | 89 | while 1: |
|
90 | 90 | token = lex.get_token() |
|
91 | 91 | if token == '': |
|
92 | 92 | break |
|
93 | 93 | # Try to handle quoted tokens correctly |
|
94 | 94 | quotes = _quotesre.match(token) |
|
95 | 95 | if quotes: |
|
96 | 96 | token = quotes.group(1) |
|
97 | 97 | lout.append(token) |
|
98 | 98 | return lout |
|
99 | 99 | |
|
100 | 100 | #**************************************************************************** |
|
101 | 101 | # Exceptions |
|
102 | 102 | class Error(Exception): |
|
103 | 103 | """Base class for exceptions in this module.""" |
|
104 | 104 | pass |
|
105 | 105 | |
|
106 | 106 | #---------------------------------------------------------------------------- |
|
107 | 107 | class IOStream: |
|
108 | 108 | def __init__(self,stream,fallback): |
|
109 | 109 | if not hasattr(stream,'write') or not hasattr(stream,'flush'): |
|
110 | 110 | stream = fallback |
|
111 | 111 | self.stream = stream |
|
112 | 112 | self._swrite = stream.write |
|
113 | 113 | self.flush = stream.flush |
|
114 | 114 | |
|
115 | 115 | def write(self,data): |
|
116 | 116 | try: |
|
117 | 117 | self._swrite(data) |
|
118 | 118 | except: |
|
119 | 119 | try: |
|
120 | 120 | # print handles some unicode issues which may trip a plain |
|
121 | 121 | # write() call. Attempt to emulate write() by using a |
|
122 | 122 | # trailing comma |
|
123 | 123 | print >> self.stream, data, |
|
124 | 124 | except: |
|
125 | 125 | # if we get here, something is seriously broken. |
|
126 | 126 | print >> sys.stderr, \ |
|
127 | 127 | 'ERROR - failed to write data to stream:', stream |
|
128 | 128 | |
|
129 | 129 | class IOTerm: |
|
130 | 130 | """ Term holds the file or file-like objects for handling I/O operations. |
|
131 | 131 | |
|
132 | 132 | These are normally just sys.stdin, sys.stdout and sys.stderr but for |
|
133 | 133 | Windows they can can replaced to allow editing the strings before they are |
|
134 | 134 | displayed.""" |
|
135 | 135 | |
|
136 | 136 | # In the future, having IPython channel all its I/O operations through |
|
137 | 137 | # this class will make it easier to embed it into other environments which |
|
138 | 138 | # are not a normal terminal (such as a GUI-based shell) |
|
139 | 139 | def __init__(self,cin=None,cout=None,cerr=None): |
|
140 | 140 | self.cin = IOStream(cin,sys.stdin) |
|
141 | 141 | self.cout = IOStream(cout,sys.stdout) |
|
142 | 142 | self.cerr = IOStream(cerr,sys.stderr) |
|
143 | 143 | |
|
144 | 144 | # Global variable to be used for all I/O |
|
145 | 145 | Term = IOTerm() |
|
146 | 146 | |
|
147 | 147 | # Windows-specific code to load Gary Bishop's readline and configure it |
|
148 | 148 | # automatically for the users |
|
149 | 149 | # Note: os.name on cygwin returns posix, so this should only pick up 'native' |
|
150 | 150 | # windows. Cygwin returns 'cygwin' for sys.platform. |
|
151 | 151 | if os.name == 'nt': |
|
152 | 152 | try: |
|
153 | 153 | import readline |
|
154 | 154 | except ImportError: |
|
155 | 155 | pass |
|
156 | 156 | else: |
|
157 | 157 | try: |
|
158 | 158 | _out = readline.GetOutputFile() |
|
159 | 159 | except AttributeError: |
|
160 | 160 | pass |
|
161 | 161 | else: |
|
162 | 162 | # Remake Term to use the readline i/o facilities |
|
163 | 163 | Term = IOTerm(cout=_out,cerr=_out) |
|
164 | 164 | del _out |
|
165 | 165 | |
|
166 | 166 | #**************************************************************************** |
|
167 | 167 | # Generic warning/error printer, used by everything else |
|
168 | 168 | def warn(msg,level=2,exit_val=1): |
|
169 | 169 | """Standard warning printer. Gives formatting consistency. |
|
170 | 170 | |
|
171 | 171 | Output is sent to Term.cerr (sys.stderr by default). |
|
172 | 172 | |
|
173 | 173 | Options: |
|
174 | 174 | |
|
175 | 175 | -level(2): allows finer control: |
|
176 | 176 | 0 -> Do nothing, dummy function. |
|
177 | 177 | 1 -> Print message. |
|
178 | 178 | 2 -> Print 'WARNING:' + message. (Default level). |
|
179 | 179 | 3 -> Print 'ERROR:' + message. |
|
180 | 180 | 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val). |
|
181 | 181 | |
|
182 | 182 | -exit_val (1): exit value returned by sys.exit() for a level 4 |
|
183 | 183 | warning. Ignored for all other levels.""" |
|
184 | 184 | |
|
185 | 185 | if level>0: |
|
186 | 186 | header = ['','','WARNING: ','ERROR: ','FATAL ERROR: '] |
|
187 | 187 | print >> Term.cerr, '%s%s' % (header[level],msg) |
|
188 | 188 | if level == 4: |
|
189 | 189 | print >> Term.cerr,'Exiting.\n' |
|
190 | 190 | sys.exit(exit_val) |
|
191 | 191 | |
|
192 | 192 | def info(msg): |
|
193 | 193 | """Equivalent to warn(msg,level=1).""" |
|
194 | 194 | |
|
195 | 195 | warn(msg,level=1) |
|
196 | 196 | |
|
197 | 197 | def error(msg): |
|
198 | 198 | """Equivalent to warn(msg,level=3).""" |
|
199 | 199 | |
|
200 | 200 | warn(msg,level=3) |
|
201 | 201 | |
|
202 | 202 | def fatal(msg,exit_val=1): |
|
203 | 203 | """Equivalent to warn(msg,exit_val=exit_val,level=4).""" |
|
204 | 204 | |
|
205 | 205 | warn(msg,exit_val=exit_val,level=4) |
|
206 | 206 | |
|
207 | 207 | #---------------------------------------------------------------------------- |
|
208 | 208 | StringTypes = types.StringTypes |
|
209 | 209 | |
|
210 | 210 | # Basic timing functionality |
|
211 | 211 | |
|
212 | 212 | # If possible (Unix), use the resource module instead of time.clock() |
|
213 | 213 | try: |
|
214 | 214 | import resource |
|
215 | 215 | def clock(): |
|
216 | 216 | """clock() -> floating point number |
|
217 | 217 | |
|
218 | 218 | Return the CPU time in seconds (user time only, system time is |
|
219 | 219 | ignored) since the start of the process. This is done via a call to |
|
220 | 220 | resource.getrusage, so it avoids the wraparound problems in |
|
221 | 221 | time.clock().""" |
|
222 | 222 | |
|
223 | 223 | return resource.getrusage(resource.RUSAGE_SELF)[0] |
|
224 | 224 | |
|
225 | 225 | def clock2(): |
|
226 | 226 | """clock2() -> (t_user,t_system) |
|
227 | 227 | |
|
228 | 228 | Similar to clock(), but return a tuple of user/system times.""" |
|
229 | 229 | return resource.getrusage(resource.RUSAGE_SELF)[:2] |
|
230 | 230 | |
|
231 | 231 | except ImportError: |
|
232 | 232 | clock = time.clock |
|
233 | 233 | def clock2(): |
|
234 | 234 | """Under windows, system CPU time can't be measured. |
|
235 | 235 | |
|
236 | 236 | This just returns clock() and zero.""" |
|
237 | 237 | return time.clock(),0.0 |
|
238 | 238 | |
|
239 | 239 | def timings_out(reps,func,*args,**kw): |
|
240 | 240 | """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output) |
|
241 | 241 | |
|
242 | 242 | Execute a function reps times, return a tuple with the elapsed total |
|
243 | 243 | CPU time in seconds, the time per call and the function's output. |
|
244 | 244 | |
|
245 | 245 | Under Unix, the return value is the sum of user+system time consumed by |
|
246 | 246 | the process, computed via the resource module. This prevents problems |
|
247 | 247 | related to the wraparound effect which the time.clock() function has. |
|
248 | 248 | |
|
249 | 249 | Under Windows the return value is in wall clock seconds. See the |
|
250 | 250 | documentation for the time module for more details.""" |
|
251 | 251 | |
|
252 | 252 | reps = int(reps) |
|
253 | 253 | assert reps >=1, 'reps must be >= 1' |
|
254 | 254 | if reps==1: |
|
255 | 255 | start = clock() |
|
256 | 256 | out = func(*args,**kw) |
|
257 | 257 | tot_time = clock()-start |
|
258 | 258 | else: |
|
259 | 259 | rng = xrange(reps-1) # the last time is executed separately to store output |
|
260 | 260 | start = clock() |
|
261 | 261 | for dummy in rng: func(*args,**kw) |
|
262 | 262 | out = func(*args,**kw) # one last time |
|
263 | 263 | tot_time = clock()-start |
|
264 | 264 | av_time = tot_time / reps |
|
265 | 265 | return tot_time,av_time,out |
|
266 | 266 | |
|
267 | 267 | def timings(reps,func,*args,**kw): |
|
268 | 268 | """timings(reps,func,*args,**kw) -> (t_total,t_per_call) |
|
269 | 269 | |
|
270 | 270 | Execute a function reps times, return a tuple with the elapsed total CPU |
|
271 | 271 | time in seconds and the time per call. These are just the first two values |
|
272 | 272 | in timings_out().""" |
|
273 | 273 | |
|
274 | 274 | return timings_out(reps,func,*args,**kw)[0:2] |
|
275 | 275 | |
|
276 | 276 | def timing(func,*args,**kw): |
|
277 | 277 | """timing(func,*args,**kw) -> t_total |
|
278 | 278 | |
|
279 | 279 | Execute a function once, return the elapsed total CPU time in |
|
280 | 280 | seconds. This is just the first value in timings_out().""" |
|
281 | 281 | |
|
282 | 282 | return timings_out(1,func,*args,**kw)[0] |
|
283 | 283 | |
|
284 | 284 | #**************************************************************************** |
|
285 | 285 | # file and system |
|
286 | 286 | |
|
287 | 287 | def system(cmd,verbose=0,debug=0,header=''): |
|
288 | 288 | """Execute a system command, return its exit status. |
|
289 | 289 | |
|
290 | 290 | Options: |
|
291 | 291 | |
|
292 | 292 | - verbose (0): print the command to be executed. |
|
293 | 293 | |
|
294 | 294 | - debug (0): only print, do not actually execute. |
|
295 | 295 | |
|
296 | 296 | - header (''): Header to print on screen prior to the executed command (it |
|
297 | 297 | is only prepended to the command, no newlines are added). |
|
298 | 298 | |
|
299 | 299 | Note: a stateful version of this function is available through the |
|
300 | 300 | SystemExec class.""" |
|
301 | 301 | |
|
302 | 302 | stat = 0 |
|
303 | 303 | if verbose or debug: print header+cmd |
|
304 | 304 | sys.stdout.flush() |
|
305 | 305 | if not debug: stat = os.system(cmd) |
|
306 | 306 | return stat |
|
307 | 307 | |
|
308 | 308 | def shell(cmd,verbose=0,debug=0,header=''): |
|
309 | 309 | """Execute a command in the system shell, always return None. |
|
310 | 310 | |
|
311 | 311 | Options: |
|
312 | 312 | |
|
313 | 313 | - verbose (0): print the command to be executed. |
|
314 | 314 | |
|
315 | 315 | - debug (0): only print, do not actually execute. |
|
316 | 316 | |
|
317 | 317 | - header (''): Header to print on screen prior to the executed command (it |
|
318 | 318 | is only prepended to the command, no newlines are added). |
|
319 | 319 | |
|
320 | 320 | Note: this is similar to genutils.system(), but it returns None so it can |
|
321 | 321 | be conveniently used in interactive loops without getting the return value |
|
322 | 322 | (typically 0) printed many times.""" |
|
323 | 323 | |
|
324 | 324 | stat = 0 |
|
325 | 325 | if verbose or debug: print header+cmd |
|
326 | 326 | # flush stdout so we don't mangle python's buffering |
|
327 | 327 | sys.stdout.flush() |
|
328 | 328 | if not debug: |
|
329 | 329 | os.system(cmd) |
|
330 | 330 | |
|
331 | 331 | def getoutput(cmd,verbose=0,debug=0,header='',split=0): |
|
332 | 332 | """Dummy substitute for perl's backquotes. |
|
333 | 333 | |
|
334 | 334 | Executes a command and returns the output. |
|
335 | 335 | |
|
336 | 336 | Accepts the same arguments as system(), plus: |
|
337 | 337 | |
|
338 | 338 | - split(0): if true, the output is returned as a list split on newlines. |
|
339 | 339 | |
|
340 | 340 | Note: a stateful version of this function is available through the |
|
341 | 341 | SystemExec class.""" |
|
342 | 342 | |
|
343 | 343 | if verbose or debug: print header+cmd |
|
344 | 344 | if not debug: |
|
345 | 345 | output = commands.getoutput(cmd) |
|
346 | 346 | if split: |
|
347 | 347 | return output.split('\n') |
|
348 | 348 | else: |
|
349 | 349 | return output |
|
350 | 350 | |
|
351 | 351 | def getoutputerror(cmd,verbose=0,debug=0,header='',split=0): |
|
352 | 352 | """Return (standard output,standard error) of executing cmd in a shell. |
|
353 | 353 | |
|
354 | 354 | Accepts the same arguments as system(), plus: |
|
355 | 355 | |
|
356 | 356 | - split(0): if true, each of stdout/err is returned as a list split on |
|
357 | 357 | newlines. |
|
358 | 358 | |
|
359 | 359 | Note: a stateful version of this function is available through the |
|
360 | 360 | SystemExec class.""" |
|
361 | 361 | |
|
362 | 362 | if verbose or debug: print header+cmd |
|
363 | 363 | if not cmd: |
|
364 | 364 | if split: |
|
365 | 365 | return [],[] |
|
366 | 366 | else: |
|
367 | 367 | return '','' |
|
368 | 368 | if not debug: |
|
369 | 369 | pin,pout,perr = os.popen3(cmd) |
|
370 | 370 | tout = pout.read().rstrip() |
|
371 | 371 | terr = perr.read().rstrip() |
|
372 | 372 | pin.close() |
|
373 | 373 | pout.close() |
|
374 | 374 | perr.close() |
|
375 | 375 | if split: |
|
376 | 376 | return tout.split('\n'),terr.split('\n') |
|
377 | 377 | else: |
|
378 | 378 | return tout,terr |
|
379 | 379 | |
|
380 | 380 | # for compatibility with older naming conventions |
|
381 | 381 | xsys = system |
|
382 | 382 | bq = getoutput |
|
383 | 383 | |
|
384 | 384 | class SystemExec: |
|
385 | 385 | """Access the system and getoutput functions through a stateful interface. |
|
386 | 386 | |
|
387 | 387 | Note: here we refer to the system and getoutput functions from this |
|
388 | 388 | library, not the ones from the standard python library. |
|
389 | 389 | |
|
390 | 390 | This class offers the system and getoutput functions as methods, but the |
|
391 | 391 | verbose, debug and header parameters can be set for the instance (at |
|
392 | 392 | creation time or later) so that they don't need to be specified on each |
|
393 | 393 | call. |
|
394 | 394 | |
|
395 | 395 | For efficiency reasons, there's no way to override the parameters on a |
|
396 | 396 | per-call basis other than by setting instance attributes. If you need |
|
397 | 397 | local overrides, it's best to directly call system() or getoutput(). |
|
398 | 398 | |
|
399 | 399 | The following names are provided as alternate options: |
|
400 | 400 | - xsys: alias to system |
|
401 | 401 | - bq: alias to getoutput |
|
402 | 402 | |
|
403 | 403 | An instance can then be created as: |
|
404 | 404 | >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ') |
|
405 | 405 | |
|
406 | 406 | And used as: |
|
407 | 407 | >>> sysexec.xsys('pwd') |
|
408 | 408 | >>> dirlist = sysexec.bq('ls -l') |
|
409 | 409 | """ |
|
410 | 410 | |
|
411 | 411 | def __init__(self,verbose=0,debug=0,header='',split=0): |
|
412 | 412 | """Specify the instance's values for verbose, debug and header.""" |
|
413 | 413 | setattr_list(self,'verbose debug header split') |
|
414 | 414 | |
|
415 | 415 | def system(self,cmd): |
|
416 | 416 | """Stateful interface to system(), with the same keyword parameters.""" |
|
417 | 417 | |
|
418 | 418 | system(cmd,self.verbose,self.debug,self.header) |
|
419 | 419 | |
|
420 | 420 | def shell(self,cmd): |
|
421 | 421 | """Stateful interface to shell(), with the same keyword parameters.""" |
|
422 | 422 | |
|
423 | 423 | shell(cmd,self.verbose,self.debug,self.header) |
|
424 | 424 | |
|
425 | 425 | xsys = system # alias |
|
426 | 426 | |
|
427 | 427 | def getoutput(self,cmd): |
|
428 | 428 | """Stateful interface to getoutput().""" |
|
429 | 429 | |
|
430 | 430 | return getoutput(cmd,self.verbose,self.debug,self.header,self.split) |
|
431 | 431 | |
|
432 | 432 | def getoutputerror(self,cmd): |
|
433 | 433 | """Stateful interface to getoutputerror().""" |
|
434 | 434 | |
|
435 | 435 | return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split) |
|
436 | 436 | |
|
437 | 437 | bq = getoutput # alias |
|
438 | 438 | |
|
439 | 439 | #----------------------------------------------------------------------------- |
|
440 | 440 | def mutex_opts(dict,ex_op): |
|
441 | 441 | """Check for presence of mutually exclusive keys in a dict. |
|
442 | 442 | |
|
443 | 443 | Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]""" |
|
444 | 444 | for op1,op2 in ex_op: |
|
445 | 445 | if op1 in dict and op2 in dict: |
|
446 | 446 | raise ValueError,'\n*** ERROR in Arguments *** '\ |
|
447 | 447 | 'Options '+op1+' and '+op2+' are mutually exclusive.' |
|
448 | 448 | |
|
449 | 449 | #----------------------------------------------------------------------------- |
|
450 | 450 | def get_py_filename(name): |
|
451 | 451 | """Return a valid python filename in the current directory. |
|
452 | 452 | |
|
453 | 453 | If the given name is not a file, it adds '.py' and searches again. |
|
454 | 454 | Raises IOError with an informative message if the file isn't found.""" |
|
455 | 455 | |
|
456 | 456 | name = os.path.expanduser(name) |
|
457 | 457 | if not os.path.isfile(name) and not name.endswith('.py'): |
|
458 | 458 | name += '.py' |
|
459 | 459 | if os.path.isfile(name): |
|
460 | 460 | return name |
|
461 | 461 | else: |
|
462 | 462 | raise IOError,'File `%s` not found.' % name |
|
463 | 463 | |
|
464 | 464 | #----------------------------------------------------------------------------- |
|
465 | 465 | def filefind(fname,alt_dirs = None): |
|
466 | 466 | """Return the given filename either in the current directory, if it |
|
467 | 467 | exists, or in a specified list of directories. |
|
468 | 468 | |
|
469 | 469 | ~ expansion is done on all file and directory names. |
|
470 | 470 | |
|
471 | 471 | Upon an unsuccessful search, raise an IOError exception.""" |
|
472 | 472 | |
|
473 | 473 | if alt_dirs is None: |
|
474 | 474 | try: |
|
475 | 475 | alt_dirs = get_home_dir() |
|
476 | 476 | except HomeDirError: |
|
477 | 477 | alt_dirs = os.getcwd() |
|
478 | 478 | search = [fname] + list_strings(alt_dirs) |
|
479 | 479 | search = map(os.path.expanduser,search) |
|
480 | 480 | #print 'search list for',fname,'list:',search # dbg |
|
481 | 481 | fname = search[0] |
|
482 | 482 | if os.path.isfile(fname): |
|
483 | 483 | return fname |
|
484 | 484 | for direc in search[1:]: |
|
485 | 485 | testname = os.path.join(direc,fname) |
|
486 | 486 | #print 'testname',testname # dbg |
|
487 | 487 | if os.path.isfile(testname): |
|
488 | 488 | return testname |
|
489 | 489 | raise IOError,'File' + `fname` + \ |
|
490 | 490 | ' not found in current or supplied directories:' + `alt_dirs` |
|
491 | 491 | |
|
492 | 492 | #---------------------------------------------------------------------------- |
|
493 | 493 | def file_read(filename): |
|
494 | 494 | """Read a file and close it. Returns the file source.""" |
|
495 | 495 | fobj=open(filename,'r'); |
|
496 | 496 | source = fobj.read(); |
|
497 | 497 | fobj.close() |
|
498 | 498 | return source |
|
499 | 499 | |
|
500 | 500 | #---------------------------------------------------------------------------- |
|
501 | 501 | def target_outdated(target,deps): |
|
502 | 502 | """Determine whether a target is out of date. |
|
503 | 503 | |
|
504 | 504 | target_outdated(target,deps) -> 1/0 |
|
505 | 505 | |
|
506 | 506 | deps: list of filenames which MUST exist. |
|
507 | 507 | target: single filename which may or may not exist. |
|
508 | 508 | |
|
509 | 509 | If target doesn't exist or is older than any file listed in deps, return |
|
510 | 510 | true, otherwise return false. |
|
511 | 511 | """ |
|
512 | 512 | try: |
|
513 | 513 | target_time = os.path.getmtime(target) |
|
514 | 514 | except os.error: |
|
515 | 515 | return 1 |
|
516 | 516 | for dep in deps: |
|
517 | 517 | dep_time = os.path.getmtime(dep) |
|
518 | 518 | if dep_time > target_time: |
|
519 | 519 | #print "For target",target,"Dep failed:",dep # dbg |
|
520 | 520 | #print "times (dep,tar):",dep_time,target_time # dbg |
|
521 | 521 | return 1 |
|
522 | 522 | return 0 |
|
523 | 523 | |
|
524 | 524 | #----------------------------------------------------------------------------- |
|
525 | 525 | def target_update(target,deps,cmd): |
|
526 | 526 | """Update a target with a given command given a list of dependencies. |
|
527 | 527 | |
|
528 | 528 | target_update(target,deps,cmd) -> runs cmd if target is outdated. |
|
529 | 529 | |
|
530 | 530 | This is just a wrapper around target_outdated() which calls the given |
|
531 | 531 | command if target is outdated.""" |
|
532 | 532 | |
|
533 | 533 | if target_outdated(target,deps): |
|
534 | 534 | xsys(cmd) |
|
535 | 535 | |
|
536 | 536 | #---------------------------------------------------------------------------- |
|
537 | 537 | def unquote_ends(istr): |
|
538 | 538 | """Remove a single pair of quotes from the endpoints of a string.""" |
|
539 | 539 | |
|
540 | 540 | if not istr: |
|
541 | 541 | return istr |
|
542 | 542 | if (istr[0]=="'" and istr[-1]=="'") or \ |
|
543 | 543 | (istr[0]=='"' and istr[-1]=='"'): |
|
544 | 544 | return istr[1:-1] |
|
545 | 545 | else: |
|
546 | 546 | return istr |
|
547 | 547 | |
|
548 | 548 | #---------------------------------------------------------------------------- |
|
549 | 549 | def process_cmdline(argv,names=[],defaults={},usage=''): |
|
550 | 550 | """ Process command-line options and arguments. |
|
551 | 551 | |
|
552 | 552 | Arguments: |
|
553 | 553 | |
|
554 | 554 | - argv: list of arguments, typically sys.argv. |
|
555 | 555 | |
|
556 | 556 | - names: list of option names. See DPyGetOpt docs for details on options |
|
557 | 557 | syntax. |
|
558 | 558 | |
|
559 | 559 | - defaults: dict of default values. |
|
560 | 560 | |
|
561 | 561 | - usage: optional usage notice to print if a wrong argument is passed. |
|
562 | 562 | |
|
563 | 563 | Return a dict of options and a list of free arguments.""" |
|
564 | 564 | |
|
565 | 565 | getopt = DPyGetOpt.DPyGetOpt() |
|
566 | 566 | getopt.setIgnoreCase(0) |
|
567 | 567 | getopt.parseConfiguration(names) |
|
568 | 568 | |
|
569 | 569 | try: |
|
570 | 570 | getopt.processArguments(argv) |
|
571 | 571 | except: |
|
572 | 572 | print usage |
|
573 | 573 | warn(`sys.exc_value`,level=4) |
|
574 | 574 | |
|
575 | 575 | defaults.update(getopt.optionValues) |
|
576 | 576 | args = getopt.freeValues |
|
577 | 577 | |
|
578 | 578 | return defaults,args |
|
579 | 579 | |
|
580 | 580 | #---------------------------------------------------------------------------- |
|
581 | 581 | def optstr2types(ostr): |
|
582 | 582 | """Convert a string of option names to a dict of type mappings. |
|
583 | 583 | |
|
584 | 584 | optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'} |
|
585 | 585 | |
|
586 | 586 | This is used to get the types of all the options in a string formatted |
|
587 | 587 | with the conventions of DPyGetOpt. The 'type' None is used for options |
|
588 | 588 | which are strings (they need no further conversion). This function's main |
|
589 | 589 | use is to get a typemap for use with read_dict(). |
|
590 | 590 | """ |
|
591 | 591 | |
|
592 | 592 | typeconv = {None:'',int:'',float:''} |
|
593 | 593 | typemap = {'s':None,'i':int,'f':float} |
|
594 | 594 | opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)') |
|
595 | 595 | |
|
596 | 596 | for w in ostr.split(): |
|
597 | 597 | oname,alias,otype = opt_re.match(w).groups() |
|
598 | 598 | if otype == '' or alias == '!': # simple switches are integers too |
|
599 | 599 | otype = 'i' |
|
600 | 600 | typeconv[typemap[otype]] += oname + ' ' |
|
601 | 601 | return typeconv |
|
602 | 602 | |
|
603 | 603 | #---------------------------------------------------------------------------- |
|
604 | 604 | def read_dict(filename,type_conv=None,**opt): |
|
605 | 605 | |
|
606 | 606 | """Read a dictionary of key=value pairs from an input file, optionally |
|
607 | 607 | performing conversions on the resulting values. |
|
608 | 608 | |
|
609 | 609 | read_dict(filename,type_conv,**opt) -> dict |
|
610 | 610 | |
|
611 | 611 | Only one value per line is accepted, the format should be |
|
612 | 612 | # optional comments are ignored |
|
613 | 613 | key value\n |
|
614 | 614 | |
|
615 | 615 | Args: |
|
616 | 616 | |
|
617 | 617 | - type_conv: A dictionary specifying which keys need to be converted to |
|
618 | 618 | which types. By default all keys are read as strings. This dictionary |
|
619 | 619 | should have as its keys valid conversion functions for strings |
|
620 | 620 | (int,long,float,complex, or your own). The value for each key |
|
621 | 621 | (converter) should be a whitespace separated string containing the names |
|
622 | 622 | of all the entries in the file to be converted using that function. For |
|
623 | 623 | keys to be left alone, use None as the conversion function (only needed |
|
624 | 624 | with purge=1, see below). |
|
625 | 625 | |
|
626 | 626 | - opt: dictionary with extra options as below (default in parens) |
|
627 | 627 | |
|
628 | 628 | purge(0): if set to 1, all keys *not* listed in type_conv are purged out |
|
629 | 629 | of the dictionary to be returned. If purge is going to be used, the |
|
630 | 630 | set of keys to be left as strings also has to be explicitly specified |
|
631 | 631 | using the (non-existent) conversion function None. |
|
632 | 632 | |
|
633 | 633 | fs(None): field separator. This is the key/value separator to be used |
|
634 | 634 | when parsing the file. The None default means any whitespace [behavior |
|
635 | 635 | of string.split()]. |
|
636 | 636 | |
|
637 | 637 | strip(0): if 1, strip string values of leading/trailinig whitespace. |
|
638 | 638 | |
|
639 | 639 | warn(1): warning level if requested keys are not found in file. |
|
640 | 640 | - 0: silently ignore. |
|
641 | 641 | - 1: inform but proceed. |
|
642 | 642 | - 2: raise KeyError exception. |
|
643 | 643 | |
|
644 | 644 | no_empty(0): if 1, remove keys with whitespace strings as a value. |
|
645 | 645 | |
|
646 | 646 | unique([]): list of keys (or space separated string) which can't be |
|
647 | 647 | repeated. If one such key is found in the file, each new instance |
|
648 | 648 | overwrites the previous one. For keys not listed here, the behavior is |
|
649 | 649 | to make a list of all appearances. |
|
650 | 650 | |
|
651 | 651 | Example: |
|
652 | 652 | If the input file test.ini has: |
|
653 | 653 | i 3 |
|
654 | 654 | x 4.5 |
|
655 | 655 | y 5.5 |
|
656 | 656 | s hi ho |
|
657 | 657 | Then: |
|
658 | 658 | |
|
659 | 659 | >>> type_conv={int:'i',float:'x',None:'s'} |
|
660 | 660 | >>> read_dict('test.ini') |
|
661 | 661 | {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'} |
|
662 | 662 | >>> read_dict('test.ini',type_conv) |
|
663 | 663 | {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'} |
|
664 | 664 | >>> read_dict('test.ini',type_conv,purge=1) |
|
665 | 665 | {'i': 3, 's': 'hi ho', 'x': 4.5} |
|
666 | 666 | """ |
|
667 | 667 | |
|
668 | 668 | # starting config |
|
669 | 669 | opt.setdefault('purge',0) |
|
670 | 670 | opt.setdefault('fs',None) # field sep defaults to any whitespace |
|
671 | 671 | opt.setdefault('strip',0) |
|
672 | 672 | opt.setdefault('warn',1) |
|
673 | 673 | opt.setdefault('no_empty',0) |
|
674 | 674 | opt.setdefault('unique','') |
|
675 | 675 | if type(opt['unique']) in StringTypes: |
|
676 | 676 | unique_keys = qw(opt['unique']) |
|
677 | 677 | elif type(opt['unique']) in (types.TupleType,types.ListType): |
|
678 | 678 | unique_keys = opt['unique'] |
|
679 | 679 | else: |
|
680 | 680 | raise ValueError, 'Unique keys must be given as a string, List or Tuple' |
|
681 | 681 | |
|
682 | 682 | dict = {} |
|
683 | 683 | # first read in table of values as strings |
|
684 | 684 | file = open(filename,'r') |
|
685 | 685 | for line in file.readlines(): |
|
686 | 686 | line = line.strip() |
|
687 | 687 | if len(line) and line[0]=='#': continue |
|
688 | 688 | if len(line)>0: |
|
689 | 689 | lsplit = line.split(opt['fs'],1) |
|
690 | 690 | try: |
|
691 | 691 | key,val = lsplit |
|
692 | 692 | except ValueError: |
|
693 | 693 | key,val = lsplit[0],'' |
|
694 | 694 | key = key.strip() |
|
695 | 695 | if opt['strip']: val = val.strip() |
|
696 | 696 | if val == "''" or val == '""': val = '' |
|
697 | 697 | if opt['no_empty'] and (val=='' or val.isspace()): |
|
698 | 698 | continue |
|
699 | 699 | # if a key is found more than once in the file, build a list |
|
700 | 700 | # unless it's in the 'unique' list. In that case, last found in file |
|
701 | 701 | # takes precedence. User beware. |
|
702 | 702 | try: |
|
703 | 703 | if dict[key] and key in unique_keys: |
|
704 | 704 | dict[key] = val |
|
705 | 705 | elif type(dict[key]) is types.ListType: |
|
706 | 706 | dict[key].append(val) |
|
707 | 707 | else: |
|
708 | 708 | dict[key] = [dict[key],val] |
|
709 | 709 | except KeyError: |
|
710 | 710 | dict[key] = val |
|
711 | 711 | # purge if requested |
|
712 | 712 | if opt['purge']: |
|
713 | 713 | accepted_keys = qwflat(type_conv.values()) |
|
714 | 714 | for key in dict.keys(): |
|
715 | 715 | if key in accepted_keys: continue |
|
716 | 716 | del(dict[key]) |
|
717 | 717 | # now convert if requested |
|
718 | 718 | if type_conv==None: return dict |
|
719 | 719 | conversions = type_conv.keys() |
|
720 | 720 | try: conversions.remove(None) |
|
721 | 721 | except: pass |
|
722 | 722 | for convert in conversions: |
|
723 | 723 | for val in qw(type_conv[convert]): |
|
724 | 724 | try: |
|
725 | 725 | dict[val] = convert(dict[val]) |
|
726 | 726 | except KeyError,e: |
|
727 | 727 | if opt['warn'] == 0: |
|
728 | 728 | pass |
|
729 | 729 | elif opt['warn'] == 1: |
|
730 | 730 | print >>sys.stderr, 'Warning: key',val,\ |
|
731 | 731 | 'not found in file',filename |
|
732 | 732 | elif opt['warn'] == 2: |
|
733 | 733 | raise KeyError,e |
|
734 | 734 | else: |
|
735 | 735 | raise ValueError,'Warning level must be 0,1 or 2' |
|
736 | 736 | |
|
737 | 737 | return dict |
|
738 | 738 | |
|
739 | 739 | #---------------------------------------------------------------------------- |
|
740 | 740 | def flag_calls(func): |
|
741 | 741 | """Wrap a function to detect and flag when it gets called. |
|
742 | 742 | |
|
743 | 743 | This is a decorator which takes a function and wraps it in a function with |
|
744 | 744 | a 'called' attribute. wrapper.called is initialized to False. |
|
745 | 745 | |
|
746 | 746 | The wrapper.called attribute is set to False right before each call to the |
|
747 | 747 | wrapped function, so if the call fails it remains False. After the call |
|
748 | 748 | completes, wrapper.called is set to True and the output is returned. |
|
749 | 749 | |
|
750 | 750 | Testing for truth in wrapper.called allows you to determine if a call to |
|
751 | 751 | func() was attempted and succeeded.""" |
|
752 | 752 | |
|
753 | 753 | def wrapper(*args,**kw): |
|
754 | 754 | wrapper.called = False |
|
755 | 755 | out = func(*args,**kw) |
|
756 | 756 | wrapper.called = True |
|
757 | 757 | return out |
|
758 | 758 | |
|
759 | 759 | wrapper.called = False |
|
760 | 760 | wrapper.__doc__ = func.__doc__ |
|
761 | 761 | return wrapper |
|
762 | 762 | |
|
763 | 763 | #---------------------------------------------------------------------------- |
|
764 | 764 | class HomeDirError(Error): |
|
765 | 765 | pass |
|
766 | 766 | |
|
767 | 767 | def get_home_dir(): |
|
768 | 768 | """Return the closest possible equivalent to a 'home' directory. |
|
769 | 769 | |
|
770 | 770 | We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH. |
|
771 | 771 | |
|
772 | 772 | Currently only Posix and NT are implemented, a HomeDirError exception is |
|
773 | 773 | raised for all other OSes. """ |
|
774 | 774 | |
|
775 | 775 | isdir = os.path.isdir |
|
776 | 776 | env = os.environ |
|
777 | 777 | try: |
|
778 | 778 | homedir = env['HOME'] |
|
779 | 779 | if not isdir(homedir): |
|
780 | 780 | # in case a user stuck some string which does NOT resolve to a |
|
781 | 781 | # valid path, it's as good as if we hadn't foud it |
|
782 | 782 | raise KeyError |
|
783 | 783 | return homedir |
|
784 | 784 | except KeyError: |
|
785 | 785 | if os.name == 'posix': |
|
786 | 786 | raise HomeDirError,'undefined $HOME, IPython can not proceed.' |
|
787 | 787 | elif os.name == 'nt': |
|
788 | 788 | # For some strange reason, win9x returns 'nt' for os.name. |
|
789 | 789 | try: |
|
790 | 790 | homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH']) |
|
791 | 791 | if not isdir(homedir): |
|
792 | 792 | homedir = os.path.join(env['USERPROFILE']) |
|
793 | 793 | if not isdir(homedir): |
|
794 | 794 | raise HomeDirError |
|
795 | 795 | return homedir |
|
796 | 796 | except: |
|
797 | 797 | try: |
|
798 | 798 | # Use the registry to get the 'My Documents' folder. |
|
799 | 799 | import _winreg as wreg |
|
800 | 800 | key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, |
|
801 | 801 | "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders") |
|
802 | 802 | homedir = wreg.QueryValueEx(key,'Personal')[0] |
|
803 | 803 | key.Close() |
|
804 | 804 | if not isdir(homedir): |
|
805 | 805 | e = ('Invalid "Personal" folder registry key ' |
|
806 | 806 | 'typically "My Documents".\n' |
|
807 | 807 | 'Value: %s\n' |
|
808 | 808 | 'This is not a valid directory on your system.' % |
|
809 | 809 | homedir) |
|
810 | 810 | raise HomeDirError(e) |
|
811 | 811 | return homedir |
|
812 | 812 | except HomeDirError: |
|
813 | 813 | raise |
|
814 | 814 | except: |
|
815 | 815 | return 'C:\\' |
|
816 | 816 | elif os.name == 'dos': |
|
817 | 817 | # Desperate, may do absurd things in classic MacOS. May work under DOS. |
|
818 | 818 | return 'C:\\' |
|
819 | 819 | else: |
|
820 | 820 | raise HomeDirError,'support for your operating system not implemented.' |
|
821 | 821 | |
|
822 | 822 | #**************************************************************************** |
|
823 | 823 | # strings and text |
|
824 | 824 | |
|
825 | 825 | class LSString(str): |
|
826 | 826 | """String derivative with a special access attributes. |
|
827 | 827 | |
|
828 | 828 | These are normal strings, but with the special attributes: |
|
829 | 829 | |
|
830 | 830 | .l (or .list) : value as list (split on newlines). |
|
831 | 831 | .n (or .nlstr): original value (the string itself). |
|
832 | 832 | .s (or .spstr): value as whitespace-separated string. |
|
833 | 833 | |
|
834 | 834 | Any values which require transformations are computed only once and |
|
835 | 835 | cached. |
|
836 | 836 | |
|
837 | 837 | Such strings are very useful to efficiently interact with the shell, which |
|
838 | 838 | typically only understands whitespace-separated options for commands.""" |
|
839 | 839 | |
|
840 | 840 | def get_list(self): |
|
841 | 841 | try: |
|
842 | 842 | return self.__list |
|
843 | 843 | except AttributeError: |
|
844 | 844 | self.__list = self.split('\n') |
|
845 | 845 | return self.__list |
|
846 | 846 | |
|
847 | 847 | l = list = property(get_list) |
|
848 | 848 | |
|
849 | 849 | def get_spstr(self): |
|
850 | 850 | try: |
|
851 | 851 | return self.__spstr |
|
852 | 852 | except AttributeError: |
|
853 | 853 | self.__spstr = self.replace('\n',' ') |
|
854 | 854 | return self.__spstr |
|
855 | 855 | |
|
856 | 856 | s = spstr = property(get_spstr) |
|
857 | 857 | |
|
858 | 858 | def get_nlstr(self): |
|
859 | 859 | return self |
|
860 | 860 | |
|
861 | 861 | n = nlstr = property(get_nlstr) |
|
862 | 862 | |
|
863 | #---------------------------------------------------------------------------- | |
|
863 | 864 | class SList(list): |
|
864 | 865 | """List derivative with a special access attributes. |
|
865 | 866 | |
|
866 | 867 | These are normal lists, but with the special attributes: |
|
867 | 868 | |
|
868 | 869 | .l (or .list) : value as list (the list itself). |
|
869 | 870 | .n (or .nlstr): value as a string, joined on newlines. |
|
870 | 871 | .s (or .spstr): value as a string, joined on spaces. |
|
871 | 872 | |
|
872 | 873 | Any values which require transformations are computed only once and |
|
873 | 874 | cached.""" |
|
874 | 875 | |
|
875 | 876 | def get_list(self): |
|
876 | 877 | return self |
|
877 | 878 | |
|
878 | 879 | l = list = property(get_list) |
|
879 | 880 | |
|
880 | 881 | def get_spstr(self): |
|
881 | 882 | try: |
|
882 | 883 | return self.__spstr |
|
883 | 884 | except AttributeError: |
|
884 | 885 | self.__spstr = ' '.join(self) |
|
885 | 886 | return self.__spstr |
|
886 | 887 | |
|
887 | 888 | s = spstr = property(get_spstr) |
|
888 | 889 | |
|
889 | 890 | def get_nlstr(self): |
|
890 | 891 | try: |
|
891 | 892 | return self.__nlstr |
|
892 | 893 | except AttributeError: |
|
893 | 894 | self.__nlstr = '\n'.join(self) |
|
894 | 895 | return self.__nlstr |
|
895 | 896 | |
|
896 | 897 | n = nlstr = property(get_nlstr) |
|
897 | 898 | |
|
899 | #---------------------------------------------------------------------------- | |
|
900 | # This can be replaced with an isspace() call once we drop 2.2 compatibility | |
|
901 | _isspace_match = re.compile(r'^\s+$').match | |
|
902 | def isspace(s): | |
|
903 | return bool(_isspace_match(s)) | |
|
904 | ||
|
905 | #---------------------------------------------------------------------------- | |
|
906 | def esc_quotes(strng): | |
|
907 | """Return the input string with single and double quotes escaped out""" | |
|
908 | ||
|
909 | return strng.replace('"','\\"').replace("'","\\'") | |
|
910 | ||
|
911 | #---------------------------------------------------------------------------- | |
|
898 | 912 | def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'): |
|
899 | 913 | """Take multiple lines of input. |
|
900 | 914 | |
|
901 | 915 | A list with each line of input as a separate element is returned when a |
|
902 | 916 | termination string is entered (defaults to a single '.'). Input can also |
|
903 | 917 | terminate via EOF (^D in Unix, ^Z-RET in Windows). |
|
904 | 918 | |
|
905 | 919 | Lines of input which end in \\ are joined into single entries (and a |
|
906 | 920 | secondary continuation prompt is issued as long as the user terminates |
|
907 | 921 | lines with \\). This allows entering very long strings which are still |
|
908 | 922 | meant to be treated as single entities. |
|
909 | 923 | """ |
|
910 | 924 | |
|
911 | 925 | try: |
|
912 | 926 | if header: |
|
913 | 927 | header += '\n' |
|
914 | 928 | lines = [raw_input(header + ps1)] |
|
915 | 929 | except EOFError: |
|
916 | 930 | return [] |
|
917 | 931 | terminate = [terminate_str] |
|
918 | 932 | try: |
|
919 | 933 | while lines[-1:] != terminate: |
|
920 | 934 | new_line = raw_input(ps1) |
|
921 | 935 | while new_line.endswith('\\'): |
|
922 | 936 | new_line = new_line[:-1] + raw_input(ps2) |
|
923 | 937 | lines.append(new_line) |
|
924 | 938 | |
|
925 | 939 | return lines[:-1] # don't return the termination command |
|
926 | 940 | except EOFError: |
|
927 | 941 | |
|
928 | 942 | return lines |
|
929 | 943 | |
|
930 | 944 | #---------------------------------------------------------------------------- |
|
931 | 945 | def raw_input_ext(prompt='', ps2='... '): |
|
932 | 946 | """Similar to raw_input(), but accepts extended lines if input ends with \\.""" |
|
933 | 947 | |
|
934 | 948 | line = raw_input(prompt) |
|
935 | 949 | while line.endswith('\\'): |
|
936 | 950 | line = line[:-1] + raw_input(ps2) |
|
937 | 951 | return line |
|
938 | 952 | |
|
939 | 953 | #---------------------------------------------------------------------------- |
|
940 | 954 | def ask_yes_no(prompt,default=None): |
|
941 | 955 | """Asks a question and returns an integer 1/0 (y/n) answer. |
|
942 | 956 | |
|
943 | 957 | If default is given (one of 'y','n'), it is used if the user input is |
|
944 | 958 | empty. Otherwise the question is repeated until an answer is given. |
|
945 | 959 | If EOF occurs 20 times consecutively, the default answer is assumed, |
|
946 | 960 | or if there is no default, an exception is raised to prevent infinite |
|
947 | 961 | loops. |
|
948 | 962 | |
|
949 | 963 | Valid answers are: y/yes/n/no (match is not case sensitive).""" |
|
950 | 964 | |
|
951 | 965 | answers = {'y':True,'n':False,'yes':True,'no':False} |
|
952 | 966 | ans = None |
|
953 | 967 | eofs, max_eofs = 0, 20 |
|
954 | 968 | while ans not in answers.keys(): |
|
955 | 969 | try: |
|
956 | 970 | ans = raw_input(prompt+' ').lower() |
|
957 | 971 | if not ans: # response was an empty string |
|
958 | 972 | ans = default |
|
959 | 973 | eofs = 0 |
|
960 | 974 | except (EOFError,KeyboardInterrupt): |
|
961 | 975 | eofs = eofs + 1 |
|
962 | 976 | if eofs >= max_eofs: |
|
963 | 977 | if default in answers.keys(): |
|
964 | 978 | ans = default |
|
965 | 979 | else: |
|
966 | 980 | raise |
|
967 | 981 | |
|
968 | 982 | return answers[ans] |
|
969 | 983 | |
|
970 | 984 | #---------------------------------------------------------------------------- |
|
971 | 985 | def marquee(txt='',width=78,mark='*'): |
|
972 | 986 | """Return the input string centered in a 'marquee'.""" |
|
973 | 987 | if not txt: |
|
974 | 988 | return (mark*width)[:width] |
|
975 | 989 | nmark = (width-len(txt)-2)/len(mark)/2 |
|
976 | 990 | if nmark < 0: nmark =0 |
|
977 | 991 | marks = mark*nmark |
|
978 | 992 | return '%s %s %s' % (marks,txt,marks) |
|
979 | 993 | |
|
980 | 994 | #---------------------------------------------------------------------------- |
|
981 | 995 | class EvalDict: |
|
982 | 996 | """ |
|
983 | 997 | Emulate a dict which evaluates its contents in the caller's frame. |
|
984 | 998 | |
|
985 | 999 | Usage: |
|
986 | 1000 | >>>number = 19 |
|
987 | 1001 | >>>text = "python" |
|
988 | 1002 | >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict() |
|
989 | 1003 | """ |
|
990 | 1004 | |
|
991 | 1005 | # This version is due to sismex01@hebmex.com on c.l.py, and is basically a |
|
992 | 1006 | # modified (shorter) version of: |
|
993 | 1007 | # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by |
|
994 | 1008 | # Skip Montanaro (skip@pobox.com). |
|
995 | 1009 | |
|
996 | 1010 | def __getitem__(self, name): |
|
997 | 1011 | frame = sys._getframe(1) |
|
998 | 1012 | return eval(name, frame.f_globals, frame.f_locals) |
|
999 | 1013 | |
|
1000 | 1014 | EvalString = EvalDict # for backwards compatibility |
|
1001 | 1015 | #---------------------------------------------------------------------------- |
|
1002 | 1016 | def qw(words,flat=0,sep=None,maxsplit=-1): |
|
1003 | 1017 | """Similar to Perl's qw() operator, but with some more options. |
|
1004 | 1018 | |
|
1005 | 1019 | qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit) |
|
1006 | 1020 | |
|
1007 | 1021 | words can also be a list itself, and with flat=1, the output will be |
|
1008 | 1022 | recursively flattened. Examples: |
|
1009 | 1023 | |
|
1010 | 1024 | >>> qw('1 2') |
|
1011 | 1025 | ['1', '2'] |
|
1012 | 1026 | >>> qw(['a b','1 2',['m n','p q']]) |
|
1013 | 1027 | [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]] |
|
1014 | 1028 | >>> qw(['a b','1 2',['m n','p q']],flat=1) |
|
1015 | 1029 | ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """ |
|
1016 | 1030 | |
|
1017 | 1031 | if type(words) in StringTypes: |
|
1018 | 1032 | return [word.strip() for word in words.split(sep,maxsplit) |
|
1019 | 1033 | if word and not word.isspace() ] |
|
1020 | 1034 | if flat: |
|
1021 | 1035 | return flatten(map(qw,words,[1]*len(words))) |
|
1022 | 1036 | return map(qw,words) |
|
1023 | 1037 | |
|
1024 | 1038 | #---------------------------------------------------------------------------- |
|
1025 | 1039 | def qwflat(words,sep=None,maxsplit=-1): |
|
1026 | 1040 | """Calls qw(words) in flat mode. It's just a convenient shorthand.""" |
|
1027 | 1041 | return qw(words,1,sep,maxsplit) |
|
1028 | 1042 | |
|
1043 | #---------------------------------------------------------------------------- | |
|
1044 | def qw_lol(indata): | |
|
1045 | """qw_lol('a b') -> [['a','b']], | |
|
1046 | otherwise it's just a call to qw(). | |
|
1047 | ||
|
1048 | We need this to make sure the modules_some keys *always* end up as a | |
|
1049 | list of lists.""" | |
|
1050 | ||
|
1051 | if type(indata) in StringTypes: | |
|
1052 | return [qw(indata)] | |
|
1053 | else: | |
|
1054 | return qw(indata) | |
|
1055 | ||
|
1029 | 1056 | #----------------------------------------------------------------------------- |
|
1030 | 1057 | def list_strings(arg): |
|
1031 | 1058 | """Always return a list of strings, given a string or list of strings |
|
1032 | 1059 | as input.""" |
|
1033 | 1060 | |
|
1034 | 1061 | if type(arg) in StringTypes: return [arg] |
|
1035 | 1062 | else: return arg |
|
1036 | 1063 | |
|
1037 | 1064 | #---------------------------------------------------------------------------- |
|
1038 | 1065 | def grep(pat,list,case=1): |
|
1039 | 1066 | """Simple minded grep-like function. |
|
1040 | 1067 | grep(pat,list) returns occurrences of pat in list, None on failure. |
|
1041 | 1068 | |
|
1042 | 1069 | It only does simple string matching, with no support for regexps. Use the |
|
1043 | 1070 | option case=0 for case-insensitive matching.""" |
|
1044 | 1071 | |
|
1045 | 1072 | # This is pretty crude. At least it should implement copying only references |
|
1046 | 1073 | # to the original data in case it's big. Now it copies the data for output. |
|
1047 | 1074 | out=[] |
|
1048 | 1075 | if case: |
|
1049 | 1076 | for term in list: |
|
1050 | 1077 | if term.find(pat)>-1: out.append(term) |
|
1051 | 1078 | else: |
|
1052 | 1079 | lpat=pat.lower() |
|
1053 | 1080 | for term in list: |
|
1054 | 1081 | if term.lower().find(lpat)>-1: out.append(term) |
|
1055 | 1082 | |
|
1056 | 1083 | if len(out): return out |
|
1057 | 1084 | else: return None |
|
1058 | 1085 | |
|
1059 | 1086 | #---------------------------------------------------------------------------- |
|
1060 | 1087 | def dgrep(pat,*opts): |
|
1061 | 1088 | """Return grep() on dir()+dir(__builtins__). |
|
1062 | 1089 | |
|
1063 | 1090 | A very common use of grep() when working interactively.""" |
|
1064 | 1091 | |
|
1065 | 1092 | return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts) |
|
1066 | 1093 | |
|
1067 | 1094 | #---------------------------------------------------------------------------- |
|
1068 | 1095 | def idgrep(pat): |
|
1069 | 1096 | """Case-insensitive dgrep()""" |
|
1070 | 1097 | |
|
1071 | 1098 | return dgrep(pat,0) |
|
1072 | 1099 | |
|
1073 | 1100 | #---------------------------------------------------------------------------- |
|
1074 | 1101 | def igrep(pat,list): |
|
1075 | 1102 | """Synonym for case-insensitive grep.""" |
|
1076 | 1103 | |
|
1077 | 1104 | return grep(pat,list,case=0) |
|
1078 | 1105 | |
|
1079 | 1106 | #---------------------------------------------------------------------------- |
|
1080 | 1107 | def indent(str,nspaces=4,ntabs=0): |
|
1081 | 1108 | """Indent a string a given number of spaces or tabstops. |
|
1082 | 1109 | |
|
1083 | 1110 | indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces. |
|
1084 | 1111 | """ |
|
1085 | 1112 | if str is None: |
|
1086 | 1113 | return |
|
1087 | 1114 | ind = '\t'*ntabs+' '*nspaces |
|
1088 | 1115 | outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind)) |
|
1089 | 1116 | if outstr.endswith(os.linesep+ind): |
|
1090 | 1117 | return outstr[:-len(ind)] |
|
1091 | 1118 | else: |
|
1092 | 1119 | return outstr |
|
1093 | 1120 | |
|
1094 | 1121 | #----------------------------------------------------------------------------- |
|
1095 | 1122 | def native_line_ends(filename,backup=1): |
|
1096 | 1123 | """Convert (in-place) a file to line-ends native to the current OS. |
|
1097 | 1124 | |
|
1098 | 1125 | If the optional backup argument is given as false, no backup of the |
|
1099 | 1126 | original file is left. """ |
|
1100 | 1127 | |
|
1101 | 1128 | backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'} |
|
1102 | 1129 | |
|
1103 | 1130 | bak_filename = filename + backup_suffixes[os.name] |
|
1104 | 1131 | |
|
1105 | 1132 | original = open(filename).read() |
|
1106 | 1133 | shutil.copy2(filename,bak_filename) |
|
1107 | 1134 | try: |
|
1108 | 1135 | new = open(filename,'wb') |
|
1109 | 1136 | new.write(os.linesep.join(original.splitlines())) |
|
1110 | 1137 | new.write(os.linesep) # ALWAYS put an eol at the end of the file |
|
1111 | 1138 | new.close() |
|
1112 | 1139 | except: |
|
1113 | 1140 | os.rename(bak_filename,filename) |
|
1114 | 1141 | if not backup: |
|
1115 | 1142 | try: |
|
1116 | 1143 | os.remove(bak_filename) |
|
1117 | 1144 | except: |
|
1118 | 1145 | pass |
|
1119 | 1146 | |
|
1120 | 1147 | #---------------------------------------------------------------------------- |
|
1121 | 1148 | def get_pager_cmd(pager_cmd = None): |
|
1122 | 1149 | """Return a pager command. |
|
1123 | 1150 | |
|
1124 | 1151 | Makes some attempts at finding an OS-correct one.""" |
|
1125 | 1152 | |
|
1126 | 1153 | if os.name == 'posix': |
|
1127 | 1154 | default_pager_cmd = 'less -r' # -r for color control sequences |
|
1128 | 1155 | elif os.name in ['nt','dos']: |
|
1129 | 1156 | default_pager_cmd = 'type' |
|
1130 | 1157 | |
|
1131 | 1158 | if pager_cmd is None: |
|
1132 | 1159 | try: |
|
1133 | 1160 | pager_cmd = os.environ['PAGER'] |
|
1134 | 1161 | except: |
|
1135 | 1162 | pager_cmd = default_pager_cmd |
|
1136 | 1163 | return pager_cmd |
|
1137 | 1164 | |
|
1138 | 1165 | #----------------------------------------------------------------------------- |
|
1139 | 1166 | def get_pager_start(pager,start): |
|
1140 | 1167 | """Return the string for paging files with an offset. |
|
1141 | 1168 | |
|
1142 | 1169 | This is the '+N' argument which less and more (under Unix) accept. |
|
1143 | 1170 | """ |
|
1144 | 1171 | |
|
1145 | 1172 | if pager in ['less','more']: |
|
1146 | 1173 | if start: |
|
1147 | 1174 | start_string = '+' + str(start) |
|
1148 | 1175 | else: |
|
1149 | 1176 | start_string = '' |
|
1150 | 1177 | else: |
|
1151 | 1178 | start_string = '' |
|
1152 | 1179 | return start_string |
|
1153 | 1180 | |
|
1154 | 1181 | #---------------------------------------------------------------------------- |
|
1155 | 1182 | def page_dumb(strng,start=0,screen_lines=25): |
|
1156 | 1183 | """Very dumb 'pager' in Python, for when nothing else works. |
|
1157 | 1184 | |
|
1158 | 1185 | Only moves forward, same interface as page(), except for pager_cmd and |
|
1159 | 1186 | mode.""" |
|
1160 | 1187 | |
|
1161 | 1188 | out_ln = strng.splitlines()[start:] |
|
1162 | 1189 | screens = chop(out_ln,screen_lines-1) |
|
1163 | 1190 | if len(screens) == 1: |
|
1164 | 1191 | print >>Term.cout, os.linesep.join(screens[0]) |
|
1165 | 1192 | else: |
|
1166 | 1193 | for scr in screens[0:-1]: |
|
1167 | 1194 | print >>Term.cout, os.linesep.join(scr) |
|
1168 | 1195 | ans = raw_input('---Return to continue, q to quit--- ') |
|
1169 | 1196 | if ans.lower().startswith('q'): |
|
1170 | 1197 | return |
|
1171 | 1198 | print >>Term.cout, os.linesep.join(screens[-1]) |
|
1172 | 1199 | |
|
1173 | 1200 | #---------------------------------------------------------------------------- |
|
1174 | 1201 | def page(strng,start=0,screen_lines=0,pager_cmd = None): |
|
1175 | 1202 | """Print a string, piping through a pager after a certain length. |
|
1176 | 1203 | |
|
1177 | 1204 | The screen_lines parameter specifies the number of *usable* lines of your |
|
1178 | 1205 | terminal screen (total lines minus lines you need to reserve to show other |
|
1179 | 1206 | information). |
|
1180 | 1207 | |
|
1181 | 1208 | If you set screen_lines to a number <=0, page() will try to auto-determine |
|
1182 | 1209 | your screen size and will only use up to (screen_size+screen_lines) for |
|
1183 | 1210 | printing, paging after that. That is, if you want auto-detection but need |
|
1184 | 1211 | to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for |
|
1185 | 1212 | auto-detection without any lines reserved simply use screen_lines = 0. |
|
1186 | 1213 | |
|
1187 | 1214 | If a string won't fit in the allowed lines, it is sent through the |
|
1188 | 1215 | specified pager command. If none given, look for PAGER in the environment, |
|
1189 | 1216 | and ultimately default to less. |
|
1190 | 1217 | |
|
1191 | 1218 | If no system pager works, the string is sent through a 'dumb pager' |
|
1192 | 1219 | written in python, very simplistic. |
|
1193 | 1220 | """ |
|
1194 | 1221 | |
|
1195 | 1222 | # Ugly kludge, but calling curses.initscr() flat out crashes in emacs |
|
1196 | 1223 | TERM = os.environ.get('TERM','dumb') |
|
1197 | 1224 | if TERM in ['dumb','emacs'] and os.name != 'nt': |
|
1198 | 1225 | print strng |
|
1199 | 1226 | return |
|
1200 | 1227 | # chop off the topmost part of the string we don't want to see |
|
1201 | 1228 | str_lines = strng.split(os.linesep)[start:] |
|
1202 | 1229 | str_toprint = os.linesep.join(str_lines) |
|
1203 | 1230 | num_newlines = len(str_lines) |
|
1204 | 1231 | len_str = len(str_toprint) |
|
1205 | 1232 | |
|
1206 | 1233 | # Dumb heuristics to guesstimate number of on-screen lines the string |
|
1207 | 1234 | # takes. Very basic, but good enough for docstrings in reasonable |
|
1208 | 1235 | # terminals. If someone later feels like refining it, it's not hard. |
|
1209 | 1236 | numlines = max(num_newlines,int(len_str/80)+1) |
|
1210 | 1237 | |
|
1211 | 1238 | screen_lines_def = 25 # default value if we can't auto-determine |
|
1212 | 1239 | |
|
1213 | 1240 | # auto-determine screen size |
|
1214 | 1241 | if screen_lines <= 0: |
|
1215 | 1242 | if TERM=='xterm': |
|
1216 | 1243 | try: |
|
1217 | 1244 | import curses |
|
1218 | 1245 | if hasattr(curses,'initscr'): |
|
1219 | 1246 | use_curses = 1 |
|
1220 | 1247 | else: |
|
1221 | 1248 | use_curses = 0 |
|
1222 | 1249 | except ImportError: |
|
1223 | 1250 | use_curses = 0 |
|
1224 | 1251 | else: |
|
1225 | 1252 | # curses causes problems on many terminals other than xterm. |
|
1226 | 1253 | use_curses = 0 |
|
1227 | 1254 | if use_curses: |
|
1228 | 1255 | scr = curses.initscr() |
|
1229 | 1256 | screen_lines_real,screen_cols = scr.getmaxyx() |
|
1230 | 1257 | curses.endwin() |
|
1231 | 1258 | screen_lines += screen_lines_real |
|
1232 | 1259 | #print '***Screen size:',screen_lines_real,'lines x',\ |
|
1233 | 1260 | #screen_cols,'columns.' # dbg |
|
1234 | 1261 | else: |
|
1235 | 1262 | screen_lines += screen_lines_def |
|
1236 | 1263 | |
|
1237 | 1264 | #print 'numlines',numlines,'screenlines',screen_lines # dbg |
|
1238 | 1265 | if numlines <= screen_lines : |
|
1239 | 1266 | #print '*** normal print' # dbg |
|
1240 | 1267 | print >>Term.cout, str_toprint |
|
1241 | 1268 | else: |
|
1242 | 1269 | # Try to open pager and default to internal one if that fails. |
|
1243 | 1270 | # All failure modes are tagged as 'retval=1', to match the return |
|
1244 | 1271 | # value of a failed system command. If any intermediate attempt |
|
1245 | 1272 | # sets retval to 1, at the end we resort to our own page_dumb() pager. |
|
1246 | 1273 | pager_cmd = get_pager_cmd(pager_cmd) |
|
1247 | 1274 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) |
|
1248 | 1275 | if os.name == 'nt': |
|
1249 | 1276 | if pager_cmd.startswith('type'): |
|
1250 | 1277 | # The default WinXP 'type' command is failing on complex strings. |
|
1251 | 1278 | retval = 1 |
|
1252 | 1279 | else: |
|
1253 | 1280 | tmpname = tempfile.mktemp('.txt') |
|
1254 | 1281 | tmpfile = file(tmpname,'wt') |
|
1255 | 1282 | tmpfile.write(strng) |
|
1256 | 1283 | tmpfile.close() |
|
1257 | 1284 | cmd = "%s < %s" % (pager_cmd,tmpname) |
|
1258 | 1285 | if os.system(cmd): |
|
1259 | 1286 | retval = 1 |
|
1260 | 1287 | else: |
|
1261 | 1288 | retval = None |
|
1262 | 1289 | os.remove(tmpname) |
|
1263 | 1290 | else: |
|
1264 | 1291 | try: |
|
1265 | 1292 | retval = None |
|
1266 | 1293 | # if I use popen4, things hang. No idea why. |
|
1267 | 1294 | #pager,shell_out = os.popen4(pager_cmd) |
|
1268 | 1295 | pager = os.popen(pager_cmd,'w') |
|
1269 | 1296 | pager.write(strng) |
|
1270 | 1297 | pager.close() |
|
1271 | 1298 | retval = pager.close() # success returns None |
|
1272 | 1299 | except IOError,msg: # broken pipe when user quits |
|
1273 | 1300 | if msg.args == (32,'Broken pipe'): |
|
1274 | 1301 | retval = None |
|
1275 | 1302 | else: |
|
1276 | 1303 | retval = 1 |
|
1277 | 1304 | except OSError: |
|
1278 | 1305 | # Other strange problems, sometimes seen in Win2k/cygwin |
|
1279 | 1306 | retval = 1 |
|
1280 | 1307 | if retval is not None: |
|
1281 | 1308 | page_dumb(strng,screen_lines=screen_lines) |
|
1282 | 1309 | |
|
1283 | 1310 | #---------------------------------------------------------------------------- |
|
1284 | 1311 | def page_file(fname,start = 0, pager_cmd = None): |
|
1285 | 1312 | """Page a file, using an optional pager command and starting line. |
|
1286 | 1313 | """ |
|
1287 | 1314 | |
|
1288 | 1315 | pager_cmd = get_pager_cmd(pager_cmd) |
|
1289 | 1316 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) |
|
1290 | 1317 | |
|
1291 | 1318 | try: |
|
1292 | 1319 | if os.environ['TERM'] in ['emacs','dumb']: |
|
1293 | 1320 | raise EnvironmentError |
|
1294 | 1321 | xsys(pager_cmd + ' ' + fname) |
|
1295 | 1322 | except: |
|
1296 | 1323 | try: |
|
1297 | 1324 | if start > 0: |
|
1298 | 1325 | start -= 1 |
|
1299 | 1326 | page(open(fname).read(),start) |
|
1300 | 1327 | except: |
|
1301 | 1328 | print 'Unable to show file',`fname` |
|
1302 | 1329 | |
|
1303 | 1330 | #---------------------------------------------------------------------------- |
|
1304 | 1331 | def snip_print(str,width = 75,print_full = 0,header = ''): |
|
1305 | 1332 | """Print a string snipping the midsection to fit in width. |
|
1306 | 1333 | |
|
1307 | 1334 | print_full: mode control: |
|
1308 | 1335 | - 0: only snip long strings |
|
1309 | 1336 | - 1: send to page() directly. |
|
1310 | 1337 | - 2: snip long strings and ask for full length viewing with page() |
|
1311 | 1338 | Return 1 if snipping was necessary, 0 otherwise.""" |
|
1312 | 1339 | |
|
1313 | 1340 | if print_full == 1: |
|
1314 | 1341 | page(header+str) |
|
1315 | 1342 | return 0 |
|
1316 | 1343 | |
|
1317 | 1344 | print header, |
|
1318 | 1345 | if len(str) < width: |
|
1319 | 1346 | print str |
|
1320 | 1347 | snip = 0 |
|
1321 | 1348 | else: |
|
1322 | 1349 | whalf = int((width -5)/2) |
|
1323 | 1350 | print str[:whalf] + ' <...> ' + str[-whalf:] |
|
1324 | 1351 | snip = 1 |
|
1325 | 1352 | if snip and print_full == 2: |
|
1326 | 1353 | if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y': |
|
1327 | 1354 | page(str) |
|
1328 | 1355 | return snip |
|
1329 | 1356 | |
|
1330 | 1357 | #**************************************************************************** |
|
1331 | 1358 | # lists, dicts and structures |
|
1332 | 1359 | |
|
1333 | 1360 | def belong(candidates,checklist): |
|
1334 | 1361 | """Check whether a list of items appear in a given list of options. |
|
1335 | 1362 | |
|
1336 | 1363 | Returns a list of 1 and 0, one for each candidate given.""" |
|
1337 | 1364 | |
|
1338 | 1365 | return [x in checklist for x in candidates] |
|
1339 | 1366 | |
|
1340 | 1367 | #---------------------------------------------------------------------------- |
|
1341 | 1368 | def uniq_stable(elems): |
|
1342 | 1369 | """uniq_stable(elems) -> list |
|
1343 | 1370 | |
|
1344 | 1371 | Return from an iterable, a list of all the unique elements in the input, |
|
1345 | 1372 | but maintaining the order in which they first appear. |
|
1346 | 1373 | |
|
1347 | 1374 | A naive solution to this problem which just makes a dictionary with the |
|
1348 | 1375 | elements as keys fails to respect the stability condition, since |
|
1349 | 1376 | dictionaries are unsorted by nature. |
|
1350 | 1377 | |
|
1351 | 1378 | Note: All elements in the input must be valid dictionary keys for this |
|
1352 | 1379 | routine to work, as it internally uses a dictionary for efficiency |
|
1353 | 1380 | reasons.""" |
|
1354 | 1381 | |
|
1355 | 1382 | unique = [] |
|
1356 | 1383 | unique_dict = {} |
|
1357 | 1384 | for nn in elems: |
|
1358 | 1385 | if nn not in unique_dict: |
|
1359 | 1386 | unique.append(nn) |
|
1360 | 1387 | unique_dict[nn] = None |
|
1361 | 1388 | return unique |
|
1362 | 1389 | |
|
1363 | 1390 | #---------------------------------------------------------------------------- |
|
1364 | 1391 | class NLprinter: |
|
1365 | 1392 | """Print an arbitrarily nested list, indicating index numbers. |
|
1366 | 1393 | |
|
1367 | 1394 | An instance of this class called nlprint is available and callable as a |
|
1368 | 1395 | function. |
|
1369 | 1396 | |
|
1370 | 1397 | nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent' |
|
1371 | 1398 | and using 'sep' to separate the index from the value. """ |
|
1372 | 1399 | |
|
1373 | 1400 | def __init__(self): |
|
1374 | 1401 | self.depth = 0 |
|
1375 | 1402 | |
|
1376 | 1403 | def __call__(self,lst,pos='',**kw): |
|
1377 | 1404 | """Prints the nested list numbering levels.""" |
|
1378 | 1405 | kw.setdefault('indent',' ') |
|
1379 | 1406 | kw.setdefault('sep',': ') |
|
1380 | 1407 | kw.setdefault('start',0) |
|
1381 | 1408 | kw.setdefault('stop',len(lst)) |
|
1382 | 1409 | # we need to remove start and stop from kw so they don't propagate |
|
1383 | 1410 | # into a recursive call for a nested list. |
|
1384 | 1411 | start = kw['start']; del kw['start'] |
|
1385 | 1412 | stop = kw['stop']; del kw['stop'] |
|
1386 | 1413 | if self.depth == 0 and 'header' in kw.keys(): |
|
1387 | 1414 | print kw['header'] |
|
1388 | 1415 | |
|
1389 | 1416 | for idx in range(start,stop): |
|
1390 | 1417 | elem = lst[idx] |
|
1391 | 1418 | if type(elem)==type([]): |
|
1392 | 1419 | self.depth += 1 |
|
1393 | 1420 | self.__call__(elem,itpl('$pos$idx,'),**kw) |
|
1394 | 1421 | self.depth -= 1 |
|
1395 | 1422 | else: |
|
1396 | 1423 | printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem') |
|
1397 | 1424 | |
|
1398 | 1425 | nlprint = NLprinter() |
|
1399 | 1426 | #---------------------------------------------------------------------------- |
|
1400 | 1427 | def all_belong(candidates,checklist): |
|
1401 | 1428 | """Check whether a list of items ALL appear in a given list of options. |
|
1402 | 1429 | |
|
1403 | 1430 | Returns a single 1 or 0 value.""" |
|
1404 | 1431 | |
|
1405 | 1432 | return 1-(0 in [x in checklist for x in candidates]) |
|
1406 | 1433 | |
|
1407 | 1434 | #---------------------------------------------------------------------------- |
|
1408 | 1435 | def sort_compare(lst1,lst2,inplace = 1): |
|
1409 | 1436 | """Sort and compare two lists. |
|
1410 | 1437 | |
|
1411 | 1438 | By default it does it in place, thus modifying the lists. Use inplace = 0 |
|
1412 | 1439 | to avoid that (at the cost of temporary copy creation).""" |
|
1413 | 1440 | if not inplace: |
|
1414 | 1441 | lst1 = lst1[:] |
|
1415 | 1442 | lst2 = lst2[:] |
|
1416 | 1443 | lst1.sort(); lst2.sort() |
|
1417 | 1444 | return lst1 == lst2 |
|
1418 | 1445 | |
|
1419 | 1446 | #---------------------------------------------------------------------------- |
|
1420 | 1447 | def mkdict(**kwargs): |
|
1421 | 1448 | """Return a dict from a keyword list. |
|
1422 | 1449 | |
|
1423 | 1450 | It's just syntactic sugar for making ditcionary creation more convenient: |
|
1424 | 1451 | # the standard way |
|
1425 | 1452 | >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 } |
|
1426 | 1453 | # a cleaner way |
|
1427 | 1454 | >>>data = dict(red=1, green=2, blue=3) |
|
1428 | 1455 | |
|
1429 | 1456 | If you need more than this, look at the Struct() class.""" |
|
1430 | 1457 | |
|
1431 | 1458 | return kwargs |
|
1432 | 1459 | |
|
1433 | 1460 | #---------------------------------------------------------------------------- |
|
1434 | 1461 | def list2dict(lst): |
|
1435 | 1462 | """Takes a list of (key,value) pairs and turns it into a dict.""" |
|
1436 | 1463 | |
|
1437 | 1464 | dic = {} |
|
1438 | 1465 | for k,v in lst: dic[k] = v |
|
1439 | 1466 | return dic |
|
1440 | 1467 | |
|
1441 | 1468 | #---------------------------------------------------------------------------- |
|
1442 | 1469 | def list2dict2(lst,default=''): |
|
1443 | 1470 | """Takes a list and turns it into a dict. |
|
1444 | 1471 | Much slower than list2dict, but more versatile. This version can take |
|
1445 | 1472 | lists with sublists of arbitrary length (including sclars).""" |
|
1446 | 1473 | |
|
1447 | 1474 | dic = {} |
|
1448 | 1475 | for elem in lst: |
|
1449 | 1476 | if type(elem) in (types.ListType,types.TupleType): |
|
1450 | 1477 | size = len(elem) |
|
1451 | 1478 | if size == 0: |
|
1452 | 1479 | pass |
|
1453 | 1480 | elif size == 1: |
|
1454 | 1481 | dic[elem] = default |
|
1455 | 1482 | else: |
|
1456 | 1483 | k,v = elem[0], elem[1:] |
|
1457 | 1484 | if len(v) == 1: v = v[0] |
|
1458 | 1485 | dic[k] = v |
|
1459 | 1486 | else: |
|
1460 | 1487 | dic[elem] = default |
|
1461 | 1488 | return dic |
|
1462 | 1489 | |
|
1463 | 1490 | #---------------------------------------------------------------------------- |
|
1464 | 1491 | def flatten(seq): |
|
1465 | 1492 | """Flatten a list of lists (NOT recursive, only works for 2d lists).""" |
|
1466 | 1493 | |
|
1467 | 1494 | # bug in python??? (YES. Fixed in 2.2, let's leave the kludgy fix in). |
|
1468 | 1495 | |
|
1469 | 1496 | # if the x=0 isn't made, a *global* variable x is left over after calling |
|
1470 | 1497 | # this function, with the value of the last element in the return |
|
1471 | 1498 | # list. This does seem like a bug big time to me. |
|
1472 | 1499 | |
|
1473 | 1500 | # the problem is fixed with the x=0, which seems to force the creation of |
|
1474 | 1501 | # a local name |
|
1475 | 1502 | |
|
1476 | 1503 | x = 0 |
|
1477 | 1504 | return [x for subseq in seq for x in subseq] |
|
1478 | 1505 | |
|
1479 | 1506 | #---------------------------------------------------------------------------- |
|
1480 | 1507 | def get_slice(seq,start=0,stop=None,step=1): |
|
1481 | 1508 | """Get a slice of a sequence with variable step. Specify start,stop,step.""" |
|
1482 | 1509 | if stop == None: |
|
1483 | 1510 | stop = len(seq) |
|
1484 | 1511 | item = lambda i: seq[i] |
|
1485 | 1512 | return map(item,xrange(start,stop,step)) |
|
1486 | 1513 | |
|
1487 | 1514 | #---------------------------------------------------------------------------- |
|
1488 | 1515 | def chop(seq,size): |
|
1489 | 1516 | """Chop a sequence into chunks of the given size.""" |
|
1490 | 1517 | chunk = lambda i: seq[i:i+size] |
|
1491 | 1518 | return map(chunk,xrange(0,len(seq),size)) |
|
1492 | 1519 | |
|
1493 | 1520 | #---------------------------------------------------------------------------- |
|
1494 | 1521 | def with(object, **args): |
|
1495 | 1522 | """Set multiple attributes for an object, similar to Pascal's with. |
|
1496 | 1523 | |
|
1497 | 1524 | Example: |
|
1498 | 1525 | with(jim, |
|
1499 | 1526 | born = 1960, |
|
1500 | 1527 | haircolour = 'Brown', |
|
1501 | 1528 | eyecolour = 'Green') |
|
1502 | 1529 | |
|
1503 | 1530 | Credit: Greg Ewing, in |
|
1504 | 1531 | http://mail.python.org/pipermail/python-list/2001-May/040703.html""" |
|
1505 | 1532 | |
|
1506 | 1533 | object.__dict__.update(args) |
|
1507 | 1534 | |
|
1508 | 1535 | #---------------------------------------------------------------------------- |
|
1509 | 1536 | def setattr_list(obj,alist,nspace = None): |
|
1510 | 1537 | """Set a list of attributes for an object taken from a namespace. |
|
1511 | 1538 | |
|
1512 | 1539 | setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in |
|
1513 | 1540 | alist with their values taken from nspace, which must be a dict (something |
|
1514 | 1541 | like locals() will often do) If nspace isn't given, locals() of the |
|
1515 | 1542 | *caller* is used, so in most cases you can omit it. |
|
1516 | 1543 | |
|
1517 | 1544 | Note that alist can be given as a string, which will be automatically |
|
1518 | 1545 | split into a list on whitespace. If given as a list, it must be a list of |
|
1519 | 1546 | *strings* (the variable names themselves), not of variables.""" |
|
1520 | 1547 | |
|
1521 | 1548 | # this grabs the local variables from the *previous* call frame -- that is |
|
1522 | 1549 | # the locals from the function that called setattr_list(). |
|
1523 | 1550 | # - snipped from weave.inline() |
|
1524 | 1551 | if nspace is None: |
|
1525 | 1552 | call_frame = sys._getframe().f_back |
|
1526 | 1553 | nspace = call_frame.f_locals |
|
1527 | 1554 | |
|
1528 | 1555 | if type(alist) in StringTypes: |
|
1529 | 1556 | alist = alist.split() |
|
1530 | 1557 | for attr in alist: |
|
1531 | 1558 | val = eval(attr,nspace) |
|
1532 | 1559 | setattr(obj,attr,val) |
|
1533 | 1560 | |
|
1534 | 1561 | #---------------------------------------------------------------------------- |
|
1535 | 1562 | def getattr_list(obj,alist,*args): |
|
1536 | 1563 | """getattr_list(obj,alist[, default]) -> attribute list. |
|
1537 | 1564 | |
|
1538 | 1565 | Get a list of named attributes for an object. When a default argument is |
|
1539 | 1566 | given, it is returned when the attribute doesn't exist; without it, an |
|
1540 | 1567 | exception is raised in that case. |
|
1541 | 1568 | |
|
1542 | 1569 | Note that alist can be given as a string, which will be automatically |
|
1543 | 1570 | split into a list on whitespace. If given as a list, it must be a list of |
|
1544 | 1571 | *strings* (the variable names themselves), not of variables.""" |
|
1545 | 1572 | |
|
1546 | 1573 | if type(alist) in StringTypes: |
|
1547 | 1574 | alist = alist.split() |
|
1548 | 1575 | if args: |
|
1549 | 1576 | if len(args)==1: |
|
1550 | 1577 | default = args[0] |
|
1551 | 1578 | return map(lambda attr: getattr(obj,attr,default),alist) |
|
1552 | 1579 | else: |
|
1553 | 1580 | raise ValueError,'getattr_list() takes only one optional argument' |
|
1554 | 1581 | else: |
|
1555 | 1582 | return map(lambda attr: getattr(obj,attr),alist) |
|
1556 | 1583 | |
|
1557 | 1584 | #---------------------------------------------------------------------------- |
|
1558 | 1585 | def map_method(method,object_list,*argseq,**kw): |
|
1559 | 1586 | """map_method(method,object_list,*args,**kw) -> list |
|
1560 | 1587 | |
|
1561 | 1588 | Return a list of the results of applying the methods to the items of the |
|
1562 | 1589 | argument sequence(s). If more than one sequence is given, the method is |
|
1563 | 1590 | called with an argument list consisting of the corresponding item of each |
|
1564 | 1591 | sequence. All sequences must be of the same length. |
|
1565 | 1592 | |
|
1566 | 1593 | Keyword arguments are passed verbatim to all objects called. |
|
1567 | 1594 | |
|
1568 | 1595 | This is Python code, so it's not nearly as fast as the builtin map().""" |
|
1569 | 1596 | |
|
1570 | 1597 | out_list = [] |
|
1571 | 1598 | idx = 0 |
|
1572 | 1599 | for object in object_list: |
|
1573 | 1600 | try: |
|
1574 | 1601 | handler = getattr(object, method) |
|
1575 | 1602 | except AttributeError: |
|
1576 | 1603 | out_list.append(None) |
|
1577 | 1604 | else: |
|
1578 | 1605 | if argseq: |
|
1579 | 1606 | args = map(lambda lst:lst[idx],argseq) |
|
1580 | 1607 | #print 'ob',object,'hand',handler,'ar',args # dbg |
|
1581 | 1608 | out_list.append(handler(args,**kw)) |
|
1582 | 1609 | else: |
|
1583 | 1610 | out_list.append(handler(**kw)) |
|
1584 | 1611 | idx += 1 |
|
1585 | 1612 | return out_list |
|
1586 | 1613 | |
|
1587 | 1614 | #---------------------------------------------------------------------------- |
|
1615 | def import_fail_info(mod_name,fns=None): | |
|
1616 | """Inform load failure for a module.""" | |
|
1617 | ||
|
1618 | if fns == None: | |
|
1619 | warn("Loading of %s failed.\n" % (mod_name,)) | |
|
1620 | else: | |
|
1621 | warn("Loading of %s from %s failed.\n" % (fns,mod_name)) | |
|
1622 | ||
|
1623 | #---------------------------------------------------------------------------- | |
|
1588 | 1624 | # Proposed popitem() extension, written as a method |
|
1589 | 1625 | |
|
1590 | 1626 | class NotGiven: pass |
|
1591 | 1627 | |
|
1592 | 1628 | def popkey(dct,key,default=NotGiven): |
|
1593 | 1629 | """Return dct[key] and delete dct[key]. |
|
1594 | 1630 | |
|
1595 | 1631 | If default is given, return it if dct[key] doesn't exist, otherwise raise |
|
1596 | 1632 | KeyError. """ |
|
1597 | 1633 | |
|
1598 | 1634 | try: |
|
1599 | 1635 | val = dct[key] |
|
1600 | 1636 | except KeyError: |
|
1601 | 1637 | if default is NotGiven: |
|
1602 | 1638 | raise |
|
1603 | 1639 | else: |
|
1604 | 1640 | return default |
|
1605 | 1641 | else: |
|
1606 | 1642 | del dct[key] |
|
1607 | 1643 | return val |
|
1608 | 1644 | #*************************** end of file <genutils.py> ********************** |
|
1609 | 1645 |
@@ -1,2060 +1,2035 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | IPython -- An enhanced Interactive Python |
|
4 | 4 | |
|
5 | 5 | Requires Python 2.1 or newer. |
|
6 | 6 | |
|
7 | 7 | This file contains all the classes and helper functions specific to IPython. |
|
8 | 8 | |
|
9 |
$Id: iplib.py 96 |
|
|
9 | $Id: iplib.py 967 2005-12-29 09:02:13Z fperez $ | |
|
10 | 10 | """ |
|
11 | 11 | |
|
12 | 12 | #***************************************************************************** |
|
13 | 13 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
14 | 14 | # Copyright (C) 2001-2005 Fernando Perez. <fperez@colorado.edu> |
|
15 | 15 | # |
|
16 | 16 | # Distributed under the terms of the BSD License. The full license is in |
|
17 | 17 | # the file COPYING, distributed as part of this software. |
|
18 | 18 | # |
|
19 | 19 | # Note: this code originally subclassed code.InteractiveConsole from the |
|
20 | 20 | # Python standard library. Over time, all of that class has been copied |
|
21 | 21 | # verbatim here for modifications which could not be accomplished by |
|
22 | 22 | # subclassing. At this point, there are no dependencies at all on the code |
|
23 | 23 | # module anymore (it is not even imported). The Python License (sec. 2) |
|
24 | 24 | # allows for this, but it's always nice to acknowledge credit where credit is |
|
25 | 25 | # due. |
|
26 | 26 | #***************************************************************************** |
|
27 | 27 | |
|
28 | 28 | #**************************************************************************** |
|
29 | 29 | # Modules and globals |
|
30 | 30 | |
|
31 | 31 | from __future__ import generators # for 2.2 backwards-compatibility |
|
32 | 32 | |
|
33 | 33 | from IPython import Release |
|
34 | 34 | __author__ = '%s <%s>\n%s <%s>' % \ |
|
35 | 35 | ( Release.authors['Janko'] + Release.authors['Fernando'] ) |
|
36 | 36 | __license__ = Release.license |
|
37 | 37 | __version__ = Release.version |
|
38 | 38 | |
|
39 | 39 | # Python standard modules |
|
40 | 40 | import __main__ |
|
41 | 41 | import __builtin__ |
|
42 | 42 | import StringIO |
|
43 | 43 | import bdb |
|
44 | 44 | import cPickle as pickle |
|
45 | 45 | import codeop |
|
46 | 46 | import exceptions |
|
47 | 47 | import glob |
|
48 | 48 | import inspect |
|
49 | 49 | import keyword |
|
50 | 50 | import new |
|
51 | 51 | import os |
|
52 | 52 | import pdb |
|
53 | 53 | import pydoc |
|
54 | 54 | import re |
|
55 | 55 | import shutil |
|
56 | 56 | import string |
|
57 | 57 | import sys |
|
58 | 58 | import traceback |
|
59 | 59 | import types |
|
60 | 60 | |
|
61 | 61 | from pprint import pprint, pformat |
|
62 | 62 | |
|
63 | 63 | # IPython's own modules |
|
64 | 64 | import IPython |
|
65 | 65 | from IPython import OInspect,PyColorize,ultraTB |
|
66 | 66 | from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names |
|
67 | 67 | from IPython.FakeModule import FakeModule |
|
68 | 68 | from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns |
|
69 | 69 | from IPython.Logger import Logger |
|
70 | 70 | from IPython.Magic import Magic |
|
71 | 71 | from IPython.Prompts import CachedOutput |
|
72 | 72 | from IPython.Struct import Struct |
|
73 | 73 | from IPython.background_jobs import BackgroundJobManager |
|
74 | 74 | from IPython.usage import cmd_line_usage,interactive_usage |
|
75 | 75 | from IPython.genutils import * |
|
76 | 76 | |
|
77 | 77 | # store the builtin raw_input globally, and use this always, in case user code |
|
78 | 78 | # overwrites it (like wx.py.PyShell does) |
|
79 | 79 | raw_input_original = raw_input |
|
80 | 80 | |
|
81 | 81 | #**************************************************************************** |
|
82 | 82 | # Some utility function definitions |
|
83 | 83 | |
|
84 | # This can be replaced with an isspace() call once we drop 2.2 compatibility | |
|
85 | _isspace_match = re.compile(r'^\s+$').match | |
|
86 | def isspace(s): | |
|
87 | return bool(_isspace_match(s)) | |
|
88 | ||
|
89 | def esc_quotes(strng): | |
|
90 | """Return the input string with single and double quotes escaped out""" | |
|
91 | ||
|
92 | return strng.replace('"','\\"').replace("'","\\'") | |
|
93 | ||
|
94 | def import_fail_info(mod_name,fns=None): | |
|
95 | """Inform load failure for a module.""" | |
|
96 | ||
|
97 | if fns == None: | |
|
98 | warn("Loading of %s failed.\n" % (mod_name,)) | |
|
99 | else: | |
|
100 | warn("Loading of %s from %s failed.\n" % (fns,mod_name)) | |
|
101 | ||
|
102 | def qw_lol(indata): | |
|
103 | """qw_lol('a b') -> [['a','b']], | |
|
104 | otherwise it's just a call to qw(). | |
|
105 | ||
|
106 | We need this to make sure the modules_some keys *always* end up as a | |
|
107 | list of lists.""" | |
|
84 | def softspace(file, newvalue): | |
|
85 | """Copied from code.py, to remove the dependency""" | |
|
86 | oldvalue = 0 | |
|
87 | try: | |
|
88 | oldvalue = file.softspace | |
|
89 | except AttributeError: | |
|
90 | pass | |
|
91 | try: | |
|
92 | file.softspace = newvalue | |
|
93 | except (AttributeError, TypeError): | |
|
94 | # "attribute-less object" or "read-only attributes" | |
|
95 | pass | |
|
96 | return oldvalue | |
|
108 | 97 | |
|
109 | if type(indata) in StringTypes: | |
|
110 | return [qw(indata)] | |
|
111 | else: | |
|
112 | return qw(indata) | |
|
98 | #**************************************************************************** | |
|
99 | # These special functions get installed in the builtin namespace, to provide | |
|
100 | # programmatic (pure python) access to magics and aliases. This is important | |
|
101 | # for logging, user scripting, and more. | |
|
113 | 102 | |
|
114 | 103 | def ipmagic(arg_s): |
|
115 | 104 | """Call a magic function by name. |
|
116 | 105 | |
|
117 | 106 | Input: a string containing the name of the magic function to call and any |
|
118 | 107 | additional arguments to be passed to the magic. |
|
119 | 108 | |
|
120 | 109 | ipmagic('name -opt foo bar') is equivalent to typing at the ipython |
|
121 | 110 | prompt: |
|
122 | 111 | |
|
123 | 112 | In[1]: %name -opt foo bar |
|
124 | 113 | |
|
125 | 114 | To call a magic without arguments, simply use ipmagic('name'). |
|
126 | 115 | |
|
127 | 116 | This provides a proper Python function to call IPython's magics in any |
|
128 | 117 | valid Python code you can type at the interpreter, including loops and |
|
129 | 118 | compound statements. It is added by IPython to the Python builtin |
|
130 | 119 | namespace upon initialization.""" |
|
131 | 120 | |
|
132 | 121 | args = arg_s.split(' ',1) |
|
133 | 122 | magic_name = args[0] |
|
134 | 123 | if magic_name.startswith(__IPYTHON__.ESC_MAGIC): |
|
135 | 124 | magic_name = magic_name[1:] |
|
136 | 125 | try: |
|
137 | 126 | magic_args = args[1] |
|
138 | 127 | except IndexError: |
|
139 | 128 | magic_args = '' |
|
140 | 129 | fn = getattr(__IPYTHON__,'magic_'+magic_name,None) |
|
141 | 130 | if fn is None: |
|
142 | 131 | error("Magic function `%s` not found." % magic_name) |
|
143 | 132 | else: |
|
144 | 133 | magic_args = __IPYTHON__.var_expand(magic_args) |
|
145 | 134 | return fn(magic_args) |
|
146 | 135 | |
|
147 | 136 | def ipalias(arg_s): |
|
148 | 137 | """Call an alias by name. |
|
149 | 138 | |
|
150 | 139 | Input: a string containing the name of the alias to call and any |
|
151 | 140 | additional arguments to be passed to the magic. |
|
152 | 141 | |
|
153 | 142 | ipalias('name -opt foo bar') is equivalent to typing at the ipython |
|
154 | 143 | prompt: |
|
155 | 144 | |
|
156 | 145 | In[1]: name -opt foo bar |
|
157 | 146 | |
|
158 | 147 | To call an alias without arguments, simply use ipalias('name'). |
|
159 | 148 | |
|
160 | 149 | This provides a proper Python function to call IPython's aliases in any |
|
161 | 150 | valid Python code you can type at the interpreter, including loops and |
|
162 | 151 | compound statements. It is added by IPython to the Python builtin |
|
163 | 152 | namespace upon initialization.""" |
|
164 | 153 | |
|
165 | 154 | args = arg_s.split(' ',1) |
|
166 | 155 | alias_name = args[0] |
|
167 | 156 | try: |
|
168 | 157 | alias_args = args[1] |
|
169 | 158 | except IndexError: |
|
170 | 159 | alias_args = '' |
|
171 | 160 | if alias_name in __IPYTHON__.alias_table: |
|
172 | 161 | __IPYTHON__.call_alias(alias_name,alias_args) |
|
173 | 162 | else: |
|
174 | 163 | error("Alias `%s` not found." % alias_name) |
|
175 | 164 | |
|
176 | def softspace(file, newvalue): | |
|
177 | """Copied from code.py, to remove the dependency""" | |
|
178 | oldvalue = 0 | |
|
179 | try: | |
|
180 | oldvalue = file.softspace | |
|
181 | except AttributeError: | |
|
182 | pass | |
|
183 | try: | |
|
184 | file.softspace = newvalue | |
|
185 | except (AttributeError, TypeError): | |
|
186 | # "attribute-less object" or "read-only attributes" | |
|
187 | pass | |
|
188 | return oldvalue | |
|
189 | ||
|
190 | ||
|
191 | 165 | #**************************************************************************** |
|
192 | 166 | # Local use exceptions |
|
193 | 167 | class SpaceInInput(exceptions.Exception): pass |
|
194 | 168 | |
|
195 | 169 | #**************************************************************************** |
|
196 | 170 | # Local use classes |
|
197 | 171 | class Bunch: pass |
|
198 | 172 | |
|
199 | 173 | class InputList(list): |
|
200 | 174 | """Class to store user input. |
|
201 | 175 | |
|
202 | 176 | It's basically a list, but slices return a string instead of a list, thus |
|
203 | 177 | allowing things like (assuming 'In' is an instance): |
|
204 | 178 | |
|
205 | 179 | exec In[4:7] |
|
206 | 180 | |
|
207 | 181 | or |
|
208 | 182 | |
|
209 | 183 | exec In[5:9] + In[14] + In[21:25]""" |
|
210 | 184 | |
|
211 | 185 | def __getslice__(self,i,j): |
|
212 | 186 | return ''.join(list.__getslice__(self,i,j)) |
|
213 | 187 | |
|
214 | 188 | class SyntaxTB(ultraTB.ListTB): |
|
215 | 189 | """Extension which holds some state: the last exception value""" |
|
216 | 190 | |
|
217 | 191 | def __init__(self,color_scheme = 'NoColor'): |
|
218 | 192 | ultraTB.ListTB.__init__(self,color_scheme) |
|
219 | 193 | self.last_syntax_error = None |
|
220 | 194 | |
|
221 | 195 | def __call__(self, etype, value, elist): |
|
222 | 196 | self.last_syntax_error = value |
|
223 | 197 | ultraTB.ListTB.__call__(self,etype,value,elist) |
|
224 | 198 | |
|
225 | 199 | def clear_err_state(self): |
|
226 | 200 | """Return the current error state and clear it""" |
|
227 | 201 | e = self.last_syntax_error |
|
228 | 202 | self.last_syntax_error = None |
|
229 | 203 | return e |
|
230 | 204 | |
|
231 | 205 | #**************************************************************************** |
|
232 | 206 | # Main IPython class |
|
233 | 207 | |
|
234 | 208 | # FIXME: the Magic class is a mixin for now, and will unfortunately remain so |
|
235 | 209 | # until a full rewrite is made. I've cleaned all cross-class uses of |
|
236 | 210 | # attributes and methods, but too much user code out there relies on the |
|
237 | 211 | # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage. |
|
238 | 212 | # |
|
239 | 213 | # But at least now, all the pieces have been separated and we could, in |
|
240 | 214 | # principle, stop using the mixin. This will ease the transition to the |
|
241 | 215 | # chainsaw branch. |
|
242 | 216 | |
|
243 | 217 | # For reference, the following is the list of 'self.foo' uses in the Magic |
|
244 | 218 | # class as of 2005-12-28. These are names we CAN'T use in the main ipython |
|
245 | 219 | # class, to prevent clashes. |
|
246 | 220 | |
|
247 | 221 | # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind', |
|
248 | 222 | # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic', |
|
249 | 223 | # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell', |
|
250 | 224 | # 'self.value'] |
|
251 | 225 | |
|
252 | ||
|
253 | 226 | class InteractiveShell(Magic): |
|
254 | 227 | """An enhanced console for Python.""" |
|
255 | 228 | |
|
256 | 229 | # class attribute to indicate whether the class supports threads or not. |
|
257 | 230 | # Subclasses with thread support should override this as needed. |
|
258 | 231 | isthreaded = False |
|
259 | 232 | |
|
260 | 233 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), |
|
261 | 234 | user_ns = None,user_global_ns=None,banner2='', |
|
262 | 235 | custom_exceptions=((),None),embedded=False): |
|
263 | 236 | |
|
264 | 237 | # some minimal strict typechecks. For some core data structures, I |
|
265 | 238 | # want actual basic python types, not just anything that looks like |
|
266 | 239 | # one. This is especially true for namespaces. |
|
267 | 240 | for ns in (user_ns,user_global_ns): |
|
268 | 241 | if ns is not None and type(ns) != types.DictType: |
|
269 | 242 | raise TypeError,'namespace must be a dictionary' |
|
270 | 243 | |
|
271 | 244 | # Put a reference to self in builtins so that any form of embedded or |
|
272 | 245 | # imported code can test for being inside IPython. |
|
273 | 246 | __builtin__.__IPYTHON__ = self |
|
274 | 247 | |
|
275 | 248 | # And load into builtins ipmagic/ipalias as well |
|
276 | 249 | __builtin__.ipmagic = ipmagic |
|
277 | 250 | __builtin__.ipalias = ipalias |
|
278 | 251 | |
|
279 | 252 | # Add to __builtin__ other parts of IPython's public API |
|
280 | 253 | __builtin__.ip_set_hook = self.set_hook |
|
281 | 254 | |
|
282 | 255 | # Keep in the builtins a flag for when IPython is active. We set it |
|
283 | 256 | # with setdefault so that multiple nested IPythons don't clobber one |
|
284 | 257 | # another. Each will increase its value by one upon being activated, |
|
285 | 258 | # which also gives us a way to determine the nesting level. |
|
286 | 259 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) |
|
287 | 260 | |
|
288 | 261 | # Do the intuitively correct thing for quit/exit: we remove the |
|
289 | 262 | # builtins if they exist, and our own prefilter routine will handle |
|
290 | 263 | # these special cases |
|
291 | 264 | try: |
|
292 | 265 | del __builtin__.exit, __builtin__.quit |
|
293 | 266 | except AttributeError: |
|
294 | 267 | pass |
|
295 | 268 | |
|
296 | 269 | # Store the actual shell's name |
|
297 | 270 | self.name = name |
|
298 | 271 | |
|
299 | 272 | # We need to know whether the instance is meant for embedding, since |
|
300 | 273 | # global/local namespaces need to be handled differently in that case |
|
301 | 274 | self.embedded = embedded |
|
302 | 275 | |
|
303 | 276 | # command compiler |
|
304 | 277 | self.compile = codeop.CommandCompiler() |
|
305 | 278 | |
|
306 | 279 | # User input buffer |
|
307 | 280 | self.buffer = [] |
|
308 | 281 | |
|
309 | 282 | # Default name given in compilation of code |
|
310 | 283 | self.filename = '<ipython console>' |
|
311 | 284 | |
|
312 | 285 | # Create the namespace where the user will operate. user_ns is |
|
313 | 286 | # normally the only one used, and it is passed to the exec calls as |
|
314 | 287 | # the locals argument. But we do carry a user_global_ns namespace |
|
315 | 288 | # given as the exec 'globals' argument, This is useful in embedding |
|
316 | 289 | # situations where the ipython shell opens in a context where the |
|
317 | 290 | # distinction between locals and globals is meaningful. |
|
318 | 291 | |
|
319 | 292 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
320 | 293 | # level as a dict instead of a module. This is a manual fix, but I |
|
321 | 294 | # should really track down where the problem is coming from. Alex |
|
322 | 295 | # Schmolck reported this problem first. |
|
323 | 296 | |
|
324 | 297 | # A useful post by Alex Martelli on this topic: |
|
325 | 298 | # Re: inconsistent value from __builtins__ |
|
326 | 299 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
327 | 300 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
328 | 301 | # Gruppen: comp.lang.python |
|
329 | 302 | |
|
330 | 303 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
331 | 304 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
332 | 305 | # > <type 'dict'> |
|
333 | 306 | # > >>> print type(__builtins__) |
|
334 | 307 | # > <type 'module'> |
|
335 | 308 | # > Is this difference in return value intentional? |
|
336 | 309 | |
|
337 | 310 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
338 | 311 | # or a module, and it's been that way for a long time. Whether it's |
|
339 | 312 | # intentional (or sensible), I don't know. In any case, the idea is |
|
340 | 313 | # that if you need to access the built-in namespace directly, you |
|
341 | 314 | # should start with "import __builtin__" (note, no 's') which will |
|
342 | 315 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
343 | 316 | |
|
344 | 317 | if user_ns is None: |
|
345 | 318 | # Set __name__ to __main__ to better match the behavior of the |
|
346 | 319 | # normal interpreter. |
|
347 | 320 | user_ns = {'__name__' :'__main__', |
|
348 | 321 | '__builtins__' : __builtin__, |
|
349 | 322 | } |
|
350 | 323 | |
|
351 | 324 | if user_global_ns is None: |
|
352 | 325 | user_global_ns = {} |
|
353 | 326 | |
|
354 | 327 | # Assign namespaces |
|
355 | 328 | # This is the namespace where all normal user variables live |
|
356 | 329 | self.user_ns = user_ns |
|
357 | 330 | # Embedded instances require a separate namespace for globals. |
|
358 | 331 | # Normally this one is unused by non-embedded instances. |
|
359 | 332 | self.user_global_ns = user_global_ns |
|
360 | 333 | # A namespace to keep track of internal data structures to prevent |
|
361 | 334 | # them from cluttering user-visible stuff. Will be updated later |
|
362 | 335 | self.internal_ns = {} |
|
363 | 336 | |
|
364 | 337 | # Namespace of system aliases. Each entry in the alias |
|
365 | 338 | # table must be a 2-tuple of the form (N,name), where N is the number |
|
366 | 339 | # of positional arguments of the alias. |
|
367 | 340 | self.alias_table = {} |
|
368 | 341 | |
|
369 | 342 | # A table holding all the namespaces IPython deals with, so that |
|
370 | 343 | # introspection facilities can search easily. |
|
371 | 344 | self.ns_table = {'user':user_ns, |
|
372 | 345 | 'user_global':user_global_ns, |
|
373 | 346 | 'alias':self.alias_table, |
|
374 | 347 | 'internal':self.internal_ns, |
|
375 | 348 | 'builtin':__builtin__.__dict__ |
|
376 | 349 | } |
|
377 | 350 | |
|
378 | 351 | # The user namespace MUST have a pointer to the shell itself. |
|
379 | 352 | self.user_ns[name] = self |
|
380 | 353 | |
|
381 | 354 | # We need to insert into sys.modules something that looks like a |
|
382 | 355 | # module but which accesses the IPython namespace, for shelve and |
|
383 | 356 | # pickle to work interactively. Normally they rely on getting |
|
384 | 357 | # everything out of __main__, but for embedding purposes each IPython |
|
385 | 358 | # instance has its own private namespace, so we can't go shoving |
|
386 | 359 | # everything into __main__. |
|
387 | 360 | |
|
388 | 361 | # note, however, that we should only do this for non-embedded |
|
389 | 362 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
390 | 363 | # namespace. Embedded instances, on the other hand, should not do |
|
391 | 364 | # this because they need to manage the user local/global namespaces |
|
392 | 365 | # only, but they live within a 'normal' __main__ (meaning, they |
|
393 | 366 | # shouldn't overtake the execution environment of the script they're |
|
394 | 367 | # embedded in). |
|
395 | 368 | |
|
396 | 369 | if not embedded: |
|
397 | 370 | try: |
|
398 | 371 | main_name = self.user_ns['__name__'] |
|
399 | 372 | except KeyError: |
|
400 | 373 | raise KeyError,'user_ns dictionary MUST have a "__name__" key' |
|
401 | 374 | else: |
|
402 | 375 | #print "pickle hack in place" # dbg |
|
403 | 376 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
404 | 377 | |
|
405 | 378 | # List of input with multi-line handling. |
|
406 | 379 | # Fill its zero entry, user counter starts at 1 |
|
407 | 380 | self.input_hist = InputList(['\n']) |
|
408 | 381 | |
|
409 | 382 | # list of visited directories |
|
410 | 383 | try: |
|
411 | 384 | self.dir_hist = [os.getcwd()] |
|
412 | 385 | except IOError, e: |
|
413 | 386 | self.dir_hist = [] |
|
414 | 387 | |
|
415 | 388 | # dict of output history |
|
416 | 389 | self.output_hist = {} |
|
417 | 390 | |
|
418 | 391 | # dict of things NOT to alias (keywords, builtins and some magics) |
|
419 | 392 | no_alias = {} |
|
420 | 393 | no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias'] |
|
421 | 394 | for key in keyword.kwlist + no_alias_magics: |
|
422 | 395 | no_alias[key] = 1 |
|
423 | 396 | no_alias.update(__builtin__.__dict__) |
|
424 | 397 | self.no_alias = no_alias |
|
425 | 398 | |
|
426 | 399 | # make global variables for user access to these |
|
427 | 400 | self.user_ns['_ih'] = self.input_hist |
|
428 | 401 | self.user_ns['_oh'] = self.output_hist |
|
429 | 402 | self.user_ns['_dh'] = self.dir_hist |
|
430 | 403 | |
|
431 | 404 | # user aliases to input and output histories |
|
432 | 405 | self.user_ns['In'] = self.input_hist |
|
433 | 406 | self.user_ns['Out'] = self.output_hist |
|
434 | 407 | |
|
435 | 408 | # Object variable to store code object waiting execution. This is |
|
436 | 409 | # used mainly by the multithreaded shells, but it can come in handy in |
|
437 | 410 | # other situations. No need to use a Queue here, since it's a single |
|
438 | 411 | # item which gets cleared once run. |
|
439 | 412 | self.code_to_run = None |
|
440 | 413 | |
|
441 | 414 | # Job manager (for jobs run as background threads) |
|
442 | 415 | self.jobs = BackgroundJobManager() |
|
443 | 416 | # Put the job manager into builtins so it's always there. |
|
444 | 417 | __builtin__.jobs = self.jobs |
|
445 | 418 | |
|
446 | 419 | # escapes for automatic behavior on the command line |
|
447 | 420 | self.ESC_SHELL = '!' |
|
448 | 421 | self.ESC_HELP = '?' |
|
449 | 422 | self.ESC_MAGIC = '%' |
|
450 | 423 | self.ESC_QUOTE = ',' |
|
451 | 424 | self.ESC_QUOTE2 = ';' |
|
452 | 425 | self.ESC_PAREN = '/' |
|
453 | 426 | |
|
454 | 427 | # And their associated handlers |
|
455 | 428 | self.esc_handlers = {self.ESC_PAREN : self.handle_auto, |
|
456 | 429 | self.ESC_QUOTE : self.handle_auto, |
|
457 | 430 | self.ESC_QUOTE2 : self.handle_auto, |
|
458 | 431 | self.ESC_MAGIC : self.handle_magic, |
|
459 | 432 | self.ESC_HELP : self.handle_help, |
|
460 | 433 | self.ESC_SHELL : self.handle_shell_escape, |
|
461 | 434 | } |
|
462 | 435 | |
|
463 | 436 | # class initializations |
|
464 | 437 | Magic.__init__(self,self) |
|
465 | 438 | |
|
466 | 439 | # Python source parser/formatter for syntax highlighting |
|
467 | 440 | pyformat = PyColorize.Parser().format |
|
468 | 441 | self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors']) |
|
469 | 442 | |
|
470 | 443 | # hooks holds pointers used for user-side customizations |
|
471 | 444 | self.hooks = Struct() |
|
472 | 445 | |
|
473 | 446 | # Set all default hooks, defined in the IPython.hooks module. |
|
474 | 447 | hooks = IPython.hooks |
|
475 | 448 | for hook_name in hooks.__all__: |
|
476 | 449 | self.set_hook(hook_name,getattr(hooks,hook_name)) |
|
477 | 450 | |
|
478 | 451 | # Flag to mark unconditional exit |
|
479 | 452 | self.exit_now = False |
|
480 | 453 | |
|
481 | 454 | self.usage_min = """\ |
|
482 | 455 | An enhanced console for Python. |
|
483 | 456 | Some of its features are: |
|
484 | 457 | - Readline support if the readline library is present. |
|
485 | 458 | - Tab completion in the local namespace. |
|
486 | 459 | - Logging of input, see command-line options. |
|
487 | 460 | - System shell escape via ! , eg !ls. |
|
488 | 461 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) |
|
489 | 462 | - Keeps track of locally defined variables via %who, %whos. |
|
490 | 463 | - Show object information with a ? eg ?x or x? (use ?? for more info). |
|
491 | 464 | """ |
|
492 | 465 | if usage: self.usage = usage |
|
493 | 466 | else: self.usage = self.usage_min |
|
494 | 467 | |
|
495 | 468 | # Storage |
|
496 | 469 | self.rc = rc # This will hold all configuration information |
|
497 | 470 | self.inputcache = [] |
|
498 | 471 | self._boundcache = [] |
|
499 | 472 | self.pager = 'less' |
|
500 | 473 | # temporary files used for various purposes. Deleted at exit. |
|
501 | 474 | self.tempfiles = [] |
|
502 | 475 | |
|
503 | 476 | # Keep track of readline usage (later set by init_readline) |
|
504 | 477 | self.has_readline = False |
|
505 | 478 | |
|
506 | 479 | # template for logfile headers. It gets resolved at runtime by the |
|
507 | 480 | # logstart method. |
|
508 | 481 | self.loghead_tpl = \ |
|
509 | 482 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** |
|
510 | 483 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW |
|
511 | 484 | #log# opts = %s |
|
512 | 485 | #log# args = %s |
|
513 | 486 | #log# It is safe to make manual edits below here. |
|
514 | 487 | #log#----------------------------------------------------------------------- |
|
515 | 488 | """ |
|
516 | 489 | # for pushd/popd management |
|
517 | 490 | try: |
|
518 | 491 | self.home_dir = get_home_dir() |
|
519 | 492 | except HomeDirError,msg: |
|
520 | 493 | fatal(msg) |
|
521 | 494 | |
|
522 | 495 | self.dir_stack = [os.getcwd().replace(self.home_dir,'~')] |
|
523 | 496 | |
|
524 | 497 | # Functions to call the underlying shell. |
|
525 | 498 | |
|
526 | 499 | # utility to expand user variables via Itpl |
|
527 | 500 | self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'), |
|
528 | 501 | self.user_ns)) |
|
529 | 502 | # The first is similar to os.system, but it doesn't return a value, |
|
530 | 503 | # and it allows interpolation of variables in the user's namespace. |
|
531 | 504 | self.system = lambda cmd: shell(self.var_expand(cmd), |
|
532 | 505 | header='IPython system call: ', |
|
533 | 506 | verbose=self.rc.system_verbose) |
|
534 | 507 | # These are for getoutput and getoutputerror: |
|
535 | 508 | self.getoutput = lambda cmd: \ |
|
536 | 509 | getoutput(self.var_expand(cmd), |
|
537 | 510 | header='IPython system call: ', |
|
538 | 511 | verbose=self.rc.system_verbose) |
|
539 | 512 | self.getoutputerror = lambda cmd: \ |
|
540 | 513 | getoutputerror(str(ItplNS(cmd.replace('#','\#'), |
|
541 | 514 | self.user_ns)), |
|
542 | 515 | header='IPython system call: ', |
|
543 | 516 | verbose=self.rc.system_verbose) |
|
544 | 517 | |
|
545 | 518 | # RegExp for splitting line contents into pre-char//first |
|
546 | 519 | # word-method//rest. For clarity, each group in on one line. |
|
547 | 520 | |
|
548 | 521 | # WARNING: update the regexp if the above escapes are changed, as they |
|
549 | 522 | # are hardwired in. |
|
550 | 523 | |
|
551 | 524 | # Don't get carried away with trying to make the autocalling catch too |
|
552 | 525 | # much: it's better to be conservative rather than to trigger hidden |
|
553 | 526 | # evals() somewhere and end up causing side effects. |
|
554 | 527 | |
|
555 | 528 | self.line_split = re.compile(r'^([\s*,;/])' |
|
556 | 529 | r'([\?\w\.]+\w*\s*)' |
|
557 | 530 | r'(\(?.*$)') |
|
558 | 531 | |
|
559 | 532 | # Original re, keep around for a while in case changes break something |
|
560 | 533 | #self.line_split = re.compile(r'(^[\s*!\?%,/]?)' |
|
561 | 534 | # r'(\s*[\?\w\.]+\w*\s*)' |
|
562 | 535 | # r'(\(?.*$)') |
|
563 | 536 | |
|
564 | 537 | # RegExp to identify potential function names |
|
565 | 538 | self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$') |
|
566 | 539 | # RegExp to exclude strings with this start from autocalling |
|
567 | 540 | self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ') |
|
568 | 541 | |
|
569 | 542 | # try to catch also methods for stuff in lists/tuples/dicts: off |
|
570 | 543 | # (experimental). For this to work, the line_split regexp would need |
|
571 | 544 | # to be modified so it wouldn't break things at '['. That line is |
|
572 | 545 | # nasty enough that I shouldn't change it until I can test it _well_. |
|
573 | 546 | #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$') |
|
574 | 547 | |
|
575 | 548 | # keep track of where we started running (mainly for crash post-mortem) |
|
576 | 549 | self.starting_dir = os.getcwd() |
|
577 | 550 | |
|
578 | 551 | # Various switches which can be set |
|
579 | 552 | self.CACHELENGTH = 5000 # this is cheap, it's just text |
|
580 | 553 | self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__ |
|
581 | 554 | self.banner2 = banner2 |
|
582 | 555 | |
|
583 | 556 | # TraceBack handlers: |
|
584 | 557 | |
|
585 | 558 | # Syntax error handler. |
|
586 | 559 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') |
|
587 | 560 | |
|
588 | 561 | # The interactive one is initialized with an offset, meaning we always |
|
589 | 562 | # want to remove the topmost item in the traceback, which is our own |
|
590 | 563 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
591 | 564 | self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain', |
|
592 | 565 | color_scheme='NoColor', |
|
593 | 566 | tb_offset = 1) |
|
594 | 567 | |
|
595 | 568 | # IPython itself shouldn't crash. This will produce a detailed |
|
596 | 569 | # post-mortem if it does. But we only install the crash handler for |
|
597 | 570 | # non-threaded shells, the threaded ones use a normal verbose reporter |
|
598 | 571 | # and lose the crash handler. This is because exceptions in the main |
|
599 | 572 | # thread (such as in GUI code) propagate directly to sys.excepthook, |
|
600 | 573 | # and there's no point in printing crash dumps for every user exception. |
|
601 | 574 | if self.isthreaded: |
|
602 | 575 | sys.excepthook = ultraTB.FormattedTB() |
|
603 | 576 | else: |
|
604 | 577 | from IPython import CrashHandler |
|
605 | 578 | sys.excepthook = CrashHandler.CrashHandler(self) |
|
606 | 579 | |
|
607 | 580 | # The instance will store a pointer to this, so that runtime code |
|
608 | 581 | # (such as magics) can access it. This is because during the |
|
609 | 582 | # read-eval loop, it gets temporarily overwritten (to deal with GUI |
|
610 | 583 | # frameworks). |
|
611 | 584 | self.sys_excepthook = sys.excepthook |
|
612 | 585 | |
|
613 | 586 | # and add any custom exception handlers the user may have specified |
|
614 | 587 | self.set_custom_exc(*custom_exceptions) |
|
615 | 588 | |
|
616 | 589 | # Object inspector |
|
617 | 590 | self.inspector = OInspect.Inspector(OInspect.InspectColors, |
|
618 | 591 | PyColorize.ANSICodeColors, |
|
619 | 592 | 'NoColor') |
|
620 | 593 | # indentation management |
|
621 | 594 | self.autoindent = False |
|
622 | 595 | self.indent_current_nsp = 0 |
|
623 | 596 | self.indent_current = '' # actual indent string |
|
624 | 597 | |
|
625 | 598 | # Make some aliases automatically |
|
626 | 599 | # Prepare list of shell aliases to auto-define |
|
627 | 600 | if os.name == 'posix': |
|
628 | 601 | auto_alias = ('mkdir mkdir', 'rmdir rmdir', |
|
629 | 602 | 'mv mv -i','rm rm -i','cp cp -i', |
|
630 | 603 | 'cat cat','less less','clear clear', |
|
631 | 604 | # a better ls |
|
632 | 605 | 'ls ls -F', |
|
633 | 606 | # long ls |
|
634 | 607 | 'll ls -lF', |
|
635 | 608 | # color ls |
|
636 | 609 | 'lc ls -F -o --color', |
|
637 | 610 | # ls normal files only |
|
638 | 611 | 'lf ls -F -o --color %l | grep ^-', |
|
639 | 612 | # ls symbolic links |
|
640 | 613 | 'lk ls -F -o --color %l | grep ^l', |
|
641 | 614 | # directories or links to directories, |
|
642 | 615 | 'ldir ls -F -o --color %l | grep /$', |
|
643 | 616 | # things which are executable |
|
644 | 617 | 'lx ls -F -o --color %l | grep ^-..x', |
|
645 | 618 | ) |
|
646 | 619 | elif os.name in ['nt','dos']: |
|
647 | 620 | auto_alias = ('dir dir /on', 'ls dir /on', |
|
648 | 621 | 'ddir dir /ad /on', 'ldir dir /ad /on', |
|
649 | 622 | 'mkdir mkdir','rmdir rmdir','echo echo', |
|
650 | 623 | 'ren ren','cls cls','copy copy') |
|
651 | 624 | else: |
|
652 | 625 | auto_alias = () |
|
653 | 626 | self.auto_alias = map(lambda s:s.split(None,1),auto_alias) |
|
654 | 627 | # Call the actual (public) initializer |
|
655 | 628 | self.init_auto_alias() |
|
656 | 629 | # end __init__ |
|
657 | 630 | |
|
658 | 631 | def post_config_initialization(self): |
|
659 | 632 | """Post configuration init method |
|
660 | 633 | |
|
661 | 634 | This is called after the configuration files have been processed to |
|
662 | 635 | 'finalize' the initialization.""" |
|
663 | 636 | |
|
664 | 637 | rc = self.rc |
|
665 | 638 | |
|
666 | 639 | # Load readline proper |
|
667 | 640 | if rc.readline: |
|
668 | 641 | self.init_readline() |
|
669 | 642 | |
|
670 | 643 | # log system |
|
671 | 644 | self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate') |
|
672 | 645 | # local shortcut, this is used a LOT |
|
673 | 646 | self.log = self.logger.log |
|
674 | 647 | |
|
675 | 648 | # Initialize cache, set in/out prompts and printing system |
|
676 | 649 | self.outputcache = CachedOutput(self, |
|
677 | 650 | rc.cache_size, |
|
678 | 651 | rc.pprint, |
|
679 | 652 | input_sep = rc.separate_in, |
|
680 | 653 | output_sep = rc.separate_out, |
|
681 | 654 | output_sep2 = rc.separate_out2, |
|
682 | 655 | ps1 = rc.prompt_in1, |
|
683 | 656 | ps2 = rc.prompt_in2, |
|
684 | 657 | ps_out = rc.prompt_out, |
|
685 | 658 | pad_left = rc.prompts_pad_left) |
|
686 | 659 | |
|
687 | 660 | # user may have over-ridden the default print hook: |
|
688 | 661 | try: |
|
689 | 662 | self.outputcache.__class__.display = self.hooks.display |
|
690 | 663 | except AttributeError: |
|
691 | 664 | pass |
|
692 | 665 | |
|
693 | 666 | # I don't like assigning globally to sys, because it means when embedding |
|
694 | 667 | # instances, each embedded instance overrides the previous choice. But |
|
695 | 668 | # sys.displayhook seems to be called internally by exec, so I don't see a |
|
696 | 669 | # way around it. |
|
697 | 670 | sys.displayhook = self.outputcache |
|
698 | 671 | |
|
699 | 672 | # Set user colors (don't do it in the constructor above so that it |
|
700 | 673 | # doesn't crash if colors option is invalid) |
|
701 | 674 | self.magic_colors(rc.colors) |
|
702 | 675 | |
|
703 | 676 | # Set calling of pdb on exceptions |
|
704 | 677 | self.call_pdb = rc.pdb |
|
705 | 678 | |
|
706 | 679 | # Load user aliases |
|
707 | 680 | for alias in rc.alias: |
|
708 | 681 | self.magic_alias(alias) |
|
709 | 682 | |
|
710 | 683 | # dynamic data that survives through sessions |
|
711 | 684 | # XXX make the filename a config option? |
|
712 | 685 | persist_base = 'persist' |
|
713 | 686 | if rc.profile: |
|
714 | 687 | persist_base += '_%s' % rc.profile |
|
715 | 688 | self.persist_fname = os.path.join(rc.ipythondir,persist_base) |
|
716 | 689 | |
|
717 | 690 | try: |
|
718 | 691 | self.persist = pickle.load(file(self.persist_fname)) |
|
719 | 692 | except: |
|
720 | 693 | self.persist = {} |
|
721 | 694 | |
|
722 | 695 | def set_hook(self,name,hook): |
|
723 | 696 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
724 | 697 | |
|
725 | 698 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
726 | 699 | resetting one of these hooks, you can modify IPython's behavior to |
|
727 | 700 | call at runtime your own routines.""" |
|
728 | 701 | |
|
729 | 702 | # At some point in the future, this should validate the hook before it |
|
730 | 703 | # accepts it. Probably at least check that the hook takes the number |
|
731 | 704 | # of args it's supposed to. |
|
732 | 705 | setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__)) |
|
733 | 706 | |
|
734 | 707 | def set_custom_exc(self,exc_tuple,handler): |
|
735 | 708 | """set_custom_exc(exc_tuple,handler) |
|
736 | 709 | |
|
737 | 710 | Set a custom exception handler, which will be called if any of the |
|
738 | 711 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
739 | 712 | runcode() method. |
|
740 | 713 | |
|
741 | 714 | Inputs: |
|
742 | 715 | |
|
743 | 716 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
744 | 717 | handler for. It is very important that you use a tuple, and NOT A |
|
745 | 718 | LIST here, because of the way Python's except statement works. If |
|
746 | 719 | you only want to trap a single exception, use a singleton tuple: |
|
747 | 720 | |
|
748 | 721 | exc_tuple == (MyCustomException,) |
|
749 | 722 | |
|
750 | 723 | - handler: this must be defined as a function with the following |
|
751 | 724 | basic interface: def my_handler(self,etype,value,tb). |
|
752 | 725 | |
|
753 | 726 | This will be made into an instance method (via new.instancemethod) |
|
754 | 727 | of IPython itself, and it will be called if any of the exceptions |
|
755 | 728 | listed in the exc_tuple are caught. If the handler is None, an |
|
756 | 729 | internal basic one is used, which just prints basic info. |
|
757 | 730 | |
|
758 | 731 | WARNING: by putting in your own exception handler into IPython's main |
|
759 | 732 | execution loop, you run a very good chance of nasty crashes. This |
|
760 | 733 | facility should only be used if you really know what you are doing.""" |
|
761 | 734 | |
|
762 | 735 | assert type(exc_tuple)==type(()) , \ |
|
763 | 736 | "The custom exceptions must be given AS A TUPLE." |
|
764 | 737 | |
|
765 | 738 | def dummy_handler(self,etype,value,tb): |
|
766 | 739 | print '*** Simple custom exception handler ***' |
|
767 | 740 | print 'Exception type :',etype |
|
768 | 741 | print 'Exception value:',value |
|
769 | 742 | print 'Traceback :',tb |
|
770 | 743 | print 'Source code :','\n'.join(self.buffer) |
|
771 | 744 | |
|
772 | 745 | if handler is None: handler = dummy_handler |
|
773 | 746 | |
|
774 | 747 | self.CustomTB = new.instancemethod(handler,self,self.__class__) |
|
775 | 748 | self.custom_exceptions = exc_tuple |
|
776 | 749 | |
|
777 | 750 | def set_custom_completer(self,completer,pos=0): |
|
778 | 751 | """set_custom_completer(completer,pos=0) |
|
779 | 752 | |
|
780 | 753 | Adds a new custom completer function. |
|
781 | 754 | |
|
782 | 755 | The position argument (defaults to 0) is the index in the completers |
|
783 | 756 | list where you want the completer to be inserted.""" |
|
784 | 757 | |
|
785 | 758 | newcomp = new.instancemethod(completer,self.Completer, |
|
786 | 759 | self.Completer.__class__) |
|
787 | 760 | self.Completer.matchers.insert(pos,newcomp) |
|
788 | 761 | |
|
789 | 762 | def _get_call_pdb(self): |
|
790 | 763 | return self._call_pdb |
|
791 | 764 | |
|
792 | 765 | def _set_call_pdb(self,val): |
|
793 | 766 | |
|
794 | 767 | if val not in (0,1,False,True): |
|
795 | 768 | raise ValueError,'new call_pdb value must be boolean' |
|
796 | 769 | |
|
797 | 770 | # store value in instance |
|
798 | 771 | self._call_pdb = val |
|
799 | 772 | |
|
800 | 773 | # notify the actual exception handlers |
|
801 | 774 | self.InteractiveTB.call_pdb = val |
|
802 | 775 | if self.isthreaded: |
|
803 | 776 | try: |
|
804 | 777 | self.sys_excepthook.call_pdb = val |
|
805 | 778 | except: |
|
806 | 779 | warn('Failed to activate pdb for threaded exception handler') |
|
807 | 780 | |
|
808 | 781 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
809 | 782 | 'Control auto-activation of pdb at exceptions') |
|
810 | 783 | |
|
811 | 784 | def complete(self,text): |
|
812 | 785 | """Return a sorted list of all possible completions on text. |
|
813 | 786 | |
|
814 | 787 | Inputs: |
|
815 | 788 | |
|
816 | 789 | - text: a string of text to be completed on. |
|
817 | 790 | |
|
818 | 791 | This is a wrapper around the completion mechanism, similar to what |
|
819 | 792 | readline does at the command line when the TAB key is hit. By |
|
820 | 793 | exposing it as a method, it can be used by other non-readline |
|
821 | 794 | environments (such as GUIs) for text completion. |
|
822 | 795 | |
|
823 | 796 | Simple usage example: |
|
824 | 797 | |
|
825 | 798 | In [1]: x = 'hello' |
|
826 | 799 | |
|
827 | 800 | In [2]: __IP.complete('x.l') |
|
828 | 801 | Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']""" |
|
829 | 802 | |
|
830 | 803 | complete = self.Completer.complete |
|
831 | 804 | state = 0 |
|
832 | 805 | # use a dict so we get unique keys, since ipyhton's multiple |
|
833 | 806 | # completers can return duplicates. |
|
834 | 807 | comps = {} |
|
835 | 808 | while True: |
|
836 | 809 | newcomp = complete(text,state) |
|
837 | 810 | if newcomp is None: |
|
838 | 811 | break |
|
839 | 812 | comps[newcomp] = 1 |
|
840 | 813 | state += 1 |
|
841 | 814 | outcomps = comps.keys() |
|
842 | 815 | outcomps.sort() |
|
843 | 816 | return outcomps |
|
844 | 817 | |
|
845 | 818 | def set_completer_frame(self, frame): |
|
846 | 819 | if frame: |
|
847 | 820 | self.Completer.namespace = frame.f_locals |
|
848 | 821 | self.Completer.global_namespace = frame.f_globals |
|
849 | 822 | else: |
|
850 | 823 | self.Completer.namespace = self.user_ns |
|
851 | 824 | self.Completer.global_namespace = self.user_global_ns |
|
852 | 825 | |
|
853 | 826 | def init_auto_alias(self): |
|
854 | 827 | """Define some aliases automatically. |
|
855 | 828 | |
|
856 | 829 | These are ALL parameter-less aliases""" |
|
857 | 830 | for alias,cmd in self.auto_alias: |
|
858 | 831 | self.alias_table[alias] = (0,cmd) |
|
859 | 832 | |
|
860 | 833 | def alias_table_validate(self,verbose=0): |
|
861 | 834 | """Update information about the alias table. |
|
862 | 835 | |
|
863 | 836 | In particular, make sure no Python keywords/builtins are in it.""" |
|
864 | 837 | |
|
865 | 838 | no_alias = self.no_alias |
|
866 | 839 | for k in self.alias_table.keys(): |
|
867 | 840 | if k in no_alias: |
|
868 | 841 | del self.alias_table[k] |
|
869 | 842 | if verbose: |
|
870 | 843 | print ("Deleting alias <%s>, it's a Python " |
|
871 | 844 | "keyword or builtin." % k) |
|
872 | 845 | |
|
873 | 846 | def set_autoindent(self,value=None): |
|
874 | 847 | """Set the autoindent flag, checking for readline support. |
|
875 | 848 | |
|
876 | 849 | If called with no arguments, it acts as a toggle.""" |
|
877 | 850 | |
|
878 | 851 | if not self.has_readline: |
|
879 | 852 | if os.name == 'posix': |
|
880 | 853 | warn("The auto-indent feature requires the readline library") |
|
881 | 854 | self.autoindent = 0 |
|
882 | 855 | return |
|
883 | 856 | if value is None: |
|
884 | 857 | self.autoindent = not self.autoindent |
|
885 | 858 | else: |
|
886 | 859 | self.autoindent = value |
|
887 | 860 | |
|
888 | 861 | def rc_set_toggle(self,rc_field,value=None): |
|
889 | 862 | """Set or toggle a field in IPython's rc config. structure. |
|
890 | 863 | |
|
891 | 864 | If called with no arguments, it acts as a toggle. |
|
892 | 865 | |
|
893 | 866 | If called with a non-existent field, the resulting AttributeError |
|
894 | 867 | exception will propagate out.""" |
|
895 | 868 | |
|
896 | 869 | rc_val = getattr(self.rc,rc_field) |
|
897 | 870 | if value is None: |
|
898 | 871 | value = not rc_val |
|
899 | 872 | setattr(self.rc,rc_field,value) |
|
900 | 873 | |
|
901 | 874 | def user_setup(self,ipythondir,rc_suffix,mode='install'): |
|
902 | 875 | """Install the user configuration directory. |
|
903 | 876 | |
|
904 | 877 | Can be called when running for the first time or to upgrade the user's |
|
905 | 878 | .ipython/ directory with the mode parameter. Valid modes are 'install' |
|
906 | 879 | and 'upgrade'.""" |
|
907 | 880 | |
|
908 | 881 | def wait(): |
|
909 | 882 | try: |
|
910 | 883 | raw_input("Please press <RETURN> to start IPython.") |
|
911 | 884 | except EOFError: |
|
912 | 885 | print >> Term.cout |
|
913 | 886 | print '*'*70 |
|
914 | 887 | |
|
915 | 888 | cwd = os.getcwd() # remember where we started |
|
916 | 889 | glb = glob.glob |
|
917 | 890 | print '*'*70 |
|
918 | 891 | if mode == 'install': |
|
919 | 892 | print \ |
|
920 | 893 | """Welcome to IPython. I will try to create a personal configuration directory |
|
921 | 894 | where you can customize many aspects of IPython's functionality in:\n""" |
|
922 | 895 | else: |
|
923 | 896 | print 'I am going to upgrade your configuration in:' |
|
924 | 897 | |
|
925 | 898 | print ipythondir |
|
926 | 899 | |
|
927 | 900 | rcdirend = os.path.join('IPython','UserConfig') |
|
928 | 901 | cfg = lambda d: os.path.join(d,rcdirend) |
|
929 | 902 | try: |
|
930 | 903 | rcdir = filter(os.path.isdir,map(cfg,sys.path))[0] |
|
931 | 904 | except IOError: |
|
932 | 905 | warning = """ |
|
933 | 906 | Installation error. IPython's directory was not found. |
|
934 | 907 | |
|
935 | 908 | Check the following: |
|
936 | 909 | |
|
937 | 910 | The ipython/IPython directory should be in a directory belonging to your |
|
938 | 911 | PYTHONPATH environment variable (that is, it should be in a directory |
|
939 | 912 | belonging to sys.path). You can copy it explicitly there or just link to it. |
|
940 | 913 | |
|
941 | 914 | IPython will proceed with builtin defaults. |
|
942 | 915 | """ |
|
943 | 916 | warn(warning) |
|
944 | 917 | wait() |
|
945 | 918 | return |
|
946 | 919 | |
|
947 | 920 | if mode == 'install': |
|
948 | 921 | try: |
|
949 | 922 | shutil.copytree(rcdir,ipythondir) |
|
950 | 923 | os.chdir(ipythondir) |
|
951 | 924 | rc_files = glb("ipythonrc*") |
|
952 | 925 | for rc_file in rc_files: |
|
953 | 926 | os.rename(rc_file,rc_file+rc_suffix) |
|
954 | 927 | except: |
|
955 | 928 | warning = """ |
|
956 | 929 | |
|
957 | 930 | There was a problem with the installation: |
|
958 | 931 | %s |
|
959 | 932 | Try to correct it or contact the developers if you think it's a bug. |
|
960 | 933 | IPython will proceed with builtin defaults.""" % sys.exc_info()[1] |
|
961 | 934 | warn(warning) |
|
962 | 935 | wait() |
|
963 | 936 | return |
|
964 | 937 | |
|
965 | 938 | elif mode == 'upgrade': |
|
966 | 939 | try: |
|
967 | 940 | os.chdir(ipythondir) |
|
968 | 941 | except: |
|
969 | 942 | print """ |
|
970 | 943 | Can not upgrade: changing to directory %s failed. Details: |
|
971 | 944 | %s |
|
972 | 945 | """ % (ipythondir,sys.exc_info()[1]) |
|
973 | 946 | wait() |
|
974 | 947 | return |
|
975 | 948 | else: |
|
976 | 949 | sources = glb(os.path.join(rcdir,'[A-Za-z]*')) |
|
977 | 950 | for new_full_path in sources: |
|
978 | 951 | new_filename = os.path.basename(new_full_path) |
|
979 | 952 | if new_filename.startswith('ipythonrc'): |
|
980 | 953 | new_filename = new_filename + rc_suffix |
|
981 | 954 | # The config directory should only contain files, skip any |
|
982 | 955 | # directories which may be there (like CVS) |
|
983 | 956 | if os.path.isdir(new_full_path): |
|
984 | 957 | continue |
|
985 | 958 | if os.path.exists(new_filename): |
|
986 | 959 | old_file = new_filename+'.old' |
|
987 | 960 | if os.path.exists(old_file): |
|
988 | 961 | os.remove(old_file) |
|
989 | 962 | os.rename(new_filename,old_file) |
|
990 | 963 | shutil.copy(new_full_path,new_filename) |
|
991 | 964 | else: |
|
992 | 965 | raise ValueError,'unrecognized mode for install:',`mode` |
|
993 | 966 | |
|
994 | 967 | # Fix line-endings to those native to each platform in the config |
|
995 | 968 | # directory. |
|
996 | 969 | try: |
|
997 | 970 | os.chdir(ipythondir) |
|
998 | 971 | except: |
|
999 | 972 | print """ |
|
1000 | 973 | Problem: changing to directory %s failed. |
|
1001 | 974 | Details: |
|
1002 | 975 | %s |
|
1003 | 976 | |
|
1004 | 977 | Some configuration files may have incorrect line endings. This should not |
|
1005 | 978 | cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) |
|
1006 | 979 | wait() |
|
1007 | 980 | else: |
|
1008 | 981 | for fname in glb('ipythonrc*'): |
|
1009 | 982 | try: |
|
1010 | 983 | native_line_ends(fname,backup=0) |
|
1011 | 984 | except IOError: |
|
1012 | 985 | pass |
|
1013 | 986 | |
|
1014 | 987 | if mode == 'install': |
|
1015 | 988 | print """ |
|
1016 | 989 | Successful installation! |
|
1017 | 990 | |
|
1018 | 991 | Please read the sections 'Initial Configuration' and 'Quick Tips' in the |
|
1019 | 992 | IPython manual (there are both HTML and PDF versions supplied with the |
|
1020 | 993 | distribution) to make sure that your system environment is properly configured |
|
1021 | 994 | to take advantage of IPython's features.""" |
|
1022 | 995 | else: |
|
1023 | 996 | print """ |
|
1024 | 997 | Successful upgrade! |
|
1025 | 998 | |
|
1026 | 999 | All files in your directory: |
|
1027 | 1000 | %(ipythondir)s |
|
1028 | 1001 | which would have been overwritten by the upgrade were backed up with a .old |
|
1029 | 1002 | extension. If you had made particular customizations in those files you may |
|
1030 | 1003 | want to merge them back into the new files.""" % locals() |
|
1031 | 1004 | wait() |
|
1032 | 1005 | os.chdir(cwd) |
|
1033 | 1006 | # end user_setup() |
|
1034 | 1007 | |
|
1035 | 1008 | def atexit_operations(self): |
|
1036 | 1009 | """This will be executed at the time of exit. |
|
1037 | 1010 | |
|
1038 | 1011 | Saving of persistent data should be performed here. """ |
|
1039 | 1012 | |
|
1040 | 1013 | # input history |
|
1041 | 1014 | self.savehist() |
|
1042 | 1015 | |
|
1043 | 1016 | # Cleanup all tempfiles left around |
|
1044 | 1017 | for tfile in self.tempfiles: |
|
1045 | 1018 | try: |
|
1046 | 1019 | os.unlink(tfile) |
|
1047 | 1020 | except OSError: |
|
1048 | 1021 | pass |
|
1049 | 1022 | |
|
1050 | 1023 | # save the "persistent data" catch-all dictionary |
|
1051 | 1024 | try: |
|
1052 | 1025 | pickle.dump(self.persist, open(self.persist_fname,"w")) |
|
1053 | 1026 | except: |
|
1054 | 1027 | print "*** ERROR *** persistent data saving failed." |
|
1055 | 1028 | |
|
1056 | 1029 | def savehist(self): |
|
1057 | 1030 | """Save input history to a file (via readline library).""" |
|
1058 | 1031 | try: |
|
1059 | 1032 | self.readline.write_history_file(self.histfile) |
|
1060 | 1033 | except: |
|
1061 | 1034 | print 'Unable to save IPython command history to file: ' + \ |
|
1062 | 1035 | `self.histfile` |
|
1063 | 1036 | |
|
1064 | 1037 | def pre_readline(self): |
|
1065 | 1038 | """readline hook to be used at the start of each line. |
|
1066 | 1039 | |
|
1067 | 1040 | Currently it handles auto-indent only.""" |
|
1068 | 1041 | |
|
1069 | 1042 | self.readline.insert_text(self.indent_current) |
|
1070 | 1043 | |
|
1071 | 1044 | def init_readline(self): |
|
1072 | 1045 | """Command history completion/saving/reloading.""" |
|
1073 | 1046 | try: |
|
1074 | 1047 | import readline |
|
1075 | 1048 | except ImportError: |
|
1076 | 1049 | self.has_readline = 0 |
|
1077 | 1050 | self.readline = None |
|
1078 | 1051 | # no point in bugging windows users with this every time: |
|
1079 | 1052 | if os.name == 'posix': |
|
1080 | 1053 | warn('Readline services not available on this platform.') |
|
1081 | 1054 | else: |
|
1082 | 1055 | import atexit |
|
1083 | 1056 | from IPython.completer import IPCompleter |
|
1084 | 1057 | self.Completer = IPCompleter(self, |
|
1085 | 1058 | self.user_ns, |
|
1086 | 1059 | self.user_global_ns, |
|
1087 | 1060 | self.rc.readline_omit__names, |
|
1088 | 1061 | self.alias_table) |
|
1089 | 1062 | |
|
1090 | 1063 | # Platform-specific configuration |
|
1091 | 1064 | if os.name == 'nt': |
|
1092 | 1065 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1093 | 1066 | else: |
|
1094 | 1067 | self.readline_startup_hook = readline.set_startup_hook |
|
1095 | 1068 | |
|
1096 | 1069 | # Load user's initrc file (readline config) |
|
1097 | 1070 | inputrc_name = os.environ.get('INPUTRC') |
|
1098 | 1071 | if inputrc_name is None: |
|
1099 | 1072 | home_dir = get_home_dir() |
|
1100 | 1073 | if home_dir is not None: |
|
1101 | 1074 | inputrc_name = os.path.join(home_dir,'.inputrc') |
|
1102 | 1075 | if os.path.isfile(inputrc_name): |
|
1103 | 1076 | try: |
|
1104 | 1077 | readline.read_init_file(inputrc_name) |
|
1105 | 1078 | except: |
|
1106 | 1079 | warn('Problems reading readline initialization file <%s>' |
|
1107 | 1080 | % inputrc_name) |
|
1108 | 1081 | |
|
1109 | 1082 | self.has_readline = 1 |
|
1110 | 1083 | self.readline = readline |
|
1111 | 1084 | # save this in sys so embedded copies can restore it properly |
|
1112 | 1085 | sys.ipcompleter = self.Completer.complete |
|
1113 | 1086 | readline.set_completer(self.Completer.complete) |
|
1114 | 1087 | |
|
1115 | 1088 | # Configure readline according to user's prefs |
|
1116 | 1089 | for rlcommand in self.rc.readline_parse_and_bind: |
|
1117 | 1090 | readline.parse_and_bind(rlcommand) |
|
1118 | 1091 | |
|
1119 | 1092 | # remove some chars from the delimiters list |
|
1120 | 1093 | delims = readline.get_completer_delims() |
|
1121 | 1094 | delims = delims.translate(string._idmap, |
|
1122 | 1095 | self.rc.readline_remove_delims) |
|
1123 | 1096 | readline.set_completer_delims(delims) |
|
1124 | 1097 | # otherwise we end up with a monster history after a while: |
|
1125 | 1098 | readline.set_history_length(1000) |
|
1126 | 1099 | try: |
|
1127 | 1100 | #print '*** Reading readline history' # dbg |
|
1128 | 1101 | readline.read_history_file(self.histfile) |
|
1129 | 1102 | except IOError: |
|
1130 | 1103 | pass # It doesn't exist yet. |
|
1131 | 1104 | |
|
1132 | 1105 | atexit.register(self.atexit_operations) |
|
1133 | 1106 | del atexit |
|
1134 | 1107 | |
|
1135 | 1108 | # Configure auto-indent for all platforms |
|
1136 | 1109 | self.set_autoindent(self.rc.autoindent) |
|
1137 | 1110 | |
|
1138 | 1111 | def _should_recompile(self,e): |
|
1139 | 1112 | """Utility routine for edit_syntax_error""" |
|
1140 | 1113 | |
|
1141 | 1114 | if e.filename in ('<ipython console>','<input>','<string>', |
|
1142 | 1115 | '<console>'): |
|
1143 | 1116 | return False |
|
1144 | 1117 | try: |
|
1145 | 1118 | if not ask_yes_no('Return to editor to correct syntax error? ' |
|
1146 | 1119 | '[Y/n] ','y'): |
|
1147 | 1120 | return False |
|
1148 | 1121 | except EOFError: |
|
1149 | 1122 | return False |
|
1150 | 1123 | self.hooks.fix_error_editor(e.filename,e.lineno,e.offset,e.msg) |
|
1151 | 1124 | return True |
|
1152 | 1125 | |
|
1153 | 1126 | def edit_syntax_error(self): |
|
1154 | 1127 | """The bottom half of the syntax error handler called in the main loop. |
|
1155 | 1128 | |
|
1156 | 1129 | Loop until syntax error is fixed or user cancels. |
|
1157 | 1130 | """ |
|
1158 | 1131 | |
|
1159 | 1132 | while self.SyntaxTB.last_syntax_error: |
|
1160 | 1133 | # copy and clear last_syntax_error |
|
1161 | 1134 | err = self.SyntaxTB.clear_err_state() |
|
1162 | 1135 | if not self._should_recompile(err): |
|
1163 | 1136 | return |
|
1164 | 1137 | try: |
|
1165 | 1138 | # may set last_syntax_error again if a SyntaxError is raised |
|
1166 | 1139 | self.safe_execfile(err.filename,self.shell.user_ns) |
|
1167 | 1140 | except: |
|
1168 | 1141 | self.showtraceback() |
|
1169 | 1142 | else: |
|
1170 | 1143 | f = file(err.filename) |
|
1171 | 1144 | try: |
|
1172 | 1145 | sys.displayhook(f.read()) |
|
1173 | 1146 | finally: |
|
1174 | 1147 | f.close() |
|
1175 | 1148 | |
|
1176 | 1149 | def showsyntaxerror(self, filename=None): |
|
1177 | 1150 | """Display the syntax error that just occurred. |
|
1178 | 1151 | |
|
1179 | 1152 | This doesn't display a stack trace because there isn't one. |
|
1180 | 1153 | |
|
1181 | 1154 | If a filename is given, it is stuffed in the exception instead |
|
1182 | 1155 | of what was there before (because Python's parser always uses |
|
1183 | 1156 | "<string>" when reading from a string). |
|
1184 | 1157 | """ |
|
1185 | 1158 | type, value, sys.last_traceback = sys.exc_info() |
|
1186 | 1159 | sys.last_type = type |
|
1187 | 1160 | sys.last_value = value |
|
1188 | 1161 | if filename and type is SyntaxError: |
|
1189 | 1162 | # Work hard to stuff the correct filename in the exception |
|
1190 | 1163 | try: |
|
1191 | 1164 | msg, (dummy_filename, lineno, offset, line) = value |
|
1192 | 1165 | except: |
|
1193 | 1166 | # Not the format we expect; leave it alone |
|
1194 | 1167 | pass |
|
1195 | 1168 | else: |
|
1196 | 1169 | # Stuff in the right filename |
|
1197 | 1170 | try: |
|
1198 | 1171 | # Assume SyntaxError is a class exception |
|
1199 | 1172 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1200 | 1173 | except: |
|
1201 | 1174 | # If that failed, assume SyntaxError is a string |
|
1202 | 1175 | value = msg, (filename, lineno, offset, line) |
|
1203 | 1176 | self.SyntaxTB(type,value,[]) |
|
1204 | 1177 | |
|
1205 | 1178 | def debugger(self): |
|
1206 | 1179 | """Call the pdb debugger.""" |
|
1207 | 1180 | |
|
1208 | 1181 | if not self.rc.pdb: |
|
1209 | 1182 | return |
|
1210 | 1183 | pdb.pm() |
|
1211 | 1184 | |
|
1212 | 1185 | def showtraceback(self,exc_tuple = None,filename=None): |
|
1213 | 1186 | """Display the exception that just occurred.""" |
|
1214 | 1187 | |
|
1215 | 1188 | # Though this won't be called by syntax errors in the input line, |
|
1216 | 1189 | # there may be SyntaxError cases whith imported code. |
|
1217 | 1190 | if exc_tuple is None: |
|
1218 | 1191 | type, value, tb = sys.exc_info() |
|
1219 | 1192 | else: |
|
1220 | 1193 | type, value, tb = exc_tuple |
|
1221 | 1194 | if type is SyntaxError: |
|
1222 | 1195 | self.showsyntaxerror(filename) |
|
1223 | 1196 | else: |
|
1224 | 1197 | sys.last_type = type |
|
1225 | 1198 | sys.last_value = value |
|
1226 | 1199 | sys.last_traceback = tb |
|
1227 | 1200 | self.InteractiveTB() |
|
1228 | 1201 | if self.InteractiveTB.call_pdb and self.has_readline: |
|
1229 | 1202 | # pdb mucks up readline, fix it back |
|
1230 | 1203 | self.readline.set_completer(self.Completer.complete) |
|
1231 | 1204 | |
|
1232 | 1205 | def update_cache(self, line): |
|
1233 | 1206 | """puts line into cache""" |
|
1234 | 1207 | self.inputcache.insert(0, line) # This copies the cache every time ... :-( |
|
1235 | 1208 | if len(self.inputcache) >= self.CACHELENGTH: |
|
1236 | 1209 | self.inputcache.pop() # This doesn't :-) |
|
1237 | 1210 | |
|
1238 | 1211 | def mainloop(self,banner=None): |
|
1239 | 1212 | """Creates the local namespace and starts the mainloop. |
|
1240 | 1213 | |
|
1241 | 1214 | If an optional banner argument is given, it will override the |
|
1242 | 1215 | internally created default banner.""" |
|
1243 | 1216 | |
|
1244 | 1217 | if self.rc.c: # Emulate Python's -c option |
|
1245 | 1218 | self.exec_init_cmd() |
|
1246 | 1219 | if banner is None: |
|
1247 | 1220 | if self.rc.banner: |
|
1248 | 1221 | banner = self.BANNER+self.banner2 |
|
1249 | 1222 | else: |
|
1250 | 1223 | banner = '' |
|
1251 | 1224 | self.interact(banner) |
|
1252 | 1225 | |
|
1253 | 1226 | def exec_init_cmd(self): |
|
1254 | 1227 | """Execute a command given at the command line. |
|
1255 | 1228 | |
|
1256 | 1229 | This emulates Python's -c option.""" |
|
1257 | 1230 | |
|
1258 | 1231 | sys.argv = ['-c'] |
|
1259 | 1232 | self.push(self.rc.c) |
|
1260 | 1233 | |
|
1261 | 1234 | def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0): |
|
1262 | 1235 | """Embeds IPython into a running python program. |
|
1263 | 1236 | |
|
1264 | 1237 | Input: |
|
1265 | 1238 | |
|
1266 | 1239 | - header: An optional header message can be specified. |
|
1267 | 1240 | |
|
1268 | 1241 | - local_ns, global_ns: working namespaces. If given as None, the |
|
1269 | 1242 | IPython-initialized one is updated with __main__.__dict__, so that |
|
1270 | 1243 | program variables become visible but user-specific configuration |
|
1271 | 1244 | remains possible. |
|
1272 | 1245 | |
|
1273 | 1246 | - stack_depth: specifies how many levels in the stack to go to |
|
1274 | 1247 | looking for namespaces (when local_ns and global_ns are None). This |
|
1275 | 1248 | allows an intermediate caller to make sure that this function gets |
|
1276 | 1249 | the namespace from the intended level in the stack. By default (0) |
|
1277 | 1250 | it will get its locals and globals from the immediate caller. |
|
1278 | 1251 | |
|
1279 | 1252 | Warning: it's possible to use this in a program which is being run by |
|
1280 | 1253 | IPython itself (via %run), but some funny things will happen (a few |
|
1281 | 1254 | globals get overwritten). In the future this will be cleaned up, as |
|
1282 | 1255 | there is no fundamental reason why it can't work perfectly.""" |
|
1283 | 1256 | |
|
1284 | 1257 | # Get locals and globals from caller |
|
1285 | 1258 | if local_ns is None or global_ns is None: |
|
1286 | 1259 | call_frame = sys._getframe(stack_depth).f_back |
|
1287 | 1260 | |
|
1288 | 1261 | if local_ns is None: |
|
1289 | 1262 | local_ns = call_frame.f_locals |
|
1290 | 1263 | if global_ns is None: |
|
1291 | 1264 | global_ns = call_frame.f_globals |
|
1292 | 1265 | |
|
1293 | 1266 | # Update namespaces and fire up interpreter |
|
1294 | 1267 | self.user_ns = local_ns |
|
1295 | 1268 | self.user_global_ns = global_ns |
|
1296 | 1269 | |
|
1297 | 1270 | # Patch for global embedding to make sure that things don't overwrite |
|
1298 | 1271 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> |
|
1299 | 1272 | # FIXME. Test this a bit more carefully (the if.. is new) |
|
1300 | 1273 | if local_ns is None and global_ns is None: |
|
1301 | 1274 | self.user_global_ns.update(__main__.__dict__) |
|
1302 | 1275 | |
|
1303 | 1276 | # make sure the tab-completer has the correct frame information, so it |
|
1304 | 1277 | # actually completes using the frame's locals/globals |
|
1305 | 1278 | self.set_completer_frame(call_frame) |
|
1306 | 1279 | |
|
1307 | 1280 | self.interact(header) |
|
1308 | 1281 | |
|
1309 | 1282 | def interact(self, banner=None): |
|
1310 | 1283 | """Closely emulate the interactive Python console. |
|
1311 | 1284 | |
|
1312 | 1285 | The optional banner argument specify the banner to print |
|
1313 | 1286 | before the first interaction; by default it prints a banner |
|
1314 | 1287 | similar to the one printed by the real Python interpreter, |
|
1315 | 1288 | followed by the current class name in parentheses (so as not |
|
1316 | 1289 | to confuse this with the real interpreter -- since it's so |
|
1317 | 1290 | close!). |
|
1318 | 1291 | |
|
1319 | 1292 | """ |
|
1320 | 1293 | cprt = 'Type "copyright", "credits" or "license" for more information.' |
|
1321 | 1294 | if banner is None: |
|
1322 | 1295 | self.write("Python %s on %s\n%s\n(%s)\n" % |
|
1323 | 1296 | (sys.version, sys.platform, cprt, |
|
1324 | 1297 | self.__class__.__name__)) |
|
1325 | 1298 | else: |
|
1326 | 1299 | self.write(banner) |
|
1327 | 1300 | |
|
1328 | 1301 | more = 0 |
|
1329 | 1302 | |
|
1330 | 1303 | # Mark activity in the builtins |
|
1331 | 1304 | __builtin__.__dict__['__IPYTHON__active'] += 1 |
|
1332 | 1305 | |
|
1333 | 1306 | # compiled regexps for autoindent management |
|
1334 | 1307 | ini_spaces_re = re.compile(r'^(\s+)') |
|
1335 | 1308 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
1336 | 1309 | |
|
1337 | 1310 | # exit_now is set by a call to %Exit or %Quit |
|
1338 | 1311 | while not self.exit_now: |
|
1339 | 1312 | try: |
|
1340 | 1313 | if more: |
|
1341 | 1314 | prompt = self.outputcache.prompt2 |
|
1342 | 1315 | if self.autoindent: |
|
1343 | 1316 | self.readline_startup_hook(self.pre_readline) |
|
1344 | 1317 | else: |
|
1345 | 1318 | prompt = self.outputcache.prompt1 |
|
1346 | 1319 | try: |
|
1347 | 1320 | line = self.raw_input(prompt,more) |
|
1348 | 1321 | if self.autoindent: |
|
1349 | 1322 | self.readline_startup_hook(None) |
|
1350 | 1323 | except EOFError: |
|
1351 | 1324 | if self.autoindent: |
|
1352 | 1325 | self.readline_startup_hook(None) |
|
1353 | 1326 | self.write("\n") |
|
1354 | 1327 | self.exit() |
|
1355 | 1328 | else: |
|
1356 | 1329 | more = self.push(line) |
|
1357 | 1330 | # Auto-indent management |
|
1358 | 1331 | if self.autoindent: |
|
1359 | 1332 | if line: |
|
1360 | 1333 | ini_spaces = ini_spaces_re.match(line) |
|
1361 | 1334 | if ini_spaces: |
|
1362 | 1335 | nspaces = ini_spaces.end() |
|
1363 | 1336 | else: |
|
1364 | 1337 | nspaces = 0 |
|
1365 | 1338 | self.indent_current_nsp = nspaces |
|
1366 | 1339 | |
|
1367 | 1340 | if line[-1] == ':': |
|
1368 | 1341 | self.indent_current_nsp += 4 |
|
1369 | 1342 | elif dedent_re.match(line): |
|
1370 | 1343 | self.indent_current_nsp -= 4 |
|
1371 | 1344 | else: |
|
1372 | 1345 | self.indent_current_nsp = 0 |
|
1373 | 1346 | |
|
1374 | 1347 | # indent_current is the actual string to be inserted |
|
1375 | 1348 | # by the readline hooks for indentation |
|
1376 | 1349 | self.indent_current = ' '* self.indent_current_nsp |
|
1377 | 1350 | |
|
1378 | 1351 | if (self.SyntaxTB.last_syntax_error and |
|
1379 | 1352 | self.rc.autoedit_syntax): |
|
1380 | 1353 | self.edit_syntax_error() |
|
1381 | 1354 | |
|
1382 | 1355 | except KeyboardInterrupt: |
|
1383 | 1356 | self.write("\nKeyboardInterrupt\n") |
|
1384 | 1357 | self.resetbuffer() |
|
1385 | 1358 | more = 0 |
|
1386 | 1359 | # keep cache in sync with the prompt counter: |
|
1387 | 1360 | self.outputcache.prompt_count -= 1 |
|
1388 | 1361 | |
|
1389 | 1362 | if self.autoindent: |
|
1390 | 1363 | self.indent_current_nsp = 0 |
|
1391 | 1364 | self.indent_current = ' '* self.indent_current_nsp |
|
1392 | 1365 | |
|
1393 | 1366 | except bdb.BdbQuit: |
|
1394 | 1367 | warn("The Python debugger has exited with a BdbQuit exception.\n" |
|
1395 | 1368 | "Because of how pdb handles the stack, it is impossible\n" |
|
1396 | 1369 | "for IPython to properly format this particular exception.\n" |
|
1397 | 1370 | "IPython will resume normal operation.") |
|
1398 | 1371 | |
|
1399 | 1372 | # We are off again... |
|
1400 | 1373 | __builtin__.__dict__['__IPYTHON__active'] -= 1 |
|
1401 | 1374 | |
|
1402 | 1375 | def excepthook(self, type, value, tb): |
|
1403 | 1376 | """One more defense for GUI apps that call sys.excepthook. |
|
1404 | 1377 | |
|
1405 | 1378 | GUI frameworks like wxPython trap exceptions and call |
|
1406 | 1379 | sys.excepthook themselves. I guess this is a feature that |
|
1407 | 1380 | enables them to keep running after exceptions that would |
|
1408 | 1381 | otherwise kill their mainloop. This is a bother for IPython |
|
1409 | 1382 | which excepts to catch all of the program exceptions with a try: |
|
1410 | 1383 | except: statement. |
|
1411 | 1384 | |
|
1412 | 1385 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1413 | 1386 | any app directly invokes sys.excepthook, it will look to the user like |
|
1414 | 1387 | IPython crashed. In order to work around this, we can disable the |
|
1415 | 1388 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1416 | 1389 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1417 | 1390 | call sys.excepthook will generate a regular-looking exception from |
|
1418 | 1391 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1419 | 1392 | crashes. |
|
1420 | 1393 | |
|
1421 | 1394 | This hook should be used sparingly, only in places which are not likely |
|
1422 | 1395 | to be true IPython errors. |
|
1423 | 1396 | """ |
|
1424 | 1397 | |
|
1425 | 1398 | self.InteractiveTB(type, value, tb, tb_offset=0) |
|
1426 | 1399 | if self.InteractiveTB.call_pdb and self.has_readline: |
|
1427 | 1400 | self.readline.set_completer(self.Completer.complete) |
|
1428 | 1401 | |
|
1429 | 1402 | def call_alias(self,alias,rest=''): |
|
1430 | 1403 | """Call an alias given its name and the rest of the line. |
|
1431 | 1404 | |
|
1432 | 1405 | This function MUST be given a proper alias, because it doesn't make |
|
1433 | 1406 | any checks when looking up into the alias table. The caller is |
|
1434 | 1407 | responsible for invoking it only with a valid alias.""" |
|
1435 | 1408 | |
|
1436 | 1409 | #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg |
|
1437 | 1410 | nargs,cmd = self.alias_table[alias] |
|
1438 | 1411 | # Expand the %l special to be the user's input line |
|
1439 | 1412 | if cmd.find('%l') >= 0: |
|
1440 | 1413 | cmd = cmd.replace('%l',rest) |
|
1441 | 1414 | rest = '' |
|
1442 | 1415 | if nargs==0: |
|
1443 | 1416 | # Simple, argument-less aliases |
|
1444 | 1417 | cmd = '%s %s' % (cmd,rest) |
|
1445 | 1418 | else: |
|
1446 | 1419 | # Handle aliases with positional arguments |
|
1447 | 1420 | args = rest.split(None,nargs) |
|
1448 | 1421 | if len(args)< nargs: |
|
1449 | 1422 | error('Alias <%s> requires %s arguments, %s given.' % |
|
1450 | 1423 | (alias,nargs,len(args))) |
|
1451 | 1424 | return |
|
1452 | 1425 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) |
|
1453 | 1426 | # Now call the macro, evaluating in the user's namespace |
|
1454 | 1427 | try: |
|
1455 | 1428 | self.system(cmd) |
|
1456 | 1429 | except: |
|
1457 | 1430 | self.showtraceback() |
|
1458 | 1431 | |
|
1459 | 1432 | def runlines(self,lines): |
|
1460 | 1433 | """Run a string of one or more lines of source. |
|
1461 | 1434 | |
|
1462 | 1435 | This method is capable of running a string containing multiple source |
|
1463 | 1436 | lines, as if they had been entered at the IPython prompt. Since it |
|
1464 | 1437 | exposes IPython's processing machinery, the given strings can contain |
|
1465 | 1438 | magic calls (%magic), special shell access (!cmd), etc.""" |
|
1466 | 1439 | |
|
1467 | 1440 | # We must start with a clean buffer, in case this is run from an |
|
1468 | 1441 | # interactive IPython session (via a magic, for example). |
|
1469 | 1442 | self.resetbuffer() |
|
1470 | 1443 | lines = lines.split('\n') |
|
1471 | 1444 | more = 0 |
|
1472 | 1445 | for line in lines: |
|
1473 | 1446 | # skip blank lines so we don't mess up the prompt counter, but do |
|
1474 | 1447 | # NOT skip even a blank line if we are in a code block (more is |
|
1475 | 1448 | # true) |
|
1476 | 1449 | if line or more: |
|
1477 | 1450 | more = self.push((self.prefilter(line,more))) |
|
1478 | 1451 | # IPython's runsource returns None if there was an error |
|
1479 | 1452 | # compiling the code. This allows us to stop processing right |
|
1480 | 1453 | # away, so the user gets the error message at the right place. |
|
1481 | 1454 | if more is None: |
|
1482 | 1455 | break |
|
1483 | 1456 | # final newline in case the input didn't have it, so that the code |
|
1484 | 1457 | # actually does get executed |
|
1485 | 1458 | if more: |
|
1486 | 1459 | self.push('\n') |
|
1487 | 1460 | |
|
1488 | 1461 | def runsource(self, source, filename='<input>', symbol='single'): |
|
1489 | 1462 | """Compile and run some source in the interpreter. |
|
1490 | 1463 | |
|
1491 | 1464 | Arguments are as for compile_command(). |
|
1492 | 1465 | |
|
1493 | 1466 | One several things can happen: |
|
1494 | 1467 | |
|
1495 | 1468 | 1) The input is incorrect; compile_command() raised an |
|
1496 | 1469 | exception (SyntaxError or OverflowError). A syntax traceback |
|
1497 | 1470 | will be printed by calling the showsyntaxerror() method. |
|
1498 | 1471 | |
|
1499 | 1472 | 2) The input is incomplete, and more input is required; |
|
1500 | 1473 | compile_command() returned None. Nothing happens. |
|
1501 | 1474 | |
|
1502 | 1475 | 3) The input is complete; compile_command() returned a code |
|
1503 | 1476 | object. The code is executed by calling self.runcode() (which |
|
1504 | 1477 | also handles run-time exceptions, except for SystemExit). |
|
1505 | 1478 | |
|
1506 | 1479 | The return value is: |
|
1507 | 1480 | |
|
1508 | 1481 | - True in case 2 |
|
1509 | 1482 | |
|
1510 | 1483 | - False in the other cases, unless an exception is raised, where |
|
1511 | 1484 | None is returned instead. This can be used by external callers to |
|
1512 | 1485 | know whether to continue feeding input or not. |
|
1513 | 1486 | |
|
1514 | 1487 | The return value can be used to decide whether to use sys.ps1 or |
|
1515 | 1488 | sys.ps2 to prompt the next line.""" |
|
1516 | 1489 | |
|
1517 | 1490 | try: |
|
1518 | 1491 | code = self.compile(source,filename,symbol) |
|
1519 | 1492 | except (OverflowError, SyntaxError, ValueError): |
|
1520 | 1493 | # Case 1 |
|
1521 | 1494 | self.showsyntaxerror(filename) |
|
1522 | 1495 | return None |
|
1523 | 1496 | |
|
1524 | 1497 | if code is None: |
|
1525 | 1498 | # Case 2 |
|
1526 | 1499 | return True |
|
1527 | 1500 | |
|
1528 | 1501 | # Case 3 |
|
1529 | 1502 | # We store the code object so that threaded shells and |
|
1530 | 1503 | # custom exception handlers can access all this info if needed. |
|
1531 | 1504 | # The source corresponding to this can be obtained from the |
|
1532 | 1505 | # buffer attribute as '\n'.join(self.buffer). |
|
1533 | 1506 | self.code_to_run = code |
|
1534 | 1507 | # now actually execute the code object |
|
1535 | 1508 | if self.runcode(code) == 0: |
|
1536 | 1509 | return False |
|
1537 | 1510 | else: |
|
1538 | 1511 | return None |
|
1539 | 1512 | |
|
1540 | 1513 | def runcode(self,code_obj): |
|
1541 | 1514 | """Execute a code object. |
|
1542 | 1515 | |
|
1543 | 1516 | When an exception occurs, self.showtraceback() is called to display a |
|
1544 | 1517 | traceback. |
|
1545 | 1518 | |
|
1546 | 1519 | Return value: a flag indicating whether the code to be run completed |
|
1547 | 1520 | successfully: |
|
1548 | 1521 | |
|
1549 | 1522 | - 0: successful execution. |
|
1550 | 1523 | - 1: an error occurred. |
|
1551 | 1524 | """ |
|
1552 | 1525 | |
|
1553 | 1526 | # Set our own excepthook in case the user code tries to call it |
|
1554 | 1527 | # directly, so that the IPython crash handler doesn't get triggered |
|
1555 | 1528 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
1556 | 1529 | |
|
1557 | 1530 | # we save the original sys.excepthook in the instance, in case config |
|
1558 | 1531 | # code (such as magics) needs access to it. |
|
1559 | 1532 | self.sys_excepthook = old_excepthook |
|
1560 | 1533 | outflag = 1 # happens in more places, so it's easier as default |
|
1561 | 1534 | try: |
|
1562 | 1535 | try: |
|
1563 | 1536 | # Embedded instances require separate global/local namespaces |
|
1564 | 1537 | # so they can see both the surrounding (local) namespace and |
|
1565 | 1538 | # the module-level globals when called inside another function. |
|
1566 | 1539 | if self.embedded: |
|
1567 | 1540 | exec code_obj in self.user_global_ns, self.user_ns |
|
1568 | 1541 | # Normal (non-embedded) instances should only have a single |
|
1569 | 1542 | # namespace for user code execution, otherwise functions won't |
|
1570 | 1543 | # see interactive top-level globals. |
|
1571 | 1544 | else: |
|
1572 | 1545 | exec code_obj in self.user_ns |
|
1573 | 1546 | finally: |
|
1574 | 1547 | # Reset our crash handler in place |
|
1575 | 1548 | sys.excepthook = old_excepthook |
|
1576 | 1549 | except SystemExit: |
|
1577 | 1550 | self.resetbuffer() |
|
1578 | 1551 | self.showtraceback() |
|
1579 | 1552 | warn("Type exit or quit to exit IPython " |
|
1580 | 1553 | "(%Exit or %Quit do so unconditionally).",level=1) |
|
1581 | 1554 | except self.custom_exceptions: |
|
1582 | 1555 | etype,value,tb = sys.exc_info() |
|
1583 | 1556 | self.CustomTB(etype,value,tb) |
|
1584 | 1557 | except: |
|
1585 | 1558 | self.showtraceback() |
|
1586 | 1559 | else: |
|
1587 | 1560 | outflag = 0 |
|
1588 | 1561 | if softspace(sys.stdout, 0): |
|
1589 | 1562 | |
|
1590 | 1563 | # Flush out code object which has been run (and source) |
|
1591 | 1564 | self.code_to_run = None |
|
1592 | 1565 | return outflag |
|
1593 | 1566 | |
|
1594 | 1567 | def push(self, line): |
|
1595 | 1568 | """Push a line to the interpreter. |
|
1596 | 1569 | |
|
1597 | 1570 | The line should not have a trailing newline; it may have |
|
1598 | 1571 | internal newlines. The line is appended to a buffer and the |
|
1599 | 1572 | interpreter's runsource() method is called with the |
|
1600 | 1573 | concatenated contents of the buffer as source. If this |
|
1601 | 1574 | indicates that the command was executed or invalid, the buffer |
|
1602 | 1575 | is reset; otherwise, the command is incomplete, and the buffer |
|
1603 | 1576 | is left as it was after the line was appended. The return |
|
1604 | 1577 | value is 1 if more input is required, 0 if the line was dealt |
|
1605 | 1578 | with in some way (this is the same as runsource()). |
|
1606 | 1579 | |
|
1607 | 1580 | """ |
|
1608 | 1581 | self.buffer.append(line) |
|
1609 | 1582 | more = self.runsource('\n'.join(self.buffer), self.filename) |
|
1610 | 1583 | if not more: |
|
1611 | 1584 | self.resetbuffer() |
|
1612 | 1585 | return more |
|
1613 | 1586 | |
|
1614 | 1587 | def resetbuffer(self): |
|
1615 | 1588 | """Reset the input buffer.""" |
|
1616 | 1589 | self.buffer[:] = [] |
|
1617 | 1590 | |
|
1618 | 1591 | def raw_input(self,prompt='',continue_prompt=False): |
|
1619 | 1592 | """Write a prompt and read a line. |
|
1620 | 1593 | |
|
1621 | 1594 | The returned line does not include the trailing newline. |
|
1622 | 1595 | When the user enters the EOF key sequence, EOFError is raised. |
|
1623 | 1596 | |
|
1624 | 1597 | Optional inputs: |
|
1625 | 1598 | |
|
1626 | 1599 | - prompt(''): a string to be printed to prompt the user. |
|
1627 | 1600 | |
|
1628 | 1601 | - continue_prompt(False): whether this line is the first one or a |
|
1629 | 1602 | continuation in a sequence of inputs. |
|
1630 | 1603 | """ |
|
1631 | 1604 | |
|
1632 | 1605 | line = raw_input_original(prompt) |
|
1633 | 1606 | # Try to be reasonably smart about not re-indenting pasted input more |
|
1634 | 1607 | # than necessary. We do this by trimming out the auto-indent initial |
|
1635 | 1608 | # spaces, if the user's actual input started itself with whitespace. |
|
1636 | 1609 | if self.autoindent: |
|
1637 | 1610 | line2 = line[self.indent_current_nsp:] |
|
1638 | 1611 | if line2[0:1] in (' ','\t'): |
|
1639 | 1612 | line = line2 |
|
1640 | 1613 | return self.prefilter(line,continue_prompt) |
|
1641 | 1614 | |
|
1642 | 1615 | def split_user_input(self,line): |
|
1643 | 1616 | """Split user input into pre-char, function part and rest.""" |
|
1644 | 1617 | |
|
1645 | 1618 | lsplit = self.line_split.match(line) |
|
1646 | 1619 | if lsplit is None: # no regexp match returns None |
|
1647 | 1620 | try: |
|
1648 | 1621 | iFun,theRest = line.split(None,1) |
|
1649 | 1622 | except ValueError: |
|
1650 | 1623 | iFun,theRest = line,'' |
|
1651 | 1624 | pre = re.match('^(\s*)(.*)',line).groups()[0] |
|
1652 | 1625 | else: |
|
1653 | 1626 | pre,iFun,theRest = lsplit.groups() |
|
1654 | 1627 | |
|
1655 | 1628 | #print 'line:<%s>' % line # dbg |
|
1656 | 1629 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg |
|
1657 | 1630 | return pre,iFun.strip(),theRest |
|
1658 | 1631 | |
|
1659 | 1632 | def _prefilter(self, line, continue_prompt): |
|
1660 | 1633 | """Calls different preprocessors, depending on the form of line.""" |
|
1661 | 1634 | |
|
1662 | 1635 | # All handlers *must* return a value, even if it's blank (''). |
|
1663 | 1636 | |
|
1664 | 1637 | # Lines are NOT logged here. Handlers should process the line as |
|
1665 | 1638 | # needed, update the cache AND log it (so that the input cache array |
|
1666 | 1639 | # stays synced). |
|
1667 | 1640 | |
|
1668 | 1641 | # This function is _very_ delicate, and since it's also the one which |
|
1669 | 1642 | # determines IPython's response to user input, it must be as efficient |
|
1670 | 1643 | # as possible. For this reason it has _many_ returns in it, trying |
|
1671 | 1644 | # always to exit as quickly as it can figure out what it needs to do. |
|
1672 | 1645 | |
|
1673 | 1646 | # This function is the main responsible for maintaining IPython's |
|
1674 | 1647 | # behavior respectful of Python's semantics. So be _very_ careful if |
|
1675 | 1648 | # making changes to anything here. |
|
1676 | 1649 | |
|
1677 | 1650 | #..................................................................... |
|
1678 | 1651 | # Code begins |
|
1679 | 1652 | |
|
1680 | 1653 | #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg |
|
1681 | 1654 | |
|
1682 | 1655 | # save the line away in case we crash, so the post-mortem handler can |
|
1683 | 1656 | # record it |
|
1684 | 1657 | self._last_input_line = line |
|
1685 | 1658 | |
|
1686 | 1659 | #print '***line: <%s>' % line # dbg |
|
1687 | 1660 | |
|
1688 | 1661 | # the input history needs to track even empty lines |
|
1689 | 1662 | if not line.strip(): |
|
1690 | 1663 | if not continue_prompt: |
|
1691 | 1664 | self.outputcache.prompt_count -= 1 |
|
1692 | 1665 | return self.handle_normal(line,continue_prompt) |
|
1693 | 1666 | #return self.handle_normal('',continue_prompt) |
|
1694 | 1667 | |
|
1695 | 1668 | # print '***cont',continue_prompt # dbg |
|
1696 | 1669 | # special handlers are only allowed for single line statements |
|
1697 | 1670 | if continue_prompt and not self.rc.multi_line_specials: |
|
1698 | 1671 | return self.handle_normal(line,continue_prompt) |
|
1699 | 1672 | |
|
1700 | 1673 | # For the rest, we need the structure of the input |
|
1701 | 1674 | pre,iFun,theRest = self.split_user_input(line) |
|
1702 | 1675 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
1703 | 1676 | |
|
1704 | 1677 | # First check for explicit escapes in the last/first character |
|
1705 | 1678 | handler = None |
|
1706 | 1679 | if line[-1] == self.ESC_HELP: |
|
1707 | 1680 | handler = self.esc_handlers.get(line[-1]) # the ? can be at the end |
|
1708 | 1681 | if handler is None: |
|
1709 | 1682 | # look at the first character of iFun, NOT of line, so we skip |
|
1710 | 1683 | # leading whitespace in multiline input |
|
1711 | 1684 | handler = self.esc_handlers.get(iFun[0:1]) |
|
1712 | 1685 | if handler is not None: |
|
1713 | 1686 | return handler(line,continue_prompt,pre,iFun,theRest) |
|
1714 | 1687 | # Emacs ipython-mode tags certain input lines |
|
1715 | 1688 | if line.endswith('# PYTHON-MODE'): |
|
1716 | 1689 | return self.handle_emacs(line,continue_prompt) |
|
1717 | 1690 | |
|
1718 | 1691 | # Next, check if we can automatically execute this thing |
|
1719 | 1692 | |
|
1720 | 1693 | # Allow ! in multi-line statements if multi_line_specials is on: |
|
1721 | 1694 | if continue_prompt and self.rc.multi_line_specials and \ |
|
1722 | 1695 | iFun.startswith(self.ESC_SHELL): |
|
1723 | 1696 | return self.handle_shell_escape(line,continue_prompt, |
|
1724 | 1697 | pre=pre,iFun=iFun, |
|
1725 | 1698 | theRest=theRest) |
|
1726 | 1699 | |
|
1727 | 1700 | # Let's try to find if the input line is a magic fn |
|
1728 | 1701 | oinfo = None |
|
1729 | 1702 | if hasattr(self,'magic_'+iFun): |
|
1730 | 1703 | oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic |
|
1731 | 1704 | if oinfo['ismagic']: |
|
1732 | 1705 | # Be careful not to call magics when a variable assignment is |
|
1733 | 1706 | # being made (ls='hi', for example) |
|
1734 | 1707 | if self.rc.automagic and \ |
|
1735 | 1708 | (len(theRest)==0 or theRest[0] not in '!=()<>,') and \ |
|
1736 | 1709 | (self.rc.multi_line_specials or not continue_prompt): |
|
1737 | 1710 | return self.handle_magic(line,continue_prompt, |
|
1738 | 1711 | pre,iFun,theRest) |
|
1739 | 1712 | else: |
|
1740 | 1713 | return self.handle_normal(line,continue_prompt) |
|
1741 | 1714 | |
|
1742 | 1715 | # If the rest of the line begins with an (in)equality, assginment or |
|
1743 | 1716 | # function call, we should not call _ofind but simply execute it. |
|
1744 | 1717 | # This avoids spurious geattr() accesses on objects upon assignment. |
|
1745 | 1718 | # |
|
1746 | 1719 | # It also allows users to assign to either alias or magic names true |
|
1747 | 1720 | # python variables (the magic/alias systems always take second seat to |
|
1748 | 1721 | # true python code). |
|
1749 | 1722 | if theRest and theRest[0] in '!=()': |
|
1750 | 1723 | return self.handle_normal(line,continue_prompt) |
|
1751 | 1724 | |
|
1752 | 1725 | if oinfo is None: |
|
1753 | 1726 | oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic |
|
1754 | 1727 | |
|
1755 | 1728 | if not oinfo['found']: |
|
1756 | 1729 | return self.handle_normal(line,continue_prompt) |
|
1757 | 1730 | else: |
|
1758 | 1731 | #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg |
|
1759 | 1732 | if oinfo['isalias']: |
|
1760 | 1733 | return self.handle_alias(line,continue_prompt, |
|
1761 | 1734 | pre,iFun,theRest) |
|
1762 | 1735 | |
|
1763 | 1736 | if self.rc.autocall and \ |
|
1764 | 1737 | not self.re_exclude_auto.match(theRest) and \ |
|
1765 | 1738 | self.re_fun_name.match(iFun) and \ |
|
1766 | 1739 | callable(oinfo['obj']) : |
|
1767 | 1740 | #print 'going auto' # dbg |
|
1768 | 1741 | return self.handle_auto(line,continue_prompt,pre,iFun,theRest) |
|
1769 | 1742 | else: |
|
1770 | 1743 | #print 'was callable?', callable(oinfo['obj']) # dbg |
|
1771 | 1744 | return self.handle_normal(line,continue_prompt) |
|
1772 | 1745 | |
|
1773 | 1746 | # If we get here, we have a normal Python line. Log and return. |
|
1774 | 1747 | return self.handle_normal(line,continue_prompt) |
|
1775 | 1748 | |
|
1776 | 1749 | def _prefilter_dumb(self, line, continue_prompt): |
|
1777 | 1750 | """simple prefilter function, for debugging""" |
|
1778 | 1751 | return self.handle_normal(line,continue_prompt) |
|
1779 | 1752 | |
|
1780 | 1753 | # Set the default prefilter() function (this can be user-overridden) |
|
1781 | 1754 | prefilter = _prefilter |
|
1782 | 1755 | |
|
1783 | 1756 | def handle_normal(self,line,continue_prompt=None, |
|
1784 | 1757 | pre=None,iFun=None,theRest=None): |
|
1785 | 1758 | """Handle normal input lines. Use as a template for handlers.""" |
|
1786 | 1759 | |
|
1787 | 1760 | # With autoindent on, we need some way to exit the input loop, and I |
|
1788 | 1761 | # don't want to force the user to have to backspace all the way to |
|
1789 | 1762 | # clear the line. The rule will be in this case, that either two |
|
1790 | 1763 | # lines of pure whitespace in a row, or a line of pure whitespace but |
|
1791 | 1764 | # of a size different to the indent level, will exit the input loop. |
|
1792 | 1765 | if (continue_prompt and self.autoindent and isspace(line) and |
|
1793 | 1766 | (line != self.indent_current or isspace(self.buffer[-1]))): |
|
1794 | 1767 | line = '' |
|
1795 | 1768 | |
|
1796 | 1769 | self.log(line,continue_prompt) |
|
1797 | 1770 | self.update_cache(line) |
|
1798 | 1771 | return line |
|
1799 | 1772 | |
|
1800 | 1773 | def handle_alias(self,line,continue_prompt=None, |
|
1801 | 1774 | pre=None,iFun=None,theRest=None): |
|
1802 | 1775 | """Handle alias input lines. """ |
|
1803 | 1776 | |
|
1804 | 1777 | theRest = esc_quotes(theRest) |
|
1805 | line_out = "%s%s.call_alias('%s','%s')" % (pre,self.name,iFun,theRest) | |
|
1806 | self.log(line_out,continue_prompt) | |
|
1807 | self.update_cache(line_out) | |
|
1808 | return line_out | |
|
1778 | # log the ipalias form, which doesn't depend on the instance name | |
|
1779 | line_log = 'ipalias("%s %s")' % (iFun,theRest) | |
|
1780 | self.log(line_log,continue_prompt) | |
|
1781 | self.update_cache(line_log) | |
|
1782 | # this is what actually gets executed | |
|
1783 | return "%s%s.call_alias('%s','%s')" % (pre,self.name,iFun,theRest) | |
|
1809 | 1784 | |
|
1810 | 1785 | def handle_shell_escape(self, line, continue_prompt=None, |
|
1811 | 1786 | pre=None,iFun=None,theRest=None): |
|
1812 | 1787 | """Execute the line in a shell, empty return value""" |
|
1813 | 1788 | |
|
1814 | 1789 | #print 'line in :', `line` # dbg |
|
1815 | 1790 | # Example of a special handler. Others follow a similar pattern. |
|
1816 | 1791 | if continue_prompt: # multi-line statements |
|
1817 | 1792 | if iFun.startswith('!!'): |
|
1818 | 1793 | print 'SyntaxError: !! is not allowed in multiline statements' |
|
1819 | 1794 | return pre |
|
1820 | 1795 | else: |
|
1821 | 1796 | cmd = ("%s %s" % (iFun[1:],theRest)) #.replace('"','\\"') |
|
1822 | 1797 | #line_out = '%s%s.system("%s")' % (pre,self.name,cmd) |
|
1823 | 1798 | line_out = '%s%s.system(r"""%s"""[:-1])' % (pre,self.name,cmd + "_") |
|
1824 | 1799 | #line_out = ('%s%s.system(' % (pre,self.name)) + repr(cmd) + ')' |
|
1825 | 1800 | else: # single-line input |
|
1826 | 1801 | if line.startswith('!!'): |
|
1827 | 1802 | # rewrite iFun/theRest to properly hold the call to %sx and |
|
1828 | 1803 | # the actual command to be executed, so handle_magic can work |
|
1829 | 1804 | # correctly |
|
1830 | 1805 | theRest = '%s %s' % (iFun[2:],theRest) |
|
1831 | 1806 | iFun = 'sx' |
|
1832 | 1807 | return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]), |
|
1833 | 1808 | continue_prompt,pre,iFun,theRest) |
|
1834 | 1809 | else: |
|
1835 | 1810 | #cmd = esc_quotes(line[1:]) |
|
1836 | 1811 | cmd=line[1:] |
|
1837 | 1812 | #line_out = '%s.system("%s")' % (self.name,cmd) |
|
1838 | 1813 | line_out = '%s.system(r"""%s"""[:-1])' % (self.name,cmd +"_") |
|
1839 | 1814 | #line_out = ('%s.system(' % self.name) + repr(cmd)+ ')' |
|
1840 | 1815 | # update cache/log and return |
|
1841 | 1816 | self.log(line_out,continue_prompt) |
|
1842 | 1817 | self.update_cache(line_out) # readline cache gets normal line |
|
1843 | 1818 | #print 'line out r:', `line_out` # dbg |
|
1844 | 1819 | #print 'line out s:', line_out # dbg |
|
1845 | 1820 | return line_out |
|
1846 | 1821 | |
|
1847 | 1822 | def handle_magic(self, line, continue_prompt=None, |
|
1848 | 1823 | pre=None,iFun=None,theRest=None): |
|
1849 | 1824 | """Execute magic functions. |
|
1850 | 1825 | |
|
1851 | 1826 | Also log them with a prepended # so the log is clean Python.""" |
|
1852 | 1827 | |
|
1853 | 1828 | cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest))) |
|
1854 | 1829 | self.log(cmd,continue_prompt) |
|
1855 | 1830 | self.update_cache(line) |
|
1856 | 1831 | #print 'in handle_magic, cmd=<%s>' % cmd # dbg |
|
1857 | 1832 | return cmd |
|
1858 | 1833 | |
|
1859 | 1834 | def handle_auto(self, line, continue_prompt=None, |
|
1860 | 1835 | pre=None,iFun=None,theRest=None): |
|
1861 | 1836 | """Hande lines which can be auto-executed, quoting if requested.""" |
|
1862 | 1837 | |
|
1863 | 1838 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
1864 | 1839 | |
|
1865 | 1840 | # This should only be active for single-line input! |
|
1866 | 1841 | if continue_prompt: |
|
1867 | 1842 | return line |
|
1868 | 1843 | |
|
1869 | 1844 | if pre == self.ESC_QUOTE: |
|
1870 | 1845 | # Auto-quote splitting on whitespace |
|
1871 | 1846 | newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) ) |
|
1872 | 1847 | elif pre == self.ESC_QUOTE2: |
|
1873 | 1848 | # Auto-quote whole string |
|
1874 | 1849 | newcmd = '%s("%s")' % (iFun,theRest) |
|
1875 | 1850 | else: |
|
1876 | 1851 | # Auto-paren |
|
1877 | 1852 | if theRest[0:1] in ('=','['): |
|
1878 | 1853 | # Don't autocall in these cases. They can be either |
|
1879 | 1854 | # rebindings of an existing callable's name, or item access |
|
1880 | 1855 | # for an object which is BOTH callable and implements |
|
1881 | 1856 | # __getitem__. |
|
1882 | 1857 | return '%s %s' % (iFun,theRest) |
|
1883 | 1858 | if theRest.endswith(';'): |
|
1884 | 1859 | newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1]) |
|
1885 | 1860 | else: |
|
1886 | 1861 | newcmd = '%s(%s)' % (iFun.rstrip(),theRest) |
|
1887 | 1862 | |
|
1888 | 1863 | print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd |
|
1889 | 1864 | # log what is now valid Python, not the actual user input (without the |
|
1890 | 1865 | # final newline) |
|
1891 | 1866 | self.log(newcmd,continue_prompt) |
|
1892 | 1867 | return newcmd |
|
1893 | 1868 | |
|
1894 | 1869 | def handle_help(self, line, continue_prompt=None, |
|
1895 | 1870 | pre=None,iFun=None,theRest=None): |
|
1896 | 1871 | """Try to get some help for the object. |
|
1897 | 1872 | |
|
1898 | 1873 | obj? or ?obj -> basic information. |
|
1899 | 1874 | obj?? or ??obj -> more details. |
|
1900 | 1875 | """ |
|
1901 | 1876 | |
|
1902 | 1877 | # We need to make sure that we don't process lines which would be |
|
1903 | 1878 | # otherwise valid python, such as "x=1 # what?" |
|
1904 | 1879 | try: |
|
1905 | 1880 | codeop.compile_command(line) |
|
1906 | 1881 | except SyntaxError: |
|
1907 | 1882 | # We should only handle as help stuff which is NOT valid syntax |
|
1908 | 1883 | if line[0]==self.ESC_HELP: |
|
1909 | 1884 | line = line[1:] |
|
1910 | 1885 | elif line[-1]==self.ESC_HELP: |
|
1911 | 1886 | line = line[:-1] |
|
1912 | 1887 | self.log('#?'+line) |
|
1913 | 1888 | self.update_cache(line) |
|
1914 | 1889 | if line: |
|
1915 | 1890 | self.magic_pinfo(line) |
|
1916 | 1891 | else: |
|
1917 | 1892 | page(self.usage,screen_lines=self.rc.screen_length) |
|
1918 | 1893 | return '' # Empty string is needed here! |
|
1919 | 1894 | except: |
|
1920 | 1895 | # Pass any other exceptions through to the normal handler |
|
1921 | 1896 | return self.handle_normal(line,continue_prompt) |
|
1922 | 1897 | else: |
|
1923 | 1898 | # If the code compiles ok, we should handle it normally |
|
1924 | 1899 | return self.handle_normal(line,continue_prompt) |
|
1925 | 1900 | |
|
1926 | 1901 | def handle_emacs(self,line,continue_prompt=None, |
|
1927 | 1902 | pre=None,iFun=None,theRest=None): |
|
1928 | 1903 | """Handle input lines marked by python-mode.""" |
|
1929 | 1904 | |
|
1930 | 1905 | # Currently, nothing is done. Later more functionality can be added |
|
1931 | 1906 | # here if needed. |
|
1932 | 1907 | |
|
1933 | 1908 | # The input cache shouldn't be updated |
|
1934 | 1909 | |
|
1935 | 1910 | return line |
|
1936 | 1911 | |
|
1937 | 1912 | def write(self,data): |
|
1938 | 1913 | """Write a string to the default output""" |
|
1939 | 1914 | Term.cout.write(data) |
|
1940 | 1915 | |
|
1941 | 1916 | def write_err(self,data): |
|
1942 | 1917 | """Write a string to the default error output""" |
|
1943 | 1918 | Term.cerr.write(data) |
|
1944 | 1919 | |
|
1945 | 1920 | def exit(self): |
|
1946 | 1921 | """Handle interactive exit. |
|
1947 | 1922 | |
|
1948 | 1923 | This method sets the exit_now attribute.""" |
|
1949 | 1924 | |
|
1950 | 1925 | if self.rc.confirm_exit: |
|
1951 | 1926 | if ask_yes_no('Do you really want to exit ([y]/n)?','y'): |
|
1952 | 1927 | self.exit_now = True |
|
1953 | 1928 | else: |
|
1954 | 1929 | self.exit_now = True |
|
1955 | 1930 | return self.exit_now |
|
1956 | 1931 | |
|
1957 | 1932 | def safe_execfile(self,fname,*where,**kw): |
|
1958 | 1933 | fname = os.path.expanduser(fname) |
|
1959 | 1934 | |
|
1960 | 1935 | # find things also in current directory |
|
1961 | 1936 | dname = os.path.dirname(fname) |
|
1962 | 1937 | if not sys.path.count(dname): |
|
1963 | 1938 | sys.path.append(dname) |
|
1964 | 1939 | |
|
1965 | 1940 | try: |
|
1966 | 1941 | xfile = open(fname) |
|
1967 | 1942 | except: |
|
1968 | 1943 | print >> Term.cerr, \ |
|
1969 | 1944 | 'Could not open file <%s> for safe execution.' % fname |
|
1970 | 1945 | return None |
|
1971 | 1946 | |
|
1972 | 1947 | kw.setdefault('islog',0) |
|
1973 | 1948 | kw.setdefault('quiet',1) |
|
1974 | 1949 | kw.setdefault('exit_ignore',0) |
|
1975 | 1950 | first = xfile.readline() |
|
1976 | 1951 | loghead = str(self.loghead_tpl).split('\n',1)[0].strip() |
|
1977 | 1952 | xfile.close() |
|
1978 | 1953 | # line by line execution |
|
1979 | 1954 | if first.startswith(loghead) or kw['islog']: |
|
1980 | 1955 | print 'Loading log file <%s> one line at a time...' % fname |
|
1981 | 1956 | if kw['quiet']: |
|
1982 | 1957 | stdout_save = sys.stdout |
|
1983 | 1958 | sys.stdout = StringIO.StringIO() |
|
1984 | 1959 | try: |
|
1985 | 1960 | globs,locs = where[0:2] |
|
1986 | 1961 | except: |
|
1987 | 1962 | try: |
|
1988 | 1963 | globs = locs = where[0] |
|
1989 | 1964 | except: |
|
1990 | 1965 | globs = locs = globals() |
|
1991 | 1966 | badblocks = [] |
|
1992 | 1967 | |
|
1993 | 1968 | # we also need to identify indented blocks of code when replaying |
|
1994 | 1969 | # logs and put them together before passing them to an exec |
|
1995 | 1970 | # statement. This takes a bit of regexp and look-ahead work in the |
|
1996 | 1971 | # file. It's easiest if we swallow the whole thing in memory |
|
1997 | 1972 | # first, and manually walk through the lines list moving the |
|
1998 | 1973 | # counter ourselves. |
|
1999 | 1974 | indent_re = re.compile('\s+\S') |
|
2000 | 1975 | xfile = open(fname) |
|
2001 | 1976 | filelines = xfile.readlines() |
|
2002 | 1977 | xfile.close() |
|
2003 | 1978 | nlines = len(filelines) |
|
2004 | 1979 | lnum = 0 |
|
2005 | 1980 | while lnum < nlines: |
|
2006 | 1981 | line = filelines[lnum] |
|
2007 | 1982 | lnum += 1 |
|
2008 | 1983 | # don't re-insert logger status info into cache |
|
2009 | 1984 | if line.startswith('#log#'): |
|
2010 | 1985 | continue |
|
2011 | 1986 | elif line.startswith('#!'): |
|
2012 | 1987 | self.update_cache(line[1:]) |
|
2013 | 1988 | else: |
|
2014 | 1989 | # build a block of code (maybe a single line) for execution |
|
2015 | 1990 | block = line |
|
2016 | 1991 | try: |
|
2017 | 1992 | next = filelines[lnum] # lnum has already incremented |
|
2018 | 1993 | except: |
|
2019 | 1994 | next = None |
|
2020 | 1995 | while next and indent_re.match(next): |
|
2021 | 1996 | block += next |
|
2022 | 1997 | lnum += 1 |
|
2023 | 1998 | try: |
|
2024 | 1999 | next = filelines[lnum] |
|
2025 | 2000 | except: |
|
2026 | 2001 | next = None |
|
2027 | 2002 | # now execute the block of one or more lines |
|
2028 | 2003 | try: |
|
2029 | 2004 | exec block in globs,locs |
|
2030 | 2005 | self.update_cache(block.rstrip()) |
|
2031 | 2006 | except SystemExit: |
|
2032 | 2007 | pass |
|
2033 | 2008 | except: |
|
2034 | 2009 | badblocks.append(block.rstrip()) |
|
2035 | 2010 | if kw['quiet']: # restore stdout |
|
2036 | 2011 | sys.stdout.close() |
|
2037 | 2012 | sys.stdout = stdout_save |
|
2038 | 2013 | print 'Finished replaying log file <%s>' % fname |
|
2039 | 2014 | if badblocks: |
|
2040 | 2015 | print >> sys.stderr, ('\nThe following lines/blocks in file ' |
|
2041 | 2016 | '<%s> reported errors:' % fname) |
|
2042 | 2017 | |
|
2043 | 2018 | for badline in badblocks: |
|
2044 | 2019 | print >> sys.stderr, badline |
|
2045 | 2020 | else: # regular file execution |
|
2046 | 2021 | try: |
|
2047 | 2022 | execfile(fname,*where) |
|
2048 | 2023 | except SyntaxError: |
|
2049 | 2024 | etype,evalue = sys.exc_info()[:2] |
|
2050 | 2025 | self.SyntaxTB(etype,evalue,[]) |
|
2051 | 2026 | warn('Failure executing file: <%s>' % fname) |
|
2052 | 2027 | except SystemExit,status: |
|
2053 | 2028 | if not kw['exit_ignore']: |
|
2054 | 2029 | self.InteractiveTB() |
|
2055 | 2030 | warn('Failure executing file: <%s>' % fname) |
|
2056 | 2031 | except: |
|
2057 | 2032 | self.InteractiveTB() |
|
2058 | 2033 | warn('Failure executing file: <%s>' % fname) |
|
2059 | 2034 | |
|
2060 | 2035 | #************************* end of file <iplib.py> ***************************** |
@@ -1,701 +1,701 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | IPython -- An enhanced Interactive Python |
|
4 | 4 | |
|
5 | 5 | Requires Python 2.1 or better. |
|
6 | 6 | |
|
7 | 7 | This file contains the main make_IPython() starter function. |
|
8 | 8 | |
|
9 |
$Id: ipmaker.py 96 |
|
|
9 | $Id: ipmaker.py 967 2005-12-29 09:02:13Z fperez $""" | |
|
10 | 10 | |
|
11 | 11 | #***************************************************************************** |
|
12 | 12 | # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu> |
|
13 | 13 | # |
|
14 | 14 | # Distributed under the terms of the BSD License. The full license is in |
|
15 | 15 | # the file COPYING, distributed as part of this software. |
|
16 | 16 | #***************************************************************************** |
|
17 | 17 | |
|
18 | 18 | from IPython import Release |
|
19 | 19 | __author__ = '%s <%s>' % Release.authors['Fernando'] |
|
20 | 20 | __license__ = Release.license |
|
21 | 21 | __version__ = Release.version |
|
22 | 22 | |
|
23 | 23 | credits._Printer__data = """ |
|
24 | 24 | Python: %s |
|
25 | 25 | |
|
26 | 26 | IPython: Fernando Perez, Janko Hauser, Nathan Gray, and many users. |
|
27 | 27 | See http://ipython.scipy.org for more information.""" \ |
|
28 | 28 | % credits._Printer__data |
|
29 | 29 | |
|
30 | 30 | copyright._Printer__data += """ |
|
31 | 31 | |
|
32 | 32 | Copyright (c) 2001-2004 Fernando Perez, Janko Hauser, Nathan Gray. |
|
33 | 33 | All Rights Reserved.""" |
|
34 | 34 | |
|
35 | 35 | #**************************************************************************** |
|
36 | 36 | # Required modules |
|
37 | 37 | |
|
38 | 38 | # From the standard library |
|
39 | 39 | import __main__ |
|
40 | 40 | import __builtin__ |
|
41 | 41 | import os |
|
42 | 42 | import re |
|
43 | 43 | import sys |
|
44 | 44 | import types |
|
45 | 45 | from pprint import pprint,pformat |
|
46 | 46 | |
|
47 | 47 | # Our own |
|
48 | 48 | from IPython import DPyGetOpt |
|
49 | 49 | from IPython.Struct import Struct |
|
50 | 50 | from IPython.OutputTrap import OutputTrap |
|
51 | 51 | from IPython.ConfigLoader import ConfigLoader |
|
52 |
from IPython.iplib import InteractiveShell |
|
|
52 | from IPython.iplib import InteractiveShell | |
|
53 | 53 | from IPython.usage import cmd_line_usage,interactive_usage |
|
54 | 54 | from IPython.genutils import * |
|
55 | 55 | |
|
56 | 56 | #----------------------------------------------------------------------------- |
|
57 | 57 | def make_IPython(argv=None,user_ns=None,user_global_ns=None,debug=1, |
|
58 | 58 | rc_override=None,shell_class=InteractiveShell, |
|
59 | 59 | embedded=False,**kw): |
|
60 | 60 | """This is a dump of IPython into a single function. |
|
61 | 61 | |
|
62 | 62 | Later it will have to be broken up in a sensible manner. |
|
63 | 63 | |
|
64 | 64 | Arguments: |
|
65 | 65 | |
|
66 | 66 | - argv: a list similar to sys.argv[1:]. It should NOT contain the desired |
|
67 | 67 | script name, b/c DPyGetOpt strips the first argument only for the real |
|
68 | 68 | sys.argv. |
|
69 | 69 | |
|
70 | 70 | - user_ns: a dict to be used as the user's namespace.""" |
|
71 | 71 | |
|
72 | 72 | #---------------------------------------------------------------------- |
|
73 | 73 | # Defaults and initialization |
|
74 | 74 | |
|
75 | 75 | # For developer debugging, deactivates crash handler and uses pdb. |
|
76 | 76 | DEVDEBUG = False |
|
77 | 77 | |
|
78 | 78 | if argv is None: |
|
79 | 79 | argv = sys.argv |
|
80 | 80 | |
|
81 | 81 | # __IP is the main global that lives throughout and represents the whole |
|
82 | 82 | # application. If the user redefines it, all bets are off as to what |
|
83 | 83 | # happens. |
|
84 | 84 | |
|
85 | 85 | # __IP is the name of he global which the caller will have accessible as |
|
86 | 86 | # __IP.name. We set its name via the first parameter passed to |
|
87 | 87 | # InteractiveShell: |
|
88 | 88 | |
|
89 | 89 | IP = shell_class('__IP',user_ns=user_ns,user_global_ns=user_global_ns, |
|
90 | 90 | embedded=embedded,**kw) |
|
91 | 91 | |
|
92 | 92 | # Put 'help' in the user namespace |
|
93 | 93 | from site import _Helper |
|
94 | 94 | IP.user_ns['help'] = _Helper() |
|
95 | 95 | |
|
96 | 96 | |
|
97 | 97 | if DEVDEBUG: |
|
98 | 98 | # For developer debugging only (global flag) |
|
99 | 99 | from IPython import ultraTB |
|
100 | 100 | sys.excepthook = ultraTB.VerboseTB(call_pdb=1) |
|
101 | 101 | |
|
102 | 102 | IP.BANNER_PARTS = ['Python %s\n' |
|
103 | 103 | 'Type "copyright", "credits" or "license" ' |
|
104 | 104 | 'for more information.\n' |
|
105 | 105 | % (sys.version.split('\n')[0],), |
|
106 | 106 | "IPython %s -- An enhanced Interactive Python." |
|
107 | 107 | % (__version__,), |
|
108 | 108 | """? -> Introduction to IPython's features. |
|
109 | 109 | %magic -> Information about IPython's 'magic' % functions. |
|
110 | 110 | help -> Python's own help system. |
|
111 | 111 | object? -> Details about 'object'. ?object also works, ?? prints more. |
|
112 | 112 | """ ] |
|
113 | 113 | |
|
114 | 114 | IP.usage = interactive_usage |
|
115 | 115 | |
|
116 | 116 | # Platform-dependent suffix and directory names. We use _ipython instead |
|
117 | 117 | # of .ipython under win32 b/c there's software that breaks with .named |
|
118 | 118 | # directories on that platform. |
|
119 | 119 | if os.name == 'posix': |
|
120 | 120 | rc_suffix = '' |
|
121 | 121 | ipdir_def = '.ipython' |
|
122 | 122 | else: |
|
123 | 123 | rc_suffix = '.ini' |
|
124 | 124 | ipdir_def = '_ipython' |
|
125 | 125 | |
|
126 | 126 | # default directory for configuration |
|
127 | 127 | ipythondir = os.path.abspath(os.environ.get('IPYTHONDIR', |
|
128 | 128 | os.path.join(IP.home_dir,ipdir_def))) |
|
129 | 129 | |
|
130 | 130 | # we need the directory where IPython itself is installed |
|
131 | 131 | import IPython |
|
132 | 132 | IPython_dir = os.path.dirname(IPython.__file__) |
|
133 | 133 | del IPython |
|
134 | 134 | |
|
135 | 135 | #------------------------------------------------------------------------- |
|
136 | 136 | # Command line handling |
|
137 | 137 | |
|
138 | 138 | # Valid command line options (uses DPyGetOpt syntax, like Perl's |
|
139 | 139 | # GetOpt::Long) |
|
140 | 140 | |
|
141 | 141 | # Any key not listed here gets deleted even if in the file (like session |
|
142 | 142 | # or profile). That's deliberate, to maintain the rc namespace clean. |
|
143 | 143 | |
|
144 | 144 | # Each set of options appears twice: under _conv only the names are |
|
145 | 145 | # listed, indicating which type they must be converted to when reading the |
|
146 | 146 | # ipythonrc file. And under DPyGetOpt they are listed with the regular |
|
147 | 147 | # DPyGetOpt syntax (=s,=i,:f,etc). |
|
148 | 148 | |
|
149 | 149 | # Make sure there's a space before each end of line (they get auto-joined!) |
|
150 | 150 | cmdline_opts = ('autocall! autoindent! automagic! banner! cache_size|cs=i ' |
|
151 | 151 | 'c=s classic|cl color_info! colors=s confirm_exit! ' |
|
152 | 152 | 'debug! deep_reload! editor=s log|l messages! nosep pdb! ' |
|
153 | 153 | 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s ' |
|
154 | 154 | 'quick screen_length|sl=i prompts_pad_left=i ' |
|
155 | 155 | 'logfile|lf=s logplay|lp=s profile|p=s ' |
|
156 | 156 | 'readline! readline_merge_completions! ' |
|
157 | 157 | 'readline_omit__names! ' |
|
158 | 158 | 'rcfile=s separate_in|si=s separate_out|so=s ' |
|
159 | 159 | 'separate_out2|so2=s xmode=s wildcards_case_sensitive! ' |
|
160 | 160 | 'magic_docstrings system_verbose! ' |
|
161 | 161 | 'multi_line_specials! ' |
|
162 | 162 | 'autoedit_syntax!') |
|
163 | 163 | |
|
164 | 164 | # Options that can *only* appear at the cmd line (not in rcfiles). |
|
165 | 165 | |
|
166 | 166 | # The "ignore" option is a kludge so that Emacs buffers don't crash, since |
|
167 | 167 | # the 'C-c !' command in emacs automatically appends a -i option at the end. |
|
168 | 168 | cmdline_only = ('help ignore|i ipythondir=s Version upgrade ' |
|
169 | 169 | 'gthread! qthread! wthread! pylab! tk!') |
|
170 | 170 | |
|
171 | 171 | # Build the actual name list to be used by DPyGetOpt |
|
172 | 172 | opts_names = qw(cmdline_opts) + qw(cmdline_only) |
|
173 | 173 | |
|
174 | 174 | # Set sensible command line defaults. |
|
175 | 175 | # This should have everything from cmdline_opts and cmdline_only |
|
176 | 176 | opts_def = Struct(autocall = 1, |
|
177 | 177 | autoedit_syntax = 1, |
|
178 | 178 | autoindent=0, |
|
179 | 179 | automagic = 1, |
|
180 | 180 | banner = 1, |
|
181 | 181 | cache_size = 1000, |
|
182 | 182 | c = '', |
|
183 | 183 | classic = 0, |
|
184 | 184 | colors = 'NoColor', |
|
185 | 185 | color_info = 0, |
|
186 | 186 | confirm_exit = 1, |
|
187 | 187 | debug = 0, |
|
188 | 188 | deep_reload = 0, |
|
189 | 189 | editor = '0', |
|
190 | 190 | help = 0, |
|
191 | 191 | ignore = 0, |
|
192 | 192 | ipythondir = ipythondir, |
|
193 | 193 | log = 0, |
|
194 | 194 | logfile = '', |
|
195 | 195 | logplay = '', |
|
196 | 196 | multi_line_specials = 1, |
|
197 | 197 | messages = 1, |
|
198 | 198 | nosep = 0, |
|
199 | 199 | pdb = 0, |
|
200 | 200 | pprint = 0, |
|
201 | 201 | profile = '', |
|
202 | 202 | prompt_in1 = 'In [\\#]: ', |
|
203 | 203 | prompt_in2 = ' .\\D.: ', |
|
204 | 204 | prompt_out = 'Out[\\#]: ', |
|
205 | 205 | prompts_pad_left = 1, |
|
206 | 206 | quick = 0, |
|
207 | 207 | readline = 1, |
|
208 | 208 | readline_merge_completions = 1, |
|
209 | 209 | readline_omit__names = 0, |
|
210 | 210 | rcfile = 'ipythonrc' + rc_suffix, |
|
211 | 211 | screen_length = 0, |
|
212 | 212 | separate_in = '\n', |
|
213 | 213 | separate_out = '\n', |
|
214 | 214 | separate_out2 = '', |
|
215 | 215 | system_verbose = 0, |
|
216 | 216 | gthread = 0, |
|
217 | 217 | qthread = 0, |
|
218 | 218 | wthread = 0, |
|
219 | 219 | pylab = 0, |
|
220 | 220 | tk = 0, |
|
221 | 221 | upgrade = 0, |
|
222 | 222 | Version = 0, |
|
223 | 223 | xmode = 'Verbose', |
|
224 | 224 | wildcards_case_sensitive = 1, |
|
225 | 225 | magic_docstrings = 0, # undocumented, for doc generation |
|
226 | 226 | ) |
|
227 | 227 | |
|
228 | 228 | # Things that will *only* appear in rcfiles (not at the command line). |
|
229 | 229 | # Make sure there's a space before each end of line (they get auto-joined!) |
|
230 | 230 | rcfile_opts = { qwflat: 'include import_mod import_all execfile ', |
|
231 | 231 | qw_lol: 'import_some ', |
|
232 | 232 | # for things with embedded whitespace: |
|
233 | 233 | list_strings:'execute alias readline_parse_and_bind ', |
|
234 | 234 | # Regular strings need no conversion: |
|
235 | 235 | None:'readline_remove_delims ', |
|
236 | 236 | } |
|
237 | 237 | # Default values for these |
|
238 | 238 | rc_def = Struct(include = [], |
|
239 | 239 | import_mod = [], |
|
240 | 240 | import_all = [], |
|
241 | 241 | import_some = [[]], |
|
242 | 242 | execute = [], |
|
243 | 243 | execfile = [], |
|
244 | 244 | alias = [], |
|
245 | 245 | readline_parse_and_bind = [], |
|
246 | 246 | readline_remove_delims = '', |
|
247 | 247 | ) |
|
248 | 248 | |
|
249 | 249 | # Build the type conversion dictionary from the above tables: |
|
250 | 250 | typeconv = rcfile_opts.copy() |
|
251 | 251 | typeconv.update(optstr2types(cmdline_opts)) |
|
252 | 252 | |
|
253 | 253 | # FIXME: the None key appears in both, put that back together by hand. Ugly! |
|
254 | 254 | typeconv[None] += ' ' + rcfile_opts[None] |
|
255 | 255 | |
|
256 | 256 | # Remove quotes at ends of all strings (used to protect spaces) |
|
257 | 257 | typeconv[unquote_ends] = typeconv[None] |
|
258 | 258 | del typeconv[None] |
|
259 | 259 | |
|
260 | 260 | # Build the list we'll use to make all config decisions with defaults: |
|
261 | 261 | opts_all = opts_def.copy() |
|
262 | 262 | opts_all.update(rc_def) |
|
263 | 263 | |
|
264 | 264 | # Build conflict resolver for recursive loading of config files: |
|
265 | 265 | # - preserve means the outermost file maintains the value, it is not |
|
266 | 266 | # overwritten if an included file has the same key. |
|
267 | 267 | # - add_flip applies + to the two values, so it better make sense to add |
|
268 | 268 | # those types of keys. But it flips them first so that things loaded |
|
269 | 269 | # deeper in the inclusion chain have lower precedence. |
|
270 | 270 | conflict = {'preserve': ' '.join([ typeconv[int], |
|
271 | 271 | typeconv[unquote_ends] ]), |
|
272 | 272 | 'add_flip': ' '.join([ typeconv[qwflat], |
|
273 | 273 | typeconv[qw_lol], |
|
274 | 274 | typeconv[list_strings] ]) |
|
275 | 275 | } |
|
276 | 276 | |
|
277 | 277 | # Now actually process the command line |
|
278 | 278 | getopt = DPyGetOpt.DPyGetOpt() |
|
279 | 279 | getopt.setIgnoreCase(0) |
|
280 | 280 | |
|
281 | 281 | getopt.parseConfiguration(opts_names) |
|
282 | 282 | |
|
283 | 283 | try: |
|
284 | 284 | getopt.processArguments(argv) |
|
285 | 285 | except: |
|
286 | 286 | print cmd_line_usage |
|
287 | 287 | warn('\nError in Arguments: ' + `sys.exc_value`) |
|
288 | 288 | sys.exit(1) |
|
289 | 289 | |
|
290 | 290 | # convert the options dict to a struct for much lighter syntax later |
|
291 | 291 | opts = Struct(getopt.optionValues) |
|
292 | 292 | args = getopt.freeValues |
|
293 | 293 | |
|
294 | 294 | # this is the struct (which has default values at this point) with which |
|
295 | 295 | # we make all decisions: |
|
296 | 296 | opts_all.update(opts) |
|
297 | 297 | |
|
298 | 298 | # Options that force an immediate exit |
|
299 | 299 | if opts_all.help: |
|
300 | 300 | page(cmd_line_usage) |
|
301 | 301 | sys.exit() |
|
302 | 302 | |
|
303 | 303 | if opts_all.Version: |
|
304 | 304 | print __version__ |
|
305 | 305 | sys.exit() |
|
306 | 306 | |
|
307 | 307 | if opts_all.magic_docstrings: |
|
308 | 308 | IP.magic_magic('-latex') |
|
309 | 309 | sys.exit() |
|
310 | 310 | |
|
311 | 311 | # Create user config directory if it doesn't exist. This must be done |
|
312 | 312 | # *after* getting the cmd line options. |
|
313 | 313 | if not os.path.isdir(opts_all.ipythondir): |
|
314 | 314 | IP.user_setup(opts_all.ipythondir,rc_suffix,'install') |
|
315 | 315 | |
|
316 | 316 | # upgrade user config files while preserving a copy of the originals |
|
317 | 317 | if opts_all.upgrade: |
|
318 | 318 | IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade') |
|
319 | 319 | |
|
320 | 320 | # check mutually exclusive options in the *original* command line |
|
321 | 321 | mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'), |
|
322 | 322 | qw('classic profile'),qw('classic rcfile')]) |
|
323 | 323 | |
|
324 | 324 | #--------------------------------------------------------------------------- |
|
325 | 325 | # Log replay |
|
326 | 326 | |
|
327 | 327 | # if -logplay, we need to 'become' the other session. That basically means |
|
328 | 328 | # replacing the current command line environment with that of the old |
|
329 | 329 | # session and moving on. |
|
330 | 330 | |
|
331 | 331 | # this is needed so that later we know we're in session reload mode, as |
|
332 | 332 | # opts_all will get overwritten: |
|
333 | 333 | load_logplay = 0 |
|
334 | 334 | |
|
335 | 335 | if opts_all.logplay: |
|
336 | 336 | load_logplay = opts_all.logplay |
|
337 | 337 | opts_debug_save = opts_all.debug |
|
338 | 338 | try: |
|
339 | 339 | logplay = open(opts_all.logplay) |
|
340 | 340 | except IOError: |
|
341 | 341 | if opts_all.debug: IP.InteractiveTB() |
|
342 | 342 | warn('Could not open logplay file '+`opts_all.logplay`) |
|
343 | 343 | # restore state as if nothing had happened and move on, but make |
|
344 | 344 | # sure that later we don't try to actually load the session file |
|
345 | 345 | logplay = None |
|
346 | 346 | load_logplay = 0 |
|
347 | 347 | del opts_all.logplay |
|
348 | 348 | else: |
|
349 | 349 | try: |
|
350 | 350 | logplay.readline() |
|
351 | 351 | logplay.readline(); |
|
352 | 352 | # this reloads that session's command line |
|
353 | 353 | cmd = logplay.readline()[6:] |
|
354 | 354 | exec cmd |
|
355 | 355 | # restore the true debug flag given so that the process of |
|
356 | 356 | # session loading itself can be monitored. |
|
357 | 357 | opts.debug = opts_debug_save |
|
358 | 358 | # save the logplay flag so later we don't overwrite the log |
|
359 | 359 | opts.logplay = load_logplay |
|
360 | 360 | # now we must update our own structure with defaults |
|
361 | 361 | opts_all.update(opts) |
|
362 | 362 | # now load args |
|
363 | 363 | cmd = logplay.readline()[6:] |
|
364 | 364 | exec cmd |
|
365 | 365 | logplay.close() |
|
366 | 366 | except: |
|
367 | 367 | logplay.close() |
|
368 | 368 | if opts_all.debug: IP.InteractiveTB() |
|
369 | 369 | warn("Logplay file lacking full configuration information.\n" |
|
370 | 370 | "I'll try to read it, but some things may not work.") |
|
371 | 371 | |
|
372 | 372 | #------------------------------------------------------------------------- |
|
373 | 373 | # set up output traps: catch all output from files, being run, modules |
|
374 | 374 | # loaded, etc. Then give it to the user in a clean form at the end. |
|
375 | 375 | |
|
376 | 376 | msg_out = 'Output messages. ' |
|
377 | 377 | msg_err = 'Error messages. ' |
|
378 | 378 | msg_sep = '\n' |
|
379 | 379 | msg = Struct(config = OutputTrap('Configuration Loader',msg_out, |
|
380 | 380 | msg_err,msg_sep,debug, |
|
381 | 381 | quiet_out=1), |
|
382 | 382 | user_exec = OutputTrap('User File Execution',msg_out, |
|
383 | 383 | msg_err,msg_sep,debug), |
|
384 | 384 | logplay = OutputTrap('Log Loader',msg_out, |
|
385 | 385 | msg_err,msg_sep,debug), |
|
386 | 386 | summary = '' |
|
387 | 387 | ) |
|
388 | 388 | |
|
389 | 389 | #------------------------------------------------------------------------- |
|
390 | 390 | # Process user ipythonrc-type configuration files |
|
391 | 391 | |
|
392 | 392 | # turn on output trapping and log to msg.config |
|
393 | 393 | # remember that with debug on, trapping is actually disabled |
|
394 | 394 | msg.config.trap_all() |
|
395 | 395 | |
|
396 | 396 | # look for rcfile in current or default directory |
|
397 | 397 | try: |
|
398 | 398 | opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir) |
|
399 | 399 | except IOError: |
|
400 | 400 | if opts_all.debug: IP.InteractiveTB() |
|
401 | 401 | warn('Configuration file %s not found. Ignoring request.' |
|
402 | 402 | % (opts_all.rcfile) ) |
|
403 | 403 | |
|
404 | 404 | # 'profiles' are a shorthand notation for config filenames |
|
405 | 405 | if opts_all.profile: |
|
406 | 406 | try: |
|
407 | 407 | opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile |
|
408 | 408 | + rc_suffix, |
|
409 | 409 | opts_all.ipythondir) |
|
410 | 410 | except IOError: |
|
411 | 411 | if opts_all.debug: IP.InteractiveTB() |
|
412 | 412 | opts.profile = '' # remove profile from options if invalid |
|
413 | 413 | warn('Profile configuration file %s not found. Ignoring request.' |
|
414 | 414 | % (opts_all.profile) ) |
|
415 | 415 | |
|
416 | 416 | # load the config file |
|
417 | 417 | rcfiledata = None |
|
418 | 418 | if opts_all.quick: |
|
419 | 419 | print 'Launching IPython in quick mode. No config file read.' |
|
420 | 420 | elif opts_all.classic: |
|
421 | 421 | print 'Launching IPython in classic mode. No config file read.' |
|
422 | 422 | elif opts_all.rcfile: |
|
423 | 423 | try: |
|
424 | 424 | cfg_loader = ConfigLoader(conflict) |
|
425 | 425 | rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv, |
|
426 | 426 | 'include',opts_all.ipythondir, |
|
427 | 427 | purge = 1, |
|
428 | 428 | unique = conflict['preserve']) |
|
429 | 429 | except: |
|
430 | 430 | IP.InteractiveTB() |
|
431 | 431 | warn('Problems loading configuration file '+ |
|
432 | 432 | `opts_all.rcfile`+ |
|
433 | 433 | '\nStarting with default -bare bones- configuration.') |
|
434 | 434 | else: |
|
435 | 435 | warn('No valid configuration file found in either currrent directory\n'+ |
|
436 | 436 | 'or in the IPython config. directory: '+`opts_all.ipythondir`+ |
|
437 | 437 | '\nProceeding with internal defaults.') |
|
438 | 438 | |
|
439 | 439 | #------------------------------------------------------------------------ |
|
440 | 440 | # Set exception handlers in mode requested by user. |
|
441 | 441 | otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode |
|
442 | 442 | IP.magic_xmode(opts_all.xmode) |
|
443 | 443 | otrap.release_out() |
|
444 | 444 | |
|
445 | 445 | #------------------------------------------------------------------------ |
|
446 | 446 | # Execute user config |
|
447 | 447 | |
|
448 | 448 | # Create a valid config structure with the right precedence order: |
|
449 | 449 | # defaults < rcfile < command line. This needs to be in the instance, so |
|
450 | 450 | # that method calls below that rely on it find it. |
|
451 | 451 | IP.rc = rc_def.copy() |
|
452 | 452 | |
|
453 | 453 | # Work with a local alias inside this routine to avoid unnecessary |
|
454 | 454 | # attribute lookups. |
|
455 | 455 | IP_rc = IP.rc |
|
456 | 456 | |
|
457 | 457 | IP_rc.update(opts_def) |
|
458 | 458 | if rcfiledata: |
|
459 | 459 | # now we can update |
|
460 | 460 | IP_rc.update(rcfiledata) |
|
461 | 461 | IP_rc.update(opts) |
|
462 | 462 | IP_rc.update(rc_override) |
|
463 | 463 | |
|
464 | 464 | # Store the original cmd line for reference: |
|
465 | 465 | IP_rc.opts = opts |
|
466 | 466 | IP_rc.args = args |
|
467 | 467 | |
|
468 | 468 | # create a *runtime* Struct like rc for holding parameters which may be |
|
469 | 469 | # created and/or modified by runtime user extensions. |
|
470 | 470 | IP.runtime_rc = Struct() |
|
471 | 471 | |
|
472 | 472 | # from this point on, all config should be handled through IP_rc, |
|
473 | 473 | # opts* shouldn't be used anymore. |
|
474 | 474 | |
|
475 | 475 | # add personal .ipython dir to sys.path so that users can put things in |
|
476 | 476 | # there for customization |
|
477 | 477 | sys.path.append(IP_rc.ipythondir) |
|
478 | 478 | sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran |
|
479 | 479 | |
|
480 | 480 | # update IP_rc with some special things that need manual |
|
481 | 481 | # tweaks. Basically options which affect other options. I guess this |
|
482 | 482 | # should just be written so that options are fully orthogonal and we |
|
483 | 483 | # wouldn't worry about this stuff! |
|
484 | 484 | |
|
485 | 485 | if IP_rc.classic: |
|
486 | 486 | IP_rc.quick = 1 |
|
487 | 487 | IP_rc.cache_size = 0 |
|
488 | 488 | IP_rc.pprint = 0 |
|
489 | 489 | IP_rc.prompt_in1 = '>>> ' |
|
490 | 490 | IP_rc.prompt_in2 = '... ' |
|
491 | 491 | IP_rc.prompt_out = '' |
|
492 | 492 | IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0' |
|
493 | 493 | IP_rc.colors = 'NoColor' |
|
494 | 494 | IP_rc.xmode = 'Plain' |
|
495 | 495 | |
|
496 | 496 | # configure readline |
|
497 | 497 | # Define the history file for saving commands in between sessions |
|
498 | 498 | if IP_rc.profile: |
|
499 | 499 | histfname = 'history-%s' % IP_rc.profile |
|
500 | 500 | else: |
|
501 | 501 | histfname = 'history' |
|
502 | 502 | IP.histfile = os.path.join(opts_all.ipythondir,histfname) |
|
503 | 503 | |
|
504 | 504 | # update exception handlers with rc file status |
|
505 | 505 | otrap.trap_out() # I don't want these messages ever. |
|
506 | 506 | IP.magic_xmode(IP_rc.xmode) |
|
507 | 507 | otrap.release_out() |
|
508 | 508 | |
|
509 | 509 | # activate logging if requested and not reloading a log |
|
510 | 510 | if IP_rc.logplay: |
|
511 | 511 | IP.magic_logstart(IP_rc.logplay + ' append') |
|
512 | 512 | elif IP_rc.logfile: |
|
513 | 513 | IP.magic_logstart(IP_rc.logfile) |
|
514 | 514 | elif IP_rc.log: |
|
515 | 515 | IP.magic_logstart() |
|
516 | 516 | |
|
517 | 517 | # find user editor so that it we don't have to look it up constantly |
|
518 | 518 | if IP_rc.editor.strip()=='0': |
|
519 | 519 | try: |
|
520 | 520 | ed = os.environ['EDITOR'] |
|
521 | 521 | except KeyError: |
|
522 | 522 | if os.name == 'posix': |
|
523 | 523 | ed = 'vi' # the only one guaranteed to be there! |
|
524 | 524 | else: |
|
525 | 525 | ed = 'notepad' # same in Windows! |
|
526 | 526 | IP_rc.editor = ed |
|
527 | 527 | |
|
528 | 528 | # Keep track of whether this is an embedded instance or not (useful for |
|
529 | 529 | # post-mortems). |
|
530 | 530 | IP_rc.embedded = IP.embedded |
|
531 | 531 | |
|
532 | 532 | # Recursive reload |
|
533 | 533 | try: |
|
534 | 534 | from IPython import deep_reload |
|
535 | 535 | if IP_rc.deep_reload: |
|
536 | 536 | __builtin__.reload = deep_reload.reload |
|
537 | 537 | else: |
|
538 | 538 | __builtin__.dreload = deep_reload.reload |
|
539 | 539 | del deep_reload |
|
540 | 540 | except ImportError: |
|
541 | 541 | pass |
|
542 | 542 | |
|
543 | 543 | # Save the current state of our namespace so that the interactive shell |
|
544 | 544 | # can later know which variables have been created by us from config files |
|
545 | 545 | # and loading. This way, loading a file (in any way) is treated just like |
|
546 | 546 | # defining things on the command line, and %who works as expected. |
|
547 | 547 | |
|
548 | 548 | # DON'T do anything that affects the namespace beyond this point! |
|
549 | 549 | IP.internal_ns.update(__main__.__dict__) |
|
550 | 550 | |
|
551 | 551 | #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who |
|
552 | 552 | |
|
553 | 553 | # Now run through the different sections of the users's config |
|
554 | 554 | if IP_rc.debug: |
|
555 | 555 | print 'Trying to execute the following configuration structure:' |
|
556 | 556 | print '(Things listed first are deeper in the inclusion tree and get' |
|
557 | 557 | print 'loaded first).\n' |
|
558 | 558 | pprint(IP_rc.__dict__) |
|
559 | 559 | |
|
560 | 560 | for mod in IP_rc.import_mod: |
|
561 | 561 | try: |
|
562 | 562 | exec 'import '+mod in IP.user_ns |
|
563 | 563 | except : |
|
564 | 564 | IP.InteractiveTB() |
|
565 | 565 | import_fail_info(mod) |
|
566 | 566 | |
|
567 | 567 | for mod_fn in IP_rc.import_some: |
|
568 | 568 | if mod_fn == []: break |
|
569 | 569 | mod,fn = mod_fn[0],','.join(mod_fn[1:]) |
|
570 | 570 | try: |
|
571 | 571 | exec 'from '+mod+' import '+fn in IP.user_ns |
|
572 | 572 | except : |
|
573 | 573 | IP.InteractiveTB() |
|
574 | 574 | import_fail_info(mod,fn) |
|
575 | 575 | |
|
576 | 576 | for mod in IP_rc.import_all: |
|
577 | 577 | try: |
|
578 | 578 | exec 'from '+mod+' import *' in IP.user_ns |
|
579 | 579 | except : |
|
580 | 580 | IP.InteractiveTB() |
|
581 | 581 | import_fail_info(mod) |
|
582 | 582 | |
|
583 | 583 | for code in IP_rc.execute: |
|
584 | 584 | try: |
|
585 | 585 | exec code in IP.user_ns |
|
586 | 586 | except: |
|
587 | 587 | IP.InteractiveTB() |
|
588 | 588 | warn('Failure executing code: ' + `code`) |
|
589 | 589 | |
|
590 | 590 | # Execute the files the user wants in ipythonrc |
|
591 | 591 | for file in IP_rc.execfile: |
|
592 | 592 | try: |
|
593 | 593 | file = filefind(file,sys.path+[IPython_dir]) |
|
594 | 594 | except IOError: |
|
595 | 595 | warn(itpl('File $file not found. Skipping it.')) |
|
596 | 596 | else: |
|
597 | 597 | IP.safe_execfile(os.path.expanduser(file),IP.user_ns) |
|
598 | 598 | |
|
599 | 599 | # release stdout and stderr and save config log into a global summary |
|
600 | 600 | msg.config.release_all() |
|
601 | 601 | if IP_rc.messages: |
|
602 | 602 | msg.summary += msg.config.summary_all() |
|
603 | 603 | |
|
604 | 604 | #------------------------------------------------------------------------ |
|
605 | 605 | # Setup interactive session |
|
606 | 606 | |
|
607 | 607 | # Now we should be fully configured. We can then execute files or load |
|
608 | 608 | # things only needed for interactive use. Then we'll open the shell. |
|
609 | 609 | |
|
610 | 610 | # Take a snapshot of the user namespace before opening the shell. That way |
|
611 | 611 | # we'll be able to identify which things were interactively defined and |
|
612 | 612 | # which were defined through config files. |
|
613 | 613 | IP.user_config_ns = IP.user_ns.copy() |
|
614 | 614 | |
|
615 | 615 | # Force reading a file as if it were a session log. Slower but safer. |
|
616 | 616 | if load_logplay: |
|
617 | 617 | print 'Replaying log...' |
|
618 | 618 | try: |
|
619 | 619 | if IP_rc.debug: |
|
620 | 620 | logplay_quiet = 0 |
|
621 | 621 | else: |
|
622 | 622 | logplay_quiet = 1 |
|
623 | 623 | |
|
624 | 624 | msg.logplay.trap_all() |
|
625 | 625 | IP.safe_execfile(load_logplay,IP.user_ns, |
|
626 | 626 | islog = 1, quiet = logplay_quiet) |
|
627 | 627 | msg.logplay.release_all() |
|
628 | 628 | if IP_rc.messages: |
|
629 | 629 | msg.summary += msg.logplay.summary_all() |
|
630 | 630 | except: |
|
631 | 631 | warn('Problems replaying logfile %s.' % load_logplay) |
|
632 | 632 | IP.InteractiveTB() |
|
633 | 633 | |
|
634 | 634 | # Load remaining files in command line |
|
635 | 635 | msg.user_exec.trap_all() |
|
636 | 636 | |
|
637 | 637 | # Do NOT execute files named in the command line as scripts to be loaded |
|
638 | 638 | # by embedded instances. Doing so has the potential for an infinite |
|
639 | 639 | # recursion if there are exceptions thrown in the process. |
|
640 | 640 | |
|
641 | 641 | # XXX FIXME: the execution of user files should be moved out to after |
|
642 | 642 | # ipython is fully initialized, just as if they were run via %run at the |
|
643 | 643 | # ipython prompt. This would also give them the benefit of ipython's |
|
644 | 644 | # nice tracebacks. |
|
645 | 645 | |
|
646 | 646 | if not embedded and IP_rc.args: |
|
647 | 647 | name_save = IP.user_ns['__name__'] |
|
648 | 648 | IP.user_ns['__name__'] = '__main__' |
|
649 | 649 | try: |
|
650 | 650 | # Set our own excepthook in case the user code tries to call it |
|
651 | 651 | # directly. This prevents triggering the IPython crash handler. |
|
652 | 652 | old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook |
|
653 | 653 | for run in args: |
|
654 | 654 | IP.safe_execfile(run,IP.user_ns) |
|
655 | 655 | finally: |
|
656 | 656 | # Reset our crash handler in place |
|
657 | 657 | sys.excepthook = old_excepthook |
|
658 | 658 | |
|
659 | 659 | IP.user_ns['__name__'] = name_save |
|
660 | 660 | |
|
661 | 661 | msg.user_exec.release_all() |
|
662 | 662 | if IP_rc.messages: |
|
663 | 663 | msg.summary += msg.user_exec.summary_all() |
|
664 | 664 | |
|
665 | 665 | # since we can't specify a null string on the cmd line, 0 is the equivalent: |
|
666 | 666 | if IP_rc.nosep: |
|
667 | 667 | IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0' |
|
668 | 668 | if IP_rc.separate_in == '0': IP_rc.separate_in = '' |
|
669 | 669 | if IP_rc.separate_out == '0': IP_rc.separate_out = '' |
|
670 | 670 | if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = '' |
|
671 | 671 | IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n') |
|
672 | 672 | IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n') |
|
673 | 673 | IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n') |
|
674 | 674 | |
|
675 | 675 | # Determine how many lines at the bottom of the screen are needed for |
|
676 | 676 | # showing prompts, so we can know wheter long strings are to be printed or |
|
677 | 677 | # paged: |
|
678 | 678 | num_lines_bot = IP_rc.separate_in.count('\n')+1 |
|
679 | 679 | IP_rc.screen_length = IP_rc.screen_length - num_lines_bot |
|
680 | 680 | |
|
681 | 681 | # configure startup banner |
|
682 | 682 | if IP_rc.c: # regular python doesn't print the banner with -c |
|
683 | 683 | IP_rc.banner = 0 |
|
684 | 684 | if IP_rc.banner: |
|
685 | 685 | BANN_P = IP.BANNER_PARTS |
|
686 | 686 | else: |
|
687 | 687 | BANN_P = [] |
|
688 | 688 | |
|
689 | 689 | if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile) |
|
690 | 690 | |
|
691 | 691 | # add message log (possibly empty) |
|
692 | 692 | if msg.summary: BANN_P.append(msg.summary) |
|
693 | 693 | # Final banner is a string |
|
694 | 694 | IP.BANNER = '\n'.join(BANN_P) |
|
695 | 695 | |
|
696 | 696 | # Finalize the IPython instance. This assumes the rc structure is fully |
|
697 | 697 | # in place. |
|
698 | 698 | IP.post_config_initialization() |
|
699 | 699 | |
|
700 | 700 | return IP |
|
701 | 701 | #************************ end of file <ipmaker.py> ************************** |
General Comments 0
You need to be logged in to leave comments.
Login now