Show More
The requested changes are too big and content was truncated. Show full diff
@@ -1,483 +1,486 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Tools for inspecting Python objects. |
|
3 | 3 | |
|
4 | 4 | Uses syntax highlighting for presenting the various information elements. |
|
5 | 5 | |
|
6 | 6 | Similar in spirit to the inspect module, but all calls take a name argument to |
|
7 | 7 | reference the name under which an object is being read. |
|
8 | 8 | |
|
9 |
$Id: OInspect.py 13 |
|
|
9 | $Id: OInspect.py 1329 2006-05-26 07:52:45Z fperez $ | |
|
10 | 10 | """ |
|
11 | 11 | |
|
12 | 12 | #***************************************************************************** |
|
13 | 13 | # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu> |
|
14 | 14 | # |
|
15 | 15 | # Distributed under the terms of the BSD License. The full license is in |
|
16 | 16 | # the file COPYING, distributed as part of this software. |
|
17 | 17 | #***************************************************************************** |
|
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 | __all__ = ['Inspector','InspectColors'] |
|
24 | 24 | |
|
25 | 25 | # stdlib modules |
|
26 | 26 | import __builtin__ |
|
27 | 27 | import inspect |
|
28 | 28 | import linecache |
|
29 | 29 | import string |
|
30 | 30 | import StringIO |
|
31 | 31 | import types |
|
32 | 32 | import os |
|
33 | 33 | # IPython's own |
|
34 | 34 | from IPython import PyColorize |
|
35 | 35 | from IPython.genutils import page,indent,Term,mkdict |
|
36 | 36 | from IPython.Itpl import itpl |
|
37 | 37 | from IPython.wildcard import list_namespace |
|
38 | 38 | from IPython.ColorANSI import * |
|
39 | 39 | |
|
40 | 40 | #**************************************************************************** |
|
41 | 41 | # Builtin color schemes |
|
42 | 42 | |
|
43 | 43 | Colors = TermColors # just a shorthand |
|
44 | 44 | |
|
45 | 45 | # Build a few color schemes |
|
46 | 46 | NoColor = ColorScheme( |
|
47 | 47 | 'NoColor',{ |
|
48 | 48 | 'header' : Colors.NoColor, |
|
49 | 49 | 'normal' : Colors.NoColor # color off (usu. Colors.Normal) |
|
50 | 50 | } ) |
|
51 | 51 | |
|
52 | 52 | LinuxColors = ColorScheme( |
|
53 | 53 | 'Linux',{ |
|
54 | 54 | 'header' : Colors.LightRed, |
|
55 | 55 | 'normal' : Colors.Normal # color off (usu. Colors.Normal) |
|
56 | 56 | } ) |
|
57 | 57 | |
|
58 | 58 | LightBGColors = ColorScheme( |
|
59 | 59 | 'LightBG',{ |
|
60 | 60 | 'header' : Colors.Red, |
|
61 | 61 | 'normal' : Colors.Normal # color off (usu. Colors.Normal) |
|
62 | 62 | } ) |
|
63 | 63 | |
|
64 | 64 | # Build table of color schemes (needed by the parser) |
|
65 | 65 | InspectColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors], |
|
66 | 66 | 'Linux') |
|
67 | 67 | |
|
68 | 68 | #**************************************************************************** |
|
69 | 69 | # Auxiliary functions |
|
70 | 70 | def getdoc(obj): |
|
71 | 71 | """Stable wrapper around inspect.getdoc. |
|
72 | 72 | |
|
73 | 73 | This can't crash because of attribute problems. |
|
74 | 74 | |
|
75 | 75 | It also attempts to call a getdoc() method on the given object. This |
|
76 | 76 | allows objects which provide their docstrings via non-standard mechanisms |
|
77 | 77 | (like Pyro proxies) to still be inspected by ipython's ? system.""" |
|
78 | 78 | |
|
79 | 79 | ds = None # default return value |
|
80 | 80 | try: |
|
81 | 81 | ds = inspect.getdoc(obj) |
|
82 | 82 | except: |
|
83 | 83 | # Harden against an inspect failure, which can occur with |
|
84 | 84 | # SWIG-wrapped extensions. |
|
85 | 85 | pass |
|
86 | 86 | # Allow objects to offer customized documentation via a getdoc method: |
|
87 | 87 | try: |
|
88 | 88 | ds2 = obj.getdoc() |
|
89 | 89 | except: |
|
90 | 90 | pass |
|
91 | 91 | else: |
|
92 | 92 | # if we get extra info, we add it to the normal docstring. |
|
93 | 93 | if ds is None: |
|
94 | 94 | ds = ds2 |
|
95 | 95 | else: |
|
96 | 96 | ds = '%s\n%s' % (ds,ds2) |
|
97 | 97 | return ds |
|
98 | 98 | |
|
99 | 99 | #**************************************************************************** |
|
100 | 100 | # Class definitions |
|
101 | 101 | |
|
102 | 102 | class myStringIO(StringIO.StringIO): |
|
103 | 103 | """Adds a writeln method to normal StringIO.""" |
|
104 | 104 | def writeln(self,*arg,**kw): |
|
105 | 105 | """Does a write() and then a write('\n')""" |
|
106 | 106 | self.write(*arg,**kw) |
|
107 | 107 | self.write('\n') |
|
108 | 108 | |
|
109 | 109 | class Inspector: |
|
110 |
def __init__(self,color_table,code_color_table,scheme |
|
|
110 | def __init__(self,color_table,code_color_table,scheme, | |
|
111 | str_detail_level=0): | |
|
111 | 112 | self.color_table = color_table |
|
112 | 113 | self.parser = PyColorize.Parser(code_color_table,out='str') |
|
113 | 114 | self.format = self.parser.format |
|
115 | self.str_detail_level = str_detail_level | |
|
114 | 116 | self.set_active_scheme(scheme) |
|
115 | 117 | |
|
116 | 118 | def __getargspec(self,obj): |
|
117 | 119 | """Get the names and default values of a function's arguments. |
|
118 | 120 | |
|
119 | 121 | A tuple of four things is returned: (args, varargs, varkw, defaults). |
|
120 | 122 | 'args' is a list of the argument names (it may contain nested lists). |
|
121 | 123 | 'varargs' and 'varkw' are the names of the * and ** arguments or None. |
|
122 | 124 | 'defaults' is an n-tuple of the default values of the last n arguments. |
|
123 | 125 | |
|
124 | 126 | Modified version of inspect.getargspec from the Python Standard |
|
125 | 127 | Library.""" |
|
126 | 128 | |
|
127 | 129 | if inspect.isfunction(obj): |
|
128 | 130 | func_obj = obj |
|
129 | 131 | elif inspect.ismethod(obj): |
|
130 | 132 | func_obj = obj.im_func |
|
131 | 133 | else: |
|
132 | 134 | raise TypeError, 'arg is not a Python function' |
|
133 | 135 | args, varargs, varkw = inspect.getargs(func_obj.func_code) |
|
134 | 136 | return args, varargs, varkw, func_obj.func_defaults |
|
135 | 137 | |
|
136 | 138 | def __getdef(self,obj,oname=''): |
|
137 | 139 | """Return the definition header for any callable object. |
|
138 | 140 | |
|
139 | 141 | If any exception is generated, None is returned instead and the |
|
140 | 142 | exception is suppressed.""" |
|
141 | 143 | |
|
142 | 144 | try: |
|
143 | 145 | return oname + inspect.formatargspec(*self.__getargspec(obj)) |
|
144 | 146 | except: |
|
145 | 147 | return None |
|
146 | 148 | |
|
147 | 149 | def __head(self,h): |
|
148 | 150 | """Return a header string with proper colors.""" |
|
149 | 151 | return '%s%s%s' % (self.color_table.active_colors.header,h, |
|
150 | 152 | self.color_table.active_colors.normal) |
|
151 | 153 | |
|
152 | 154 | def set_active_scheme(self,scheme): |
|
153 | 155 | self.color_table.set_active_scheme(scheme) |
|
154 | 156 | self.parser.color_table.set_active_scheme(scheme) |
|
155 | 157 | |
|
156 | 158 | def noinfo(self,msg,oname): |
|
157 | 159 | """Generic message when no information is found.""" |
|
158 | 160 | print 'No %s found' % msg, |
|
159 | 161 | if oname: |
|
160 | 162 | print 'for %s' % oname |
|
161 | 163 | else: |
|
162 | 164 | |
|
163 | 165 | |
|
164 | 166 | def pdef(self,obj,oname=''): |
|
165 | 167 | """Print the definition header for any callable object. |
|
166 | 168 | |
|
167 | 169 | If the object is a class, print the constructor information.""" |
|
168 | 170 | |
|
169 | 171 | if not callable(obj): |
|
170 | 172 | print 'Object is not callable.' |
|
171 | 173 | return |
|
172 | 174 | |
|
173 | 175 | header = '' |
|
174 | 176 | if type(obj) is types.ClassType: |
|
175 | 177 | header = self.__head('Class constructor information:\n') |
|
176 | 178 | obj = obj.__init__ |
|
177 | 179 | elif type(obj) is types.InstanceType: |
|
178 | 180 | obj = obj.__call__ |
|
179 | 181 | |
|
180 | 182 | output = self.__getdef(obj,oname) |
|
181 | 183 | if output is None: |
|
182 | 184 | self.noinfo('definition header',oname) |
|
183 | 185 | else: |
|
184 | 186 | print >>Term.cout, header,self.format(output), |
|
185 | 187 | |
|
186 | 188 | def pdoc(self,obj,oname='',formatter = None): |
|
187 | 189 | """Print the docstring for any object. |
|
188 | 190 | |
|
189 | 191 | Optional: |
|
190 | 192 | -formatter: a function to run the docstring through for specially |
|
191 | 193 | formatted docstrings.""" |
|
192 | 194 | |
|
193 | 195 | head = self.__head # so that itpl can find it even if private |
|
194 | 196 | ds = getdoc(obj) |
|
195 | 197 | if formatter: |
|
196 | 198 | ds = formatter(ds) |
|
197 | 199 | if type(obj) is types.ClassType: |
|
198 | 200 | init_ds = getdoc(obj.__init__) |
|
199 | 201 | output = itpl('$head("Class Docstring:")\n' |
|
200 | 202 | '$indent(ds)\n' |
|
201 | 203 | '$head("Constructor Docstring"):\n' |
|
202 | 204 | '$indent(init_ds)') |
|
203 | 205 | elif type(obj) is types.InstanceType and hasattr(obj,'__call__'): |
|
204 | 206 | call_ds = getdoc(obj.__call__) |
|
205 | 207 | if call_ds: |
|
206 | 208 | output = itpl('$head("Class Docstring:")\n$indent(ds)\n' |
|
207 | 209 | '$head("Calling Docstring:")\n$indent(call_ds)') |
|
208 | 210 | else: |
|
209 | 211 | output = ds |
|
210 | 212 | else: |
|
211 | 213 | output = ds |
|
212 | 214 | if output is None: |
|
213 | 215 | self.noinfo('documentation',oname) |
|
214 | 216 | return |
|
215 | 217 | page(output) |
|
216 | 218 | |
|
217 | 219 | def psource(self,obj,oname=''): |
|
218 | 220 | """Print the source code for an object.""" |
|
219 | 221 | |
|
220 | 222 | # Flush the source cache because inspect can return out-of-date source |
|
221 | 223 | linecache.checkcache() |
|
222 | 224 | try: |
|
223 | 225 | src = inspect.getsource(obj) |
|
224 | 226 | except: |
|
225 | 227 | self.noinfo('source',oname) |
|
226 | 228 | else: |
|
227 | 229 | page(self.format(src)) |
|
228 | 230 | |
|
229 | 231 | def pfile(self,obj,oname=''): |
|
230 | 232 | """Show the whole file where an object was defined.""" |
|
231 | 233 | try: |
|
232 | 234 | sourcelines,lineno = inspect.getsourcelines(obj) |
|
233 | 235 | except: |
|
234 | 236 | self.noinfo('file',oname) |
|
235 | 237 | else: |
|
236 | 238 | # run contents of file through pager starting at line |
|
237 | 239 | # where the object is defined |
|
238 | 240 | ofile = inspect.getabsfile(obj) |
|
239 | 241 | |
|
240 | 242 | if (ofile.endswith('.so') or ofile.endswith('.dll')): |
|
241 | 243 | print 'File %r is binary, not printing.' % ofile |
|
242 | 244 | elif not os.path.isfile(ofile): |
|
243 | 245 | print 'File %r does not exist, not printing.' % ofile |
|
244 | 246 | else: |
|
245 | 247 | # Print only text files, not extension binaries. |
|
246 | 248 | page(self.format(open(ofile).read()),lineno) |
|
247 | 249 | #page(self.format(open(inspect.getabsfile(obj)).read()),lineno) |
|
248 | 250 | |
|
249 | 251 | def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0): |
|
250 | 252 | """Show detailed information about an object. |
|
251 | 253 | |
|
252 | 254 | Optional arguments: |
|
253 | 255 | |
|
254 | 256 | - oname: name of the variable pointing to the object. |
|
255 | 257 | |
|
256 | 258 | - formatter: special formatter for docstrings (see pdoc) |
|
257 | 259 | |
|
258 | 260 | - info: a structure with some information fields which may have been |
|
259 | 261 | precomputed already. |
|
260 | 262 | |
|
261 | 263 | - detail_level: if set to 1, more information is given. |
|
262 | 264 | """ |
|
263 | 265 | |
|
264 | 266 | obj_type = type(obj) |
|
265 | 267 | |
|
266 | 268 | header = self.__head |
|
267 | 269 | if info is None: |
|
268 | 270 | ismagic = 0 |
|
269 | 271 | isalias = 0 |
|
270 | 272 | ospace = '' |
|
271 | 273 | else: |
|
272 | 274 | ismagic = info.ismagic |
|
273 | 275 | isalias = info.isalias |
|
274 | 276 | ospace = info.namespace |
|
275 | 277 | # Get docstring, special-casing aliases: |
|
276 | 278 | if isalias: |
|
277 | 279 | ds = "Alias to the system command:\n %s" % obj[1] |
|
278 | 280 | else: |
|
279 | 281 | ds = getdoc(obj) |
|
280 | 282 | if ds is None: |
|
281 | 283 | ds = '<no docstring>' |
|
282 | 284 | if formatter is not None: |
|
283 | 285 | ds = formatter(ds) |
|
284 | 286 | |
|
285 | 287 | # store output in a list which gets joined with \n at the end. |
|
286 | 288 | out = myStringIO() |
|
287 | 289 | |
|
288 | 290 | string_max = 200 # max size of strings to show (snipped if longer) |
|
289 | 291 | shalf = int((string_max -5)/2) |
|
290 | 292 | |
|
291 | 293 | if ismagic: |
|
292 | 294 | obj_type_name = 'Magic function' |
|
293 | 295 | elif isalias: |
|
294 | 296 | obj_type_name = 'System alias' |
|
295 | 297 | else: |
|
296 | 298 | obj_type_name = obj_type.__name__ |
|
297 | 299 | out.writeln(header('Type:\t\t')+obj_type_name) |
|
298 | 300 | |
|
299 | 301 | try: |
|
300 | 302 | bclass = obj.__class__ |
|
301 | 303 | out.writeln(header('Base Class:\t')+str(bclass)) |
|
302 | 304 | except: pass |
|
303 | 305 | |
|
304 | 306 | # String form, but snip if too long in ? form (full in ??) |
|
305 | try: | |
|
306 |
|
|
|
307 |
str |
|
|
308 | if not detail_level and len(ostr)>string_max: | |
|
309 | ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:] | |
|
310 | ostr = ("\n" + " " * len(str_head.expandtabs())).\ | |
|
311 | join(map(string.strip,ostr.split("\n"))) | |
|
312 | if ostr.find('\n') > -1: | |
|
313 | # Print multi-line strings starting at the next line. | |
|
314 | str_sep = '\n' | |
|
315 | else: | |
|
316 |
|
|
|
317 | out.writeln("%s%s%s" % (header(str_head),str_sep,ostr)) | |
|
318 | except: | |
|
319 |
|
|
|
307 | if detail_level >= self.str_detail_level: | |
|
308 | try: | |
|
309 | ostr = str(obj) | |
|
310 | str_head = 'String Form:' | |
|
311 | if not detail_level and len(ostr)>string_max: | |
|
312 | ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:] | |
|
313 | ostr = ("\n" + " " * len(str_head.expandtabs())).\ | |
|
314 | join(map(string.strip,ostr.split("\n"))) | |
|
315 | if ostr.find('\n') > -1: | |
|
316 | # Print multi-line strings starting at the next line. | |
|
317 | str_sep = '\n' | |
|
318 | else: | |
|
319 | str_sep = '\t' | |
|
320 | out.writeln("%s%s%s" % (header(str_head),str_sep,ostr)) | |
|
321 | except: | |
|
322 | pass | |
|
320 | 323 | |
|
321 | 324 | if ospace: |
|
322 | 325 | out.writeln(header('Namespace:\t')+ospace) |
|
323 | 326 | |
|
324 | 327 | # Length (for strings and lists) |
|
325 | 328 | try: |
|
326 | 329 | length = str(len(obj)) |
|
327 | 330 | out.writeln(header('Length:\t\t')+length) |
|
328 | 331 | except: pass |
|
329 | 332 | |
|
330 | 333 | # Filename where object was defined |
|
331 | 334 | binary_file = False |
|
332 | 335 | try: |
|
333 | 336 | fname = inspect.getabsfile(obj) |
|
334 | 337 | if fname.endswith('<string>'): |
|
335 | 338 | fname = 'Dynamically generated function. No source code available.' |
|
336 | 339 | if (fname.endswith('.so') or fname.endswith('.dll') or |
|
337 | 340 | not os.path.isfile(fname)): |
|
338 | 341 | binary_file = True |
|
339 | 342 | out.writeln(header('File:\t\t')+fname) |
|
340 | 343 | except: |
|
341 | 344 | # if anything goes wrong, we don't want to show source, so it's as |
|
342 | 345 | # if the file was binary |
|
343 | 346 | binary_file = True |
|
344 | 347 | |
|
345 | 348 | # reconstruct the function definition and print it: |
|
346 | 349 | defln = self.__getdef(obj,oname) |
|
347 | 350 | if defln: |
|
348 | 351 | out.write(header('Definition:\t')+self.format(defln)) |
|
349 | 352 | |
|
350 | 353 | # Docstrings only in detail 0 mode, since source contains them (we |
|
351 | 354 | # avoid repetitions). If source fails, we add them back, see below. |
|
352 | 355 | if ds and detail_level == 0: |
|
353 | 356 | out.writeln(header('Docstring:\n') + indent(ds)) |
|
354 | 357 | |
|
355 | 358 | |
|
356 | 359 | # Original source code for any callable |
|
357 | 360 | if detail_level: |
|
358 | 361 | # Flush the source cache because inspect can return out-of-date source |
|
359 | 362 | linecache.checkcache() |
|
360 | 363 | source_success = False |
|
361 | 364 | try: |
|
362 | 365 | if not binary_file: |
|
363 | 366 | source = self.format(inspect.getsource(obj)) |
|
364 | 367 | out.write(header('Source:\n')+source.rstrip()) |
|
365 | 368 | source_success = True |
|
366 | 369 | except: |
|
367 | 370 | pass |
|
368 | 371 | |
|
369 | 372 | if ds and not source_success: |
|
370 | 373 | out.writeln(header('Docstring [source file open failed]:\n') + indent(ds)) |
|
371 | 374 | |
|
372 | 375 | # Constructor docstring for classes |
|
373 | 376 | if obj_type is types.ClassType: |
|
374 | 377 | # reconstruct the function definition and print it: |
|
375 | 378 | try: |
|
376 | 379 | obj_init = obj.__init__ |
|
377 | 380 | except AttributeError: |
|
378 | 381 | init_def = init_ds = None |
|
379 | 382 | else: |
|
380 | 383 | init_def = self.__getdef(obj_init,oname) |
|
381 | 384 | init_ds = getdoc(obj_init) |
|
382 | 385 | |
|
383 | 386 | if init_def or init_ds: |
|
384 | 387 | out.writeln(header('\nConstructor information:')) |
|
385 | 388 | if init_def: |
|
386 | 389 | out.write(header('Definition:\t')+ self.format(init_def)) |
|
387 | 390 | if init_ds: |
|
388 | 391 | out.writeln(header('Docstring:\n') + indent(init_ds)) |
|
389 | 392 | # and class docstring for instances: |
|
390 | 393 | elif obj_type is types.InstanceType: |
|
391 | 394 | |
|
392 | 395 | # First, check whether the instance docstring is identical to the |
|
393 | 396 | # class one, and print it separately if they don't coincide. In |
|
394 | 397 | # most cases they will, but it's nice to print all the info for |
|
395 | 398 | # objects which use instance-customized docstrings. |
|
396 | 399 | if ds: |
|
397 | 400 | class_ds = getdoc(obj.__class__) |
|
398 | 401 | if class_ds and ds != class_ds: |
|
399 | 402 | out.writeln(header('Class Docstring:\n') + |
|
400 | 403 | indent(class_ds)) |
|
401 | 404 | |
|
402 | 405 | # Next, try to show constructor docstrings |
|
403 | 406 | try: |
|
404 | 407 | init_ds = getdoc(obj.__init__) |
|
405 | 408 | except AttributeError: |
|
406 | 409 | init_ds = None |
|
407 | 410 | if init_ds: |
|
408 | 411 | out.writeln(header('Constructor Docstring:\n') + |
|
409 | 412 | indent(init_ds)) |
|
410 | 413 | |
|
411 | 414 | # Call form docstring for callable instances |
|
412 | 415 | if hasattr(obj,'__call__'): |
|
413 | 416 | out.writeln(header('Callable:\t')+'Yes') |
|
414 | 417 | call_def = self.__getdef(obj.__call__,oname) |
|
415 | 418 | if call_def is None: |
|
416 | 419 | out.write(header('Call def:\t')+ |
|
417 | 420 | 'Calling definition not available.') |
|
418 | 421 | else: |
|
419 | 422 | out.write(header('Call def:\t')+self.format(call_def)) |
|
420 | 423 | call_ds = getdoc(obj.__call__) |
|
421 | 424 | if call_ds: |
|
422 | 425 | out.writeln(header('Call docstring:\n') + indent(call_ds)) |
|
423 | 426 | |
|
424 | 427 | # Finally send to printer/pager |
|
425 | 428 | output = out.getvalue() |
|
426 | 429 | if output: |
|
427 | 430 | page(output) |
|
428 | 431 | # end pinfo |
|
429 | 432 | |
|
430 | 433 | def psearch(self,pattern,ns_table,ns_search=[], |
|
431 | 434 | ignore_case=False,show_all=False): |
|
432 | 435 | """Search namespaces with wildcards for objects. |
|
433 | 436 | |
|
434 | 437 | Arguments: |
|
435 | 438 | |
|
436 | 439 | - pattern: string containing shell-like wildcards to use in namespace |
|
437 | 440 | searches and optionally a type specification to narrow the search to |
|
438 | 441 | objects of that type. |
|
439 | 442 | |
|
440 | 443 | - ns_table: dict of name->namespaces for search. |
|
441 | 444 | |
|
442 | 445 | Optional arguments: |
|
443 | 446 | |
|
444 | 447 | - ns_search: list of namespace names to include in search. |
|
445 | 448 | |
|
446 | 449 | - ignore_case(False): make the search case-insensitive. |
|
447 | 450 | |
|
448 | 451 | - show_all(False): show all names, including those starting with |
|
449 | 452 | underscores. |
|
450 | 453 | """ |
|
451 | 454 | # defaults |
|
452 | 455 | type_pattern = 'all' |
|
453 | 456 | filter = '' |
|
454 | 457 | |
|
455 | 458 | cmds = pattern.split() |
|
456 | 459 | len_cmds = len(cmds) |
|
457 | 460 | if len_cmds == 1: |
|
458 | 461 | # Only filter pattern given |
|
459 | 462 | filter = cmds[0] |
|
460 | 463 | elif len_cmds == 2: |
|
461 | 464 | # Both filter and type specified |
|
462 | 465 | filter,type_pattern = cmds |
|
463 | 466 | else: |
|
464 | 467 | raise ValueError('invalid argument string for psearch: <%s>' % |
|
465 | 468 | pattern) |
|
466 | 469 | |
|
467 | 470 | # filter search namespaces |
|
468 | 471 | for name in ns_search: |
|
469 | 472 | if name not in ns_table: |
|
470 | 473 | raise ValueError('invalid namespace <%s>. Valid names: %s' % |
|
471 | 474 | (name,ns_table.keys())) |
|
472 | 475 | |
|
473 | 476 | #print 'type_pattern:',type_pattern # dbg |
|
474 | 477 | search_result = [] |
|
475 | 478 | for ns_name in ns_search: |
|
476 | 479 | ns = ns_table[ns_name] |
|
477 | 480 | tmp_res = list(list_namespace(ns,type_pattern,filter, |
|
478 | 481 | ignore_case=ignore_case, |
|
479 | 482 | show_all=show_all)) |
|
480 | 483 | search_result.extend(tmp_res) |
|
481 | 484 | search_result.sort() |
|
482 | 485 | |
|
483 | 486 | page('\n'.join(search_result)) |
@@ -1,597 +1,607 b'' | |||
|
1 | 1 | # -*- Mode: Shell-Script -*- Not really, but shows comments correctly |
|
2 |
# $Id: ipythonrc 132 |
|
|
2 | # $Id: ipythonrc 1329 2006-05-26 07:52:45Z fperez $ | |
|
3 | 3 | |
|
4 | 4 | #*************************************************************************** |
|
5 | 5 | # |
|
6 | 6 | # Configuration file for IPython -- ipythonrc format |
|
7 | 7 | # |
|
8 | 8 | # The format of this file is simply one of 'key value' lines. |
|
9 | 9 | # Lines containing only whitespace at the beginning and then a # are ignored |
|
10 | 10 | # as comments. But comments can NOT be put on lines with data. |
|
11 | 11 | |
|
12 | 12 | # The meaning and use of each key are explained below. |
|
13 | 13 | |
|
14 | 14 | #--------------------------------------------------------------------------- |
|
15 | 15 | # Section: included files |
|
16 | 16 | |
|
17 | 17 | # Put one or more *config* files (with the syntax of this file) you want to |
|
18 | 18 | # include. For keys with a unique value the outermost file has precedence. For |
|
19 | 19 | # keys with multiple values, they all get assembled into a list which then |
|
20 | 20 | # gets loaded by IPython. |
|
21 | 21 | |
|
22 | 22 | # In this file, all lists of things should simply be space-separated. |
|
23 | 23 | |
|
24 | 24 | # This allows you to build hierarchies of files which recursively load |
|
25 | 25 | # lower-level services. If this is your main ~/.ipython/ipythonrc file, you |
|
26 | 26 | # should only keep here basic things you always want available. Then you can |
|
27 | 27 | # include it in every other special-purpose config file you create. |
|
28 | 28 | include |
|
29 | 29 | |
|
30 | 30 | #--------------------------------------------------------------------------- |
|
31 | 31 | # Section: startup setup |
|
32 | 32 | |
|
33 | 33 | # These are mostly things which parallel a command line option of the same |
|
34 | 34 | # name. |
|
35 | 35 | |
|
36 | 36 | # Keys in this section should only appear once. If any key from this section |
|
37 | 37 | # is encountered more than once, the last value remains, all earlier ones get |
|
38 | 38 | # discarded. |
|
39 | 39 | |
|
40 | 40 | |
|
41 | 41 | # Automatic calling of callable objects. If set to 1 or 2, callable objects |
|
42 | 42 | # are automatically called when invoked at the command line, even if you don't |
|
43 | 43 | # type parentheses. IPython adds the parentheses for you. For example: |
|
44 | 44 | |
|
45 | 45 | #In [1]: str 45 |
|
46 | 46 | #------> str(45) |
|
47 | 47 | #Out[1]: '45' |
|
48 | 48 | |
|
49 | 49 | # IPython reprints your line with '---->' indicating that it added |
|
50 | 50 | # parentheses. While this option is very convenient for interactive use, it |
|
51 | 51 | # may occasionally cause problems with objects which have side-effects if |
|
52 | 52 | # called unexpectedly. |
|
53 | 53 | |
|
54 | 54 | # The valid values for autocall are: |
|
55 | 55 | |
|
56 | 56 | # autocall 0 -> disabled (you can toggle it at runtime with the %autocall magic) |
|
57 | 57 | |
|
58 | 58 | # autocall 1 -> active, but do not apply if there are no arguments on the line. |
|
59 | 59 | |
|
60 | 60 | # In this mode, you get: |
|
61 | 61 | |
|
62 | 62 | #In [1]: callable |
|
63 | 63 | #Out[1]: <built-in function callable> |
|
64 | 64 | |
|
65 | 65 | #In [2]: callable 'hello' |
|
66 | 66 | #------> callable('hello') |
|
67 | 67 | #Out[2]: False |
|
68 | 68 | |
|
69 | 69 | # 2 -> Active always. Even if no arguments are present, the callable object |
|
70 | 70 | # is called: |
|
71 | 71 | |
|
72 | 72 | #In [4]: callable |
|
73 | 73 | #------> callable() |
|
74 | 74 | |
|
75 | 75 | # Note that even with autocall off, you can still use '/' at the start of a |
|
76 | 76 | # line to treat the first argument on the command line as a function and add |
|
77 | 77 | # parentheses to it: |
|
78 | 78 | |
|
79 | 79 | #In [8]: /str 43 |
|
80 | 80 | #------> str(43) |
|
81 | 81 | #Out[8]: '43' |
|
82 | 82 | |
|
83 | 83 | autocall 1 |
|
84 | 84 | |
|
85 | 85 | # Auto-edit syntax errors. When you use the %edit magic in ipython to edit |
|
86 | 86 | # source code (see the 'editor' variable below), it is possible that you save |
|
87 | 87 | # a file with syntax errors in it. If this variable is true, IPython will ask |
|
88 | 88 | # you whether to re-open the editor immediately to correct such an error. |
|
89 | 89 | |
|
90 | 90 | autoedit_syntax 0 |
|
91 | 91 | |
|
92 | 92 | # Auto-indent. IPython can recognize lines ending in ':' and indent the next |
|
93 | 93 | # line, while also un-indenting automatically after 'raise' or 'return'. |
|
94 | 94 | |
|
95 | 95 | # This feature uses the readline library, so it will honor your ~/.inputrc |
|
96 | 96 | # configuration (or whatever file your INPUTRC variable points to). Adding |
|
97 | 97 | # the following lines to your .inputrc file can make indent/unindenting more |
|
98 | 98 | # convenient (M-i indents, M-u unindents): |
|
99 | 99 | |
|
100 | 100 | # $if Python |
|
101 | 101 | # "\M-i": " " |
|
102 | 102 | # "\M-u": "\d\d\d\d" |
|
103 | 103 | # $endif |
|
104 | 104 | |
|
105 | 105 | # The feature is potentially a bit dangerous, because it can cause problems |
|
106 | 106 | # with pasting of indented code (the pasted code gets re-indented on each |
|
107 | 107 | # line). But it's a huge time-saver when working interactively. The magic |
|
108 | 108 | # function %autoindent allows you to toggle it on/off at runtime. |
|
109 | 109 | |
|
110 | 110 | autoindent 1 |
|
111 | 111 | |
|
112 | 112 | # Auto-magic. This gives you access to all the magic functions without having |
|
113 | 113 | # to prepend them with an % sign. If you define a variable with the same name |
|
114 | 114 | # as a magic function (say who=1), you will need to access the magic function |
|
115 | 115 | # with % (%who in this example). However, if later you delete your variable |
|
116 | 116 | # (del who), you'll recover the automagic calling form. |
|
117 | 117 | |
|
118 | 118 | # Considering that many magic functions provide a lot of shell-like |
|
119 | 119 | # functionality, automagic gives you something close to a full Python+system |
|
120 | 120 | # shell environment (and you can extend it further if you want). |
|
121 | 121 | |
|
122 | 122 | automagic 1 |
|
123 | 123 | |
|
124 | 124 | # Size of the output cache. After this many entries are stored, the cache will |
|
125 | 125 | # get flushed. Depending on the size of your intermediate calculations, you |
|
126 | 126 | # may have memory problems if you make it too big, since keeping things in the |
|
127 | 127 | # cache prevents Python from reclaiming the memory for old results. Experiment |
|
128 | 128 | # with a value that works well for you. |
|
129 | 129 | |
|
130 | 130 | # If you choose cache_size 0 IPython will revert to python's regular >>> |
|
131 | 131 | # unnumbered prompt. You will still have _, __ and ___ for your last three |
|
132 | 132 | # results, but that will be it. No dynamic _1, _2, etc. will be created. If |
|
133 | 133 | # you are running on a slow machine or with very limited memory, this may |
|
134 | 134 | # help. |
|
135 | 135 | |
|
136 | 136 | cache_size 1000 |
|
137 | 137 | |
|
138 | 138 | # Classic mode: Setting 'classic 1' you lose many of IPython niceties, |
|
139 | 139 | # but that's your choice! Classic 1 -> same as IPython -classic. |
|
140 | 140 | # Note that this is _not_ the normal python interpreter, it's simply |
|
141 | 141 | # IPython emulating most of the classic interpreter's behavior. |
|
142 | 142 | classic 0 |
|
143 | 143 | |
|
144 | 144 | # colors - Coloring option for prompts and traceback printouts. |
|
145 | 145 | |
|
146 | 146 | # Currently available schemes: NoColor, Linux, LightBG. |
|
147 | 147 | |
|
148 | 148 | # This option allows coloring the prompts and traceback printouts. This |
|
149 | 149 | # requires a terminal which can properly handle color escape sequences. If you |
|
150 | 150 | # are having problems with this, use the NoColor scheme (uses no color escapes |
|
151 | 151 | # at all). |
|
152 | 152 | |
|
153 | 153 | # The Linux option works well in linux console type environments: dark |
|
154 | 154 | # background with light fonts. |
|
155 | 155 | |
|
156 | 156 | # LightBG is similar to Linux but swaps dark/light colors to be more readable |
|
157 | 157 | # in light background terminals. |
|
158 | 158 | |
|
159 | 159 | # keep uncommented only the one you want: |
|
160 | 160 | colors Linux |
|
161 | 161 | #colors LightBG |
|
162 | 162 | #colors NoColor |
|
163 | 163 | |
|
164 | 164 | ######################## |
|
165 | 165 | # Note to Windows users |
|
166 | 166 | # |
|
167 | 167 | # Color and readline support is avaialble to Windows users via Gary Bishop's |
|
168 | 168 | # readline library. You can find Gary's tools at |
|
169 | 169 | # http://sourceforge.net/projects/uncpythontools. |
|
170 | 170 | # Note that his readline module requires in turn the ctypes library, available |
|
171 | 171 | # at http://starship.python.net/crew/theller/ctypes. |
|
172 | 172 | ######################## |
|
173 | 173 | |
|
174 | 174 | # color_info: IPython can display information about objects via a set of |
|
175 | 175 | # functions, and optionally can use colors for this, syntax highlighting |
|
176 | 176 | # source code and various other elements. This information is passed through a |
|
177 | 177 | # pager (it defaults to 'less' if $PAGER is not set). |
|
178 | 178 | |
|
179 | 179 | # If your pager has problems, try to setting it to properly handle escapes |
|
180 | 180 | # (see the less manpage for detail), or disable this option. The magic |
|
181 | 181 | # function %color_info allows you to toggle this interactively for testing. |
|
182 | 182 | |
|
183 | 183 | color_info 1 |
|
184 | 184 | |
|
185 | 185 | # confirm_exit: set to 1 if you want IPython to confirm when you try to exit |
|
186 | 186 | # with an EOF (Control-d in Unix, Control-Z/Enter in Windows). Note that using |
|
187 | 187 | # the magic functions %Exit or %Quit you can force a direct exit, bypassing |
|
188 | 188 | # any confirmation. |
|
189 | 189 | |
|
190 | 190 | confirm_exit 1 |
|
191 | 191 | |
|
192 | 192 | # Use deep_reload() as a substitute for reload() by default. deep_reload() is |
|
193 | 193 | # still available as dreload() and appears as a builtin. |
|
194 | 194 | |
|
195 | 195 | deep_reload 0 |
|
196 | 196 | |
|
197 | 197 | # Which editor to use with the %edit command. If you leave this at 0, IPython |
|
198 | 198 | # will honor your EDITOR environment variable. Since this editor is invoked on |
|
199 | 199 | # the fly by ipython and is meant for editing small code snippets, you may |
|
200 | 200 | # want to use a small, lightweight editor here. |
|
201 | 201 | |
|
202 | 202 | # For Emacs users, setting up your Emacs server properly as described in the |
|
203 | 203 | # manual is a good idea. An alternative is to use jed, a very light editor |
|
204 | 204 | # with much of the feel of Emacs (though not as powerful for heavy-duty work). |
|
205 | 205 | |
|
206 | 206 | editor 0 |
|
207 | 207 | |
|
208 | 208 | # log 1 -> same as ipython -log. This automatically logs to ./ipython.log |
|
209 | 209 | log 0 |
|
210 | 210 | |
|
211 | 211 | # Same as ipython -Logfile YourLogfileName. |
|
212 | 212 | # Don't use with log 1 (use one or the other) |
|
213 | 213 | logfile '' |
|
214 | 214 | |
|
215 | 215 | # banner 0 -> same as ipython -nobanner |
|
216 | 216 | banner 1 |
|
217 | 217 | |
|
218 | 218 | # messages 0 -> same as ipython -nomessages |
|
219 | 219 | messages 1 |
|
220 | 220 | |
|
221 | 221 | # Automatically call the pdb debugger after every uncaught exception. If you |
|
222 | 222 | # are used to debugging using pdb, this puts you automatically inside of it |
|
223 | 223 | # after any call (either in IPython or in code called by it) which triggers an |
|
224 | 224 | # exception which goes uncaught. |
|
225 | 225 | pdb 0 |
|
226 | 226 | |
|
227 | 227 | # Enable the pprint module for printing. pprint tends to give a more readable |
|
228 | 228 | # display (than print) for complex nested data structures. |
|
229 | 229 | pprint 1 |
|
230 | 230 | |
|
231 | 231 | # Prompt strings |
|
232 | 232 | |
|
233 | 233 | # Most bash-like escapes can be used to customize IPython's prompts, as well as |
|
234 | 234 | # a few additional ones which are IPython-specific. All valid prompt escapes |
|
235 | 235 | # are described in detail in the Customization section of the IPython HTML/PDF |
|
236 | 236 | # manual. |
|
237 | 237 | |
|
238 | 238 | # Use \# to represent the current prompt number, and quote them to protect |
|
239 | 239 | # spaces. |
|
240 | 240 | prompt_in1 'In [\#]: ' |
|
241 | 241 | |
|
242 | 242 | # \D is replaced by as many dots as there are digits in the |
|
243 | 243 | # current value of \#. |
|
244 | 244 | prompt_in2 ' .\D.: ' |
|
245 | 245 | |
|
246 | 246 | prompt_out 'Out[\#]: ' |
|
247 | 247 | |
|
248 | 248 | # Select whether to left-pad the output prompts to match the length of the |
|
249 | 249 | # input ones. This allows you for example to use a simple '>' as an output |
|
250 | 250 | # prompt, and yet have the output line up with the input. If set to false, |
|
251 | 251 | # the output prompts will be unpadded (flush left). |
|
252 | 252 | prompts_pad_left 1 |
|
253 | 253 | |
|
254 | 254 | # quick 1 -> same as ipython -quick |
|
255 | 255 | quick 0 |
|
256 | 256 | |
|
257 | 257 | # Use the readline library (1) or not (0). Most users will want this on, but |
|
258 | 258 | # if you experience strange problems with line management (mainly when using |
|
259 | 259 | # IPython inside Emacs buffers) you may try disabling it. Not having it on |
|
260 | 260 | # prevents you from getting command history with the arrow keys, searching and |
|
261 | 261 | # name completion using TAB. |
|
262 | 262 | |
|
263 | 263 | readline 1 |
|
264 | 264 | |
|
265 | 265 | # Screen Length: number of lines of your screen. This is used to control |
|
266 | 266 | # printing of very long strings. Strings longer than this number of lines will |
|
267 | 267 | # be paged with the less command instead of directly printed. |
|
268 | 268 | |
|
269 | 269 | # The default value for this is 0, which means IPython will auto-detect your |
|
270 | 270 | # screen size every time it needs to print. If for some reason this isn't |
|
271 | 271 | # working well (it needs curses support), specify it yourself. Otherwise don't |
|
272 | 272 | # change the default. |
|
273 | 273 | |
|
274 | 274 | screen_length 0 |
|
275 | 275 | |
|
276 | 276 | # Prompt separators for input and output. |
|
277 | 277 | # Use \n for newline explicitly, without quotes. |
|
278 | 278 | # Use 0 (like at the cmd line) to turn off a given separator. |
|
279 | 279 | |
|
280 | 280 | # The structure of prompt printing is: |
|
281 | 281 | # (SeparateIn)Input.... |
|
282 | 282 | # (SeparateOut)Output... |
|
283 | 283 | # (SeparateOut2), # that is, no newline is printed after Out2 |
|
284 | 284 | # By choosing these you can organize your output any way you want. |
|
285 | 285 | |
|
286 | 286 | separate_in \n |
|
287 | 287 | separate_out 0 |
|
288 | 288 | separate_out2 0 |
|
289 | 289 | |
|
290 | 290 | # 'nosep 1' is a shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 0'. |
|
291 | 291 | # Simply removes all input/output separators, overriding the choices above. |
|
292 | 292 | nosep 0 |
|
293 | 293 | |
|
294 | 294 | # Wildcard searches - IPython has a system for searching names using |
|
295 | 295 | # shell-like wildcards; type %psearch? for details. This variables sets |
|
296 | 296 | # whether by default such searches should be case sensitive or not. You can |
|
297 | 297 | # always override the default at the system command line or the IPython |
|
298 | 298 | # prompt. |
|
299 | 299 | |
|
300 | 300 | wildcards_case_sensitive 1 |
|
301 | 301 | |
|
302 | # Object information: at what level of detail to display the string form of an | |
|
303 | # object. If set to 0, ipython will compute the string form of any object X, | |
|
304 | # by calling str(X), when X? is typed. If set to 1, str(X) will only be | |
|
305 | # computed when X?? is given, and if set to 2 or higher, it will never be | |
|
306 | # computed (there is no X??? level of detail). This is mostly of use to | |
|
307 | # people who frequently manipulate objects whose string representation is | |
|
308 | # extremely expensive to compute. | |
|
309 | ||
|
310 | object_info_string_level 0 | |
|
311 | ||
|
302 | 312 | # xmode - Exception reporting mode. |
|
303 | 313 | |
|
304 | 314 | # Valid modes: Plain, Context and Verbose. |
|
305 | 315 | |
|
306 | 316 | # Plain: similar to python's normal traceback printing. |
|
307 | 317 | |
|
308 | 318 | # Context: prints 5 lines of context source code around each line in the |
|
309 | 319 | # traceback. |
|
310 | 320 | |
|
311 | 321 | # Verbose: similar to Context, but additionally prints the variables currently |
|
312 | 322 | # visible where the exception happened (shortening their strings if too |
|
313 | 323 | # long). This can potentially be very slow, if you happen to have a huge data |
|
314 | 324 | # structure whose string representation is complex to compute. Your computer |
|
315 | 325 | # may appear to freeze for a while with cpu usage at 100%. If this occurs, you |
|
316 | 326 | # can cancel the traceback with Ctrl-C (maybe hitting it more than once). |
|
317 | 327 | |
|
318 | 328 | #xmode Plain |
|
319 | 329 | xmode Context |
|
320 | 330 | #xmode Verbose |
|
321 | 331 | |
|
322 | 332 | # multi_line_specials: if true, allow magics, aliases and shell escapes (via |
|
323 | 333 | # !cmd) to be used in multi-line input (like for loops). For example, if you |
|
324 | 334 | # have this active, the following is valid in IPython: |
|
325 | 335 | # |
|
326 | 336 | #In [17]: for i in range(3): |
|
327 | 337 | # ....: mkdir $i |
|
328 | 338 | # ....: !touch $i/hello |
|
329 | 339 | # ....: ls -l $i |
|
330 | 340 | |
|
331 | 341 | multi_line_specials 1 |
|
332 | 342 | |
|
333 | 343 | # wxversion: request a specific wxPython version (used for -wthread) |
|
334 | 344 | |
|
335 | 345 | # Set this to the value of wxPython you want to use, but note that this |
|
336 | 346 | # feature requires you to have the wxversion Python module to work. If you |
|
337 | 347 | # don't have the wxversion module (try 'import wxversion' at the prompt to |
|
338 | 348 | # check) or simply want to leave the system to pick up the default, leave this |
|
339 | 349 | # variable at 0. |
|
340 | 350 | |
|
341 | 351 | wxversion 0 |
|
342 | 352 | |
|
343 | 353 | #--------------------------------------------------------------------------- |
|
344 | 354 | # Section: Readline configuration (readline is not available for MS-Windows) |
|
345 | 355 | |
|
346 | 356 | # This is done via the following options: |
|
347 | 357 | |
|
348 | 358 | # (i) readline_parse_and_bind: this option can appear as many times as you |
|
349 | 359 | # want, each time defining a string to be executed via a |
|
350 | 360 | # readline.parse_and_bind() command. The syntax for valid commands of this |
|
351 | 361 | # kind can be found by reading the documentation for the GNU readline library, |
|
352 | 362 | # as these commands are of the kind which readline accepts in its |
|
353 | 363 | # configuration file. |
|
354 | 364 | |
|
355 | 365 | # The TAB key can be used to complete names at the command line in one of two |
|
356 | 366 | # ways: 'complete' and 'menu-complete'. The difference is that 'complete' only |
|
357 | 367 | # completes as much as possible while 'menu-complete' cycles through all |
|
358 | 368 | # possible completions. Leave the one you prefer uncommented. |
|
359 | 369 | |
|
360 | 370 | readline_parse_and_bind tab: complete |
|
361 | 371 | #readline_parse_and_bind tab: menu-complete |
|
362 | 372 | |
|
363 | 373 | # This binds Control-l to printing the list of all possible completions when |
|
364 | 374 | # there is more than one (what 'complete' does when hitting TAB twice, or at |
|
365 | 375 | # the first TAB if show-all-if-ambiguous is on) |
|
366 | 376 | readline_parse_and_bind "\C-l": possible-completions |
|
367 | 377 | |
|
368 | 378 | # This forces readline to automatically print the above list when tab |
|
369 | 379 | # completion is set to 'complete'. You can still get this list manually by |
|
370 | 380 | # using the key bound to 'possible-completions' (Control-l by default) or by |
|
371 | 381 | # hitting TAB twice. Turning this on makes the printing happen at the first |
|
372 | 382 | # TAB. |
|
373 | 383 | readline_parse_and_bind set show-all-if-ambiguous on |
|
374 | 384 | |
|
375 | 385 | # If you have TAB set to complete names, you can rebind any key (Control-o by |
|
376 | 386 | # default) to insert a true TAB character. |
|
377 | 387 | readline_parse_and_bind "\C-o": tab-insert |
|
378 | 388 | |
|
379 | 389 | # These commands allow you to indent/unindent easily, with the 4-space |
|
380 | 390 | # convention of the Python coding standards. Since IPython's internal |
|
381 | 391 | # auto-indent system also uses 4 spaces, you should not change the number of |
|
382 | 392 | # spaces in the code below. |
|
383 | 393 | readline_parse_and_bind "\M-i": " " |
|
384 | 394 | readline_parse_and_bind "\M-o": "\d\d\d\d" |
|
385 | 395 | readline_parse_and_bind "\M-I": "\d\d\d\d" |
|
386 | 396 | |
|
387 | 397 | # Bindings for incremental searches in the history. These searches use the |
|
388 | 398 | # string typed so far on the command line and search anything in the previous |
|
389 | 399 | # input history containing them. |
|
390 | 400 | readline_parse_and_bind "\C-r": reverse-search-history |
|
391 | 401 | readline_parse_and_bind "\C-s": forward-search-history |
|
392 | 402 | |
|
393 | 403 | # Bindings for completing the current line in the history of previous |
|
394 | 404 | # commands. This allows you to recall any previous command by typing its first |
|
395 | 405 | # few letters and hitting Control-p, bypassing all intermediate commands which |
|
396 | 406 | # may be in the history (much faster than hitting up-arrow 50 times!) |
|
397 | 407 | readline_parse_and_bind "\C-p": history-search-backward |
|
398 | 408 | readline_parse_and_bind "\C-n": history-search-forward |
|
399 | 409 | |
|
400 | 410 | # I also like to have the same functionality on the plain arrow keys. If you'd |
|
401 | 411 | # rather have the arrows use all the history (and not just match what you've |
|
402 | 412 | # typed so far), comment out or delete the next two lines. |
|
403 | 413 | readline_parse_and_bind "\e[A": history-search-backward |
|
404 | 414 | readline_parse_and_bind "\e[B": history-search-forward |
|
405 | 415 | |
|
406 | 416 | # These are typically on by default under *nix, but not win32. |
|
407 | 417 | readline_parse_and_bind "\C-k": kill-line |
|
408 | 418 | readline_parse_and_bind "\C-u": unix-line-discard |
|
409 | 419 | |
|
410 | 420 | # (ii) readline_remove_delims: a string of characters to be removed from the |
|
411 | 421 | # default word-delimiters list used by readline, so that completions may be |
|
412 | 422 | # performed on strings which contain them. |
|
413 | 423 | |
|
414 | 424 | readline_remove_delims -/~ |
|
415 | 425 | |
|
416 | 426 | # (iii) readline_merge_completions: whether to merge the result of all |
|
417 | 427 | # possible completions or not. If true, IPython will complete filenames, |
|
418 | 428 | # python names and aliases and return all possible completions. If you set it |
|
419 | 429 | # to false, each completer is used at a time, and only if it doesn't return |
|
420 | 430 | # any completions is the next one used. |
|
421 | 431 | |
|
422 | 432 | # The default order is: [python_matches, file_matches, alias_matches] |
|
423 | 433 | |
|
424 | 434 | readline_merge_completions 1 |
|
425 | 435 | |
|
426 | 436 | # (iv) readline_omit__names: normally hitting <tab> after a '.' in a name |
|
427 | 437 | # will complete all attributes of an object, including all the special methods |
|
428 | 438 | # whose names start with single or double underscores (like __getitem__ or |
|
429 | 439 | # __class__). |
|
430 | 440 | |
|
431 | 441 | # This variable allows you to control this completion behavior: |
|
432 | 442 | |
|
433 | 443 | # readline_omit__names 1 -> completion will omit showing any names starting |
|
434 | 444 | # with two __, but it will still show names starting with one _. |
|
435 | 445 | |
|
436 | 446 | # readline_omit__names 2 -> completion will omit all names beginning with one |
|
437 | 447 | # _ (which obviously means filtering out the double __ ones). |
|
438 | 448 | |
|
439 | 449 | # Even when this option is set, you can still see those names by explicitly |
|
440 | 450 | # typing a _ after the period and hitting <tab>: 'name._<tab>' will always |
|
441 | 451 | # complete attribute names starting with '_'. |
|
442 | 452 | |
|
443 | 453 | # This option is off by default so that new users see all attributes of any |
|
444 | 454 | # objects they are dealing with. |
|
445 | 455 | |
|
446 | 456 | readline_omit__names 0 |
|
447 | 457 | |
|
448 | 458 | #--------------------------------------------------------------------------- |
|
449 | 459 | # Section: modules to be loaded with 'import ...' |
|
450 | 460 | |
|
451 | 461 | # List, separated by spaces, the names of the modules you want to import |
|
452 | 462 | |
|
453 | 463 | # Example: |
|
454 | 464 | # import_mod sys os |
|
455 | 465 | # will produce internally the statements |
|
456 | 466 | # import sys |
|
457 | 467 | # import os |
|
458 | 468 | |
|
459 | 469 | # Each import is executed in its own try/except block, so if one module |
|
460 | 470 | # fails to load the others will still be ok. |
|
461 | 471 | |
|
462 | 472 | import_mod |
|
463 | 473 | |
|
464 | 474 | #--------------------------------------------------------------------------- |
|
465 | 475 | # Section: modules to import some functions from: 'from ... import ...' |
|
466 | 476 | |
|
467 | 477 | # List, one per line, the modules for which you want only to import some |
|
468 | 478 | # functions. Give the module name first and then the name of functions to be |
|
469 | 479 | # imported from that module. |
|
470 | 480 | |
|
471 | 481 | # Example: |
|
472 | 482 | |
|
473 | 483 | # import_some IPython.genutils timing timings |
|
474 | 484 | # will produce internally the statement |
|
475 | 485 | # from IPython.genutils import timing, timings |
|
476 | 486 | |
|
477 | 487 | # timing() and timings() are two IPython utilities for timing the execution of |
|
478 | 488 | # your own functions, which you may find useful. Just commment out the above |
|
479 | 489 | # line if you want to test them. |
|
480 | 490 | |
|
481 | 491 | # If you have more than one modules_some line, each gets its own try/except |
|
482 | 492 | # block (like modules, see above). |
|
483 | 493 | |
|
484 | 494 | import_some |
|
485 | 495 | |
|
486 | 496 | #--------------------------------------------------------------------------- |
|
487 | 497 | # Section: modules to import all from : 'from ... import *' |
|
488 | 498 | |
|
489 | 499 | # List (same syntax as import_mod above) those modules for which you want to |
|
490 | 500 | # import all functions. Remember, this is a potentially dangerous thing to do, |
|
491 | 501 | # since it is very easy to overwrite names of things you need. Use with |
|
492 | 502 | # caution. |
|
493 | 503 | |
|
494 | 504 | # Example: |
|
495 | 505 | # import_all sys os |
|
496 | 506 | # will produce internally the statements |
|
497 | 507 | # from sys import * |
|
498 | 508 | # from os import * |
|
499 | 509 | |
|
500 | 510 | # As before, each will be called in a separate try/except block. |
|
501 | 511 | |
|
502 | 512 | import_all |
|
503 | 513 | |
|
504 | 514 | #--------------------------------------------------------------------------- |
|
505 | 515 | # Section: Python code to execute. |
|
506 | 516 | |
|
507 | 517 | # Put here code to be explicitly executed (keep it simple!) |
|
508 | 518 | # Put one line of python code per line. All whitespace is removed (this is a |
|
509 | 519 | # feature, not a bug), so don't get fancy building loops here. |
|
510 | 520 | # This is just for quick convenient creation of things you want available. |
|
511 | 521 | |
|
512 | 522 | # Example: |
|
513 | 523 | # execute x = 1 |
|
514 | 524 | # execute print 'hello world'; y = z = 'a' |
|
515 | 525 | # will produce internally |
|
516 | 526 | # x = 1 |
|
517 | 527 | # print 'hello world'; y = z = 'a' |
|
518 | 528 | # and each *line* (not each statement, we don't do python syntax parsing) is |
|
519 | 529 | # executed in its own try/except block. |
|
520 | 530 | |
|
521 | 531 | execute |
|
522 | 532 | |
|
523 | 533 | # Note for the adventurous: you can use this to define your own names for the |
|
524 | 534 | # magic functions, by playing some namespace tricks: |
|
525 | 535 | |
|
526 | 536 | # execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile |
|
527 | 537 | |
|
528 | 538 | # defines %pf as a new name for %profile. |
|
529 | 539 | |
|
530 | 540 | #--------------------------------------------------------------------------- |
|
531 | 541 | # Section: Pyhton files to load and execute. |
|
532 | 542 | |
|
533 | 543 | # Put here the full names of files you want executed with execfile(file). If |
|
534 | 544 | # you want complicated initialization, just write whatever you want in a |
|
535 | 545 | # regular python file and load it from here. |
|
536 | 546 | |
|
537 | 547 | # Filenames defined here (which *must* include the extension) are searched for |
|
538 | 548 | # through all of sys.path. Since IPython adds your .ipython directory to |
|
539 | 549 | # sys.path, they can also be placed in your .ipython dir and will be |
|
540 | 550 | # found. Otherwise (if you want to execute things not in .ipyton nor in |
|
541 | 551 | # sys.path) give a full path (you can use ~, it gets expanded) |
|
542 | 552 | |
|
543 | 553 | # Example: |
|
544 | 554 | # execfile file1.py ~/file2.py |
|
545 | 555 | # will generate |
|
546 | 556 | # execfile('file1.py') |
|
547 | 557 | # execfile('_path_to_your_home/file2.py') |
|
548 | 558 | |
|
549 | 559 | # As before, each file gets its own try/except block. |
|
550 | 560 | |
|
551 | 561 | execfile |
|
552 | 562 | |
|
553 | 563 | # If you are feeling adventurous, you can even add functionality to IPython |
|
554 | 564 | # through here. IPython works through a global variable called __ip which |
|
555 | 565 | # exists at the time when these files are read. If you know what you are doing |
|
556 | 566 | # (read the source) you can add functions to __ip in files loaded here. |
|
557 | 567 | |
|
558 | 568 | # The file example-magic.py contains a simple but correct example. Try it: |
|
559 | 569 | |
|
560 | 570 | # execfile example-magic.py |
|
561 | 571 | |
|
562 | 572 | # Look at the examples in IPython/iplib.py for more details on how these magic |
|
563 | 573 | # functions need to process their arguments. |
|
564 | 574 | |
|
565 | 575 | #--------------------------------------------------------------------------- |
|
566 | 576 | # Section: aliases for system shell commands |
|
567 | 577 | |
|
568 | 578 | # Here you can define your own names for system commands. The syntax is |
|
569 | 579 | # similar to that of the builtin %alias function: |
|
570 | 580 | |
|
571 | 581 | # alias alias_name command_string |
|
572 | 582 | |
|
573 | 583 | # The resulting aliases are auto-generated magic functions (hence usable as |
|
574 | 584 | # %alias_name) |
|
575 | 585 | |
|
576 | 586 | # For example: |
|
577 | 587 | |
|
578 | 588 | # alias myls ls -la |
|
579 | 589 | |
|
580 | 590 | # will define 'myls' as an alias for executing the system command 'ls -la'. |
|
581 | 591 | # This allows you to customize IPython's environment to have the same aliases |
|
582 | 592 | # you are accustomed to from your own shell. |
|
583 | 593 | |
|
584 | 594 | # You can also define aliases with parameters using %s specifiers (one per |
|
585 | 595 | # parameter): |
|
586 | 596 | |
|
587 | 597 | # alias parts echo first %s second %s |
|
588 | 598 | |
|
589 | 599 | # will give you in IPython: |
|
590 | 600 | # >>> %parts A B |
|
591 | 601 | # first A second B |
|
592 | 602 | |
|
593 | 603 | # Use one 'alias' statement per alias you wish to define. |
|
594 | 604 | |
|
595 | 605 | # alias |
|
596 | 606 | |
|
597 | 607 | #************************* end of file <ipythonrc> ************************ |
@@ -1,2291 +1,2300 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | IPython -- An enhanced Interactive Python |
|
4 | 4 | |
|
5 | 5 | Requires Python 2.3 or newer. |
|
6 | 6 | |
|
7 | 7 | This file contains all the classes and helper functions specific to IPython. |
|
8 | 8 | |
|
9 |
$Id: iplib.py 132 |
|
|
9 | $Id: iplib.py 1329 2006-05-26 07:52:45Z fperez $ | |
|
10 | 10 | """ |
|
11 | 11 | |
|
12 | 12 | #***************************************************************************** |
|
13 | 13 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
14 | 14 | # Copyright (C) 2001-2006 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 IPython import Release |
|
32 | 32 | __author__ = '%s <%s>\n%s <%s>' % \ |
|
33 | 33 | ( Release.authors['Janko'] + Release.authors['Fernando'] ) |
|
34 | 34 | __license__ = Release.license |
|
35 | 35 | __version__ = Release.version |
|
36 | 36 | |
|
37 | 37 | # Python standard modules |
|
38 | 38 | import __main__ |
|
39 | 39 | import __builtin__ |
|
40 | 40 | import StringIO |
|
41 | 41 | import bdb |
|
42 | 42 | import cPickle as pickle |
|
43 | 43 | import codeop |
|
44 | 44 | import exceptions |
|
45 | 45 | import glob |
|
46 | 46 | import inspect |
|
47 | 47 | import keyword |
|
48 | 48 | import new |
|
49 | 49 | import os |
|
50 | 50 | import pdb |
|
51 | 51 | import pydoc |
|
52 | 52 | import re |
|
53 | 53 | import shutil |
|
54 | 54 | import string |
|
55 | 55 | import sys |
|
56 | 56 | import tempfile |
|
57 | 57 | import traceback |
|
58 | 58 | import types |
|
59 | 59 | import pickleshare |
|
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.ipstruct 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 | import IPython.ipapi |
|
77 | 77 | |
|
78 | 78 | # Globals |
|
79 | 79 | |
|
80 | 80 | # store the builtin raw_input globally, and use this always, in case user code |
|
81 | 81 | # overwrites it (like wx.py.PyShell does) |
|
82 | 82 | raw_input_original = raw_input |
|
83 | 83 | |
|
84 | 84 | # compiled regexps for autoindent management |
|
85 | 85 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
86 | 86 | |
|
87 | 87 | |
|
88 | 88 | #**************************************************************************** |
|
89 | 89 | # Some utility function definitions |
|
90 | 90 | |
|
91 | 91 | ini_spaces_re = re.compile(r'^(\s+)') |
|
92 | 92 | |
|
93 | 93 | def num_ini_spaces(strng): |
|
94 | 94 | """Return the number of initial spaces in a string""" |
|
95 | 95 | |
|
96 | 96 | ini_spaces = ini_spaces_re.match(strng) |
|
97 | 97 | if ini_spaces: |
|
98 | 98 | return ini_spaces.end() |
|
99 | 99 | else: |
|
100 | 100 | return 0 |
|
101 | 101 | |
|
102 | 102 | def softspace(file, newvalue): |
|
103 | 103 | """Copied from code.py, to remove the dependency""" |
|
104 | 104 | |
|
105 | 105 | oldvalue = 0 |
|
106 | 106 | try: |
|
107 | 107 | oldvalue = file.softspace |
|
108 | 108 | except AttributeError: |
|
109 | 109 | pass |
|
110 | 110 | try: |
|
111 | 111 | file.softspace = newvalue |
|
112 | 112 | except (AttributeError, TypeError): |
|
113 | 113 | # "attribute-less object" or "read-only attributes" |
|
114 | 114 | pass |
|
115 | 115 | return oldvalue |
|
116 | 116 | |
|
117 | 117 | |
|
118 | 118 | #**************************************************************************** |
|
119 | 119 | # Local use exceptions |
|
120 | 120 | class SpaceInInput(exceptions.Exception): pass |
|
121 | 121 | |
|
122 | 122 | |
|
123 | 123 | #**************************************************************************** |
|
124 | 124 | # Local use classes |
|
125 | 125 | class Bunch: pass |
|
126 | 126 | |
|
127 | 127 | class Undefined: pass |
|
128 | 128 | |
|
129 | 129 | class InputList(list): |
|
130 | 130 | """Class to store user input. |
|
131 | 131 | |
|
132 | 132 | It's basically a list, but slices return a string instead of a list, thus |
|
133 | 133 | allowing things like (assuming 'In' is an instance): |
|
134 | 134 | |
|
135 | 135 | exec In[4:7] |
|
136 | 136 | |
|
137 | 137 | or |
|
138 | 138 | |
|
139 | 139 | exec In[5:9] + In[14] + In[21:25]""" |
|
140 | 140 | |
|
141 | 141 | def __getslice__(self,i,j): |
|
142 | 142 | return ''.join(list.__getslice__(self,i,j)) |
|
143 | 143 | |
|
144 | 144 | class SyntaxTB(ultraTB.ListTB): |
|
145 | 145 | """Extension which holds some state: the last exception value""" |
|
146 | 146 | |
|
147 | 147 | def __init__(self,color_scheme = 'NoColor'): |
|
148 | 148 | ultraTB.ListTB.__init__(self,color_scheme) |
|
149 | 149 | self.last_syntax_error = None |
|
150 | 150 | |
|
151 | 151 | def __call__(self, etype, value, elist): |
|
152 | 152 | self.last_syntax_error = value |
|
153 | 153 | ultraTB.ListTB.__call__(self,etype,value,elist) |
|
154 | 154 | |
|
155 | 155 | def clear_err_state(self): |
|
156 | 156 | """Return the current error state and clear it""" |
|
157 | 157 | e = self.last_syntax_error |
|
158 | 158 | self.last_syntax_error = None |
|
159 | 159 | return e |
|
160 | 160 | |
|
161 | 161 | #**************************************************************************** |
|
162 | 162 | # Main IPython class |
|
163 | 163 | |
|
164 | 164 | # FIXME: the Magic class is a mixin for now, and will unfortunately remain so |
|
165 | 165 | # until a full rewrite is made. I've cleaned all cross-class uses of |
|
166 | 166 | # attributes and methods, but too much user code out there relies on the |
|
167 | 167 | # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage. |
|
168 | 168 | # |
|
169 | 169 | # But at least now, all the pieces have been separated and we could, in |
|
170 | 170 | # principle, stop using the mixin. This will ease the transition to the |
|
171 | 171 | # chainsaw branch. |
|
172 | 172 | |
|
173 | 173 | # For reference, the following is the list of 'self.foo' uses in the Magic |
|
174 | 174 | # class as of 2005-12-28. These are names we CAN'T use in the main ipython |
|
175 | 175 | # class, to prevent clashes. |
|
176 | 176 | |
|
177 | 177 | # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind', |
|
178 | 178 | # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic', |
|
179 | 179 | # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell', |
|
180 | 180 | # 'self.value'] |
|
181 | 181 | |
|
182 | 182 | class InteractiveShell(object,Magic): |
|
183 | 183 | """An enhanced console for Python.""" |
|
184 | 184 | |
|
185 | 185 | # class attribute to indicate whether the class supports threads or not. |
|
186 | 186 | # Subclasses with thread support should override this as needed. |
|
187 | 187 | isthreaded = False |
|
188 | 188 | |
|
189 | 189 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), |
|
190 | 190 | user_ns = None,user_global_ns=None,banner2='', |
|
191 | 191 | custom_exceptions=((),None),embedded=False): |
|
192 | 192 | |
|
193 | 193 | |
|
194 | 194 | # log system |
|
195 | 195 | self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate') |
|
196 | 196 | |
|
197 | 197 | # some minimal strict typechecks. For some core data structures, I |
|
198 | 198 | # want actual basic python types, not just anything that looks like |
|
199 | 199 | # one. This is especially true for namespaces. |
|
200 | 200 | for ns in (user_ns,user_global_ns): |
|
201 | 201 | if ns is not None and type(ns) != types.DictType: |
|
202 | 202 | raise TypeError,'namespace must be a dictionary' |
|
203 | 203 | |
|
204 | 204 | # Job manager (for jobs run as background threads) |
|
205 | 205 | self.jobs = BackgroundJobManager() |
|
206 | 206 | |
|
207 | 207 | # Store the actual shell's name |
|
208 | 208 | self.name = name |
|
209 | 209 | |
|
210 | 210 | # We need to know whether the instance is meant for embedding, since |
|
211 | 211 | # global/local namespaces need to be handled differently in that case |
|
212 | 212 | self.embedded = embedded |
|
213 | 213 | |
|
214 | 214 | # command compiler |
|
215 | 215 | self.compile = codeop.CommandCompiler() |
|
216 | 216 | |
|
217 | 217 | # User input buffer |
|
218 | 218 | self.buffer = [] |
|
219 | 219 | |
|
220 | 220 | # Default name given in compilation of code |
|
221 | 221 | self.filename = '<ipython console>' |
|
222 | 222 | |
|
223 | 223 | # Make an empty namespace, which extension writers can rely on both |
|
224 | 224 | # existing and NEVER being used by ipython itself. This gives them a |
|
225 | 225 | # convenient location for storing additional information and state |
|
226 | 226 | # their extensions may require, without fear of collisions with other |
|
227 | 227 | # ipython names that may develop later. |
|
228 | 228 | self.meta = Struct() |
|
229 | 229 | |
|
230 | 230 | # Create the namespace where the user will operate. user_ns is |
|
231 | 231 | # normally the only one used, and it is passed to the exec calls as |
|
232 | 232 | # the locals argument. But we do carry a user_global_ns namespace |
|
233 | 233 | # given as the exec 'globals' argument, This is useful in embedding |
|
234 | 234 | # situations where the ipython shell opens in a context where the |
|
235 | 235 | # distinction between locals and globals is meaningful. |
|
236 | 236 | |
|
237 | 237 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
238 | 238 | # level as a dict instead of a module. This is a manual fix, but I |
|
239 | 239 | # should really track down where the problem is coming from. Alex |
|
240 | 240 | # Schmolck reported this problem first. |
|
241 | 241 | |
|
242 | 242 | # A useful post by Alex Martelli on this topic: |
|
243 | 243 | # Re: inconsistent value from __builtins__ |
|
244 | 244 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
245 | 245 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
246 | 246 | # Gruppen: comp.lang.python |
|
247 | 247 | |
|
248 | 248 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
249 | 249 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
250 | 250 | # > <type 'dict'> |
|
251 | 251 | # > >>> print type(__builtins__) |
|
252 | 252 | # > <type 'module'> |
|
253 | 253 | # > Is this difference in return value intentional? |
|
254 | 254 | |
|
255 | 255 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
256 | 256 | # or a module, and it's been that way for a long time. Whether it's |
|
257 | 257 | # intentional (or sensible), I don't know. In any case, the idea is |
|
258 | 258 | # that if you need to access the built-in namespace directly, you |
|
259 | 259 | # should start with "import __builtin__" (note, no 's') which will |
|
260 | 260 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
261 | 261 | |
|
262 | 262 | # These routines return properly built dicts as needed by the rest of |
|
263 | 263 | # the code, and can also be used by extension writers to generate |
|
264 | 264 | # properly initialized namespaces. |
|
265 | 265 | user_ns = IPython.ipapi.make_user_ns(user_ns) |
|
266 | 266 | user_global_ns = IPython.ipapi.make_user_global_ns(user_global_ns) |
|
267 | 267 | |
|
268 | 268 | # Assign namespaces |
|
269 | 269 | # This is the namespace where all normal user variables live |
|
270 | 270 | self.user_ns = user_ns |
|
271 | 271 | # Embedded instances require a separate namespace for globals. |
|
272 | 272 | # Normally this one is unused by non-embedded instances. |
|
273 | 273 | self.user_global_ns = user_global_ns |
|
274 | 274 | # A namespace to keep track of internal data structures to prevent |
|
275 | 275 | # them from cluttering user-visible stuff. Will be updated later |
|
276 | 276 | self.internal_ns = {} |
|
277 | 277 | |
|
278 | 278 | # Namespace of system aliases. Each entry in the alias |
|
279 | 279 | # table must be a 2-tuple of the form (N,name), where N is the number |
|
280 | 280 | # of positional arguments of the alias. |
|
281 | 281 | self.alias_table = {} |
|
282 | 282 | |
|
283 | 283 | # A table holding all the namespaces IPython deals with, so that |
|
284 | 284 | # introspection facilities can search easily. |
|
285 | 285 | self.ns_table = {'user':user_ns, |
|
286 | 286 | 'user_global':user_global_ns, |
|
287 | 287 | 'alias':self.alias_table, |
|
288 | 288 | 'internal':self.internal_ns, |
|
289 | 289 | 'builtin':__builtin__.__dict__ |
|
290 | 290 | } |
|
291 | 291 | |
|
292 | 292 | # The user namespace MUST have a pointer to the shell itself. |
|
293 | 293 | self.user_ns[name] = self |
|
294 | 294 | |
|
295 | 295 | # We need to insert into sys.modules something that looks like a |
|
296 | 296 | # module but which accesses the IPython namespace, for shelve and |
|
297 | 297 | # pickle to work interactively. Normally they rely on getting |
|
298 | 298 | # everything out of __main__, but for embedding purposes each IPython |
|
299 | 299 | # instance has its own private namespace, so we can't go shoving |
|
300 | 300 | # everything into __main__. |
|
301 | 301 | |
|
302 | 302 | # note, however, that we should only do this for non-embedded |
|
303 | 303 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
304 | 304 | # namespace. Embedded instances, on the other hand, should not do |
|
305 | 305 | # this because they need to manage the user local/global namespaces |
|
306 | 306 | # only, but they live within a 'normal' __main__ (meaning, they |
|
307 | 307 | # shouldn't overtake the execution environment of the script they're |
|
308 | 308 | # embedded in). |
|
309 | 309 | |
|
310 | 310 | if not embedded: |
|
311 | 311 | try: |
|
312 | 312 | main_name = self.user_ns['__name__'] |
|
313 | 313 | except KeyError: |
|
314 | 314 | raise KeyError,'user_ns dictionary MUST have a "__name__" key' |
|
315 | 315 | else: |
|
316 | 316 | #print "pickle hack in place" # dbg |
|
317 | 317 | #print 'main_name:',main_name # dbg |
|
318 | 318 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
319 | 319 | |
|
320 | 320 | # List of input with multi-line handling. |
|
321 | 321 | # Fill its zero entry, user counter starts at 1 |
|
322 | 322 | self.input_hist = InputList(['\n']) |
|
323 | 323 | # This one will hold the 'raw' input history, without any |
|
324 | 324 | # pre-processing. This will allow users to retrieve the input just as |
|
325 | 325 | # it was exactly typed in by the user, with %hist -r. |
|
326 | 326 | self.input_hist_raw = InputList(['\n']) |
|
327 | 327 | |
|
328 | 328 | # list of visited directories |
|
329 | 329 | try: |
|
330 | 330 | self.dir_hist = [os.getcwd()] |
|
331 | 331 | except IOError, e: |
|
332 | 332 | self.dir_hist = [] |
|
333 | 333 | |
|
334 | 334 | # dict of output history |
|
335 | 335 | self.output_hist = {} |
|
336 | 336 | |
|
337 | 337 | # dict of things NOT to alias (keywords, builtins and some magics) |
|
338 | 338 | no_alias = {} |
|
339 | 339 | no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias'] |
|
340 | 340 | for key in keyword.kwlist + no_alias_magics: |
|
341 | 341 | no_alias[key] = 1 |
|
342 | 342 | no_alias.update(__builtin__.__dict__) |
|
343 | 343 | self.no_alias = no_alias |
|
344 | 344 | |
|
345 | 345 | # make global variables for user access to these |
|
346 | 346 | self.user_ns['_ih'] = self.input_hist |
|
347 | 347 | self.user_ns['_oh'] = self.output_hist |
|
348 | 348 | self.user_ns['_dh'] = self.dir_hist |
|
349 | 349 | |
|
350 | 350 | # user aliases to input and output histories |
|
351 | 351 | self.user_ns['In'] = self.input_hist |
|
352 | 352 | self.user_ns['Out'] = self.output_hist |
|
353 | 353 | |
|
354 | 354 | # Object variable to store code object waiting execution. This is |
|
355 | 355 | # used mainly by the multithreaded shells, but it can come in handy in |
|
356 | 356 | # other situations. No need to use a Queue here, since it's a single |
|
357 | 357 | # item which gets cleared once run. |
|
358 | 358 | self.code_to_run = None |
|
359 | 359 | |
|
360 | 360 | # escapes for automatic behavior on the command line |
|
361 | 361 | self.ESC_SHELL = '!' |
|
362 | 362 | self.ESC_HELP = '?' |
|
363 | 363 | self.ESC_MAGIC = '%' |
|
364 | 364 | self.ESC_QUOTE = ',' |
|
365 | 365 | self.ESC_QUOTE2 = ';' |
|
366 | 366 | self.ESC_PAREN = '/' |
|
367 | 367 | |
|
368 | 368 | # And their associated handlers |
|
369 | 369 | self.esc_handlers = {self.ESC_PAREN : self.handle_auto, |
|
370 | 370 | self.ESC_QUOTE : self.handle_auto, |
|
371 | 371 | self.ESC_QUOTE2 : self.handle_auto, |
|
372 | 372 | self.ESC_MAGIC : self.handle_magic, |
|
373 | 373 | self.ESC_HELP : self.handle_help, |
|
374 | 374 | self.ESC_SHELL : self.handle_shell_escape, |
|
375 | 375 | } |
|
376 | 376 | |
|
377 | 377 | # class initializations |
|
378 | 378 | Magic.__init__(self,self) |
|
379 | 379 | |
|
380 | 380 | # Python source parser/formatter for syntax highlighting |
|
381 | 381 | pyformat = PyColorize.Parser().format |
|
382 | 382 | self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors']) |
|
383 | 383 | |
|
384 | 384 | # hooks holds pointers used for user-side customizations |
|
385 | 385 | self.hooks = Struct() |
|
386 | 386 | |
|
387 | 387 | # Set all default hooks, defined in the IPython.hooks module. |
|
388 | 388 | hooks = IPython.hooks |
|
389 | 389 | for hook_name in hooks.__all__: |
|
390 | 390 | # default hooks have priority 100, i.e. low; user hooks should have 0-100 priority |
|
391 | 391 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
392 | 392 | #print "bound hook",hook_name |
|
393 | 393 | |
|
394 | 394 | # Flag to mark unconditional exit |
|
395 | 395 | self.exit_now = False |
|
396 | 396 | |
|
397 | 397 | self.usage_min = """\ |
|
398 | 398 | An enhanced console for Python. |
|
399 | 399 | Some of its features are: |
|
400 | 400 | - Readline support if the readline library is present. |
|
401 | 401 | - Tab completion in the local namespace. |
|
402 | 402 | - Logging of input, see command-line options. |
|
403 | 403 | - System shell escape via ! , eg !ls. |
|
404 | 404 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) |
|
405 | 405 | - Keeps track of locally defined variables via %who, %whos. |
|
406 | 406 | - Show object information with a ? eg ?x or x? (use ?? for more info). |
|
407 | 407 | """ |
|
408 | 408 | if usage: self.usage = usage |
|
409 | 409 | else: self.usage = self.usage_min |
|
410 | 410 | |
|
411 | 411 | # Storage |
|
412 | 412 | self.rc = rc # This will hold all configuration information |
|
413 | 413 | self.pager = 'less' |
|
414 | 414 | # temporary files used for various purposes. Deleted at exit. |
|
415 | 415 | self.tempfiles = [] |
|
416 | 416 | |
|
417 | 417 | # Keep track of readline usage (later set by init_readline) |
|
418 | 418 | self.has_readline = False |
|
419 | 419 | |
|
420 | 420 | # template for logfile headers. It gets resolved at runtime by the |
|
421 | 421 | # logstart method. |
|
422 | 422 | self.loghead_tpl = \ |
|
423 | 423 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** |
|
424 | 424 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW |
|
425 | 425 | #log# opts = %s |
|
426 | 426 | #log# args = %s |
|
427 | 427 | #log# It is safe to make manual edits below here. |
|
428 | 428 | #log#----------------------------------------------------------------------- |
|
429 | 429 | """ |
|
430 | 430 | # for pushd/popd management |
|
431 | 431 | try: |
|
432 | 432 | self.home_dir = get_home_dir() |
|
433 | 433 | except HomeDirError,msg: |
|
434 | 434 | fatal(msg) |
|
435 | 435 | |
|
436 | 436 | self.dir_stack = [os.getcwd().replace(self.home_dir,'~')] |
|
437 | 437 | |
|
438 | 438 | # Functions to call the underlying shell. |
|
439 | 439 | |
|
440 | 440 | # utility to expand user variables via Itpl |
|
441 | 441 | self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'), |
|
442 | 442 | self.user_ns)) |
|
443 | 443 | # The first is similar to os.system, but it doesn't return a value, |
|
444 | 444 | # and it allows interpolation of variables in the user's namespace. |
|
445 | 445 | self.system = lambda cmd: shell(self.var_expand(cmd), |
|
446 | 446 | header='IPython system call: ', |
|
447 | 447 | verbose=self.rc.system_verbose) |
|
448 | 448 | # These are for getoutput and getoutputerror: |
|
449 | 449 | self.getoutput = lambda cmd: \ |
|
450 | 450 | getoutput(self.var_expand(cmd), |
|
451 | 451 | header='IPython system call: ', |
|
452 | 452 | verbose=self.rc.system_verbose) |
|
453 | 453 | self.getoutputerror = lambda cmd: \ |
|
454 | 454 | getoutputerror(str(ItplNS(cmd.replace('#','\#'), |
|
455 | 455 | self.user_ns)), |
|
456 | 456 | header='IPython system call: ', |
|
457 | 457 | verbose=self.rc.system_verbose) |
|
458 | 458 | |
|
459 | 459 | # RegExp for splitting line contents into pre-char//first |
|
460 | 460 | # word-method//rest. For clarity, each group in on one line. |
|
461 | 461 | |
|
462 | 462 | # WARNING: update the regexp if the above escapes are changed, as they |
|
463 | 463 | # are hardwired in. |
|
464 | 464 | |
|
465 | 465 | # Don't get carried away with trying to make the autocalling catch too |
|
466 | 466 | # much: it's better to be conservative rather than to trigger hidden |
|
467 | 467 | # evals() somewhere and end up causing side effects. |
|
468 | 468 | |
|
469 | 469 | self.line_split = re.compile(r'^([\s*,;/])' |
|
470 | 470 | r'([\?\w\.]+\w*\s*)' |
|
471 | 471 | r'(\(?.*$)') |
|
472 | 472 | |
|
473 | 473 | # Original re, keep around for a while in case changes break something |
|
474 | 474 | #self.line_split = re.compile(r'(^[\s*!\?%,/]?)' |
|
475 | 475 | # r'(\s*[\?\w\.]+\w*\s*)' |
|
476 | 476 | # r'(\(?.*$)') |
|
477 | 477 | |
|
478 | 478 | # RegExp to identify potential function names |
|
479 | 479 | self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$') |
|
480 | 480 | |
|
481 | 481 | # RegExp to exclude strings with this start from autocalling. In |
|
482 | 482 | # particular, all binary operators should be excluded, so that if foo |
|
483 | 483 | # is callable, foo OP bar doesn't become foo(OP bar), which is |
|
484 | 484 | # invalid. The characters '!=()' don't need to be checked for, as the |
|
485 | 485 | # _prefilter routine explicitely does so, to catch direct calls and |
|
486 | 486 | # rebindings of existing names. |
|
487 | 487 | |
|
488 | 488 | # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise |
|
489 | 489 | # it affects the rest of the group in square brackets. |
|
490 | 490 | self.re_exclude_auto = re.compile(r'^[<>,&^\|\*/\+-]' |
|
491 | 491 | '|^is |^not |^in |^and |^or ') |
|
492 | 492 | |
|
493 | 493 | # try to catch also methods for stuff in lists/tuples/dicts: off |
|
494 | 494 | # (experimental). For this to work, the line_split regexp would need |
|
495 | 495 | # to be modified so it wouldn't break things at '['. That line is |
|
496 | 496 | # nasty enough that I shouldn't change it until I can test it _well_. |
|
497 | 497 | #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$') |
|
498 | 498 | |
|
499 | 499 | # keep track of where we started running (mainly for crash post-mortem) |
|
500 | 500 | self.starting_dir = os.getcwd() |
|
501 | 501 | |
|
502 | 502 | # Various switches which can be set |
|
503 | 503 | self.CACHELENGTH = 5000 # this is cheap, it's just text |
|
504 | 504 | self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__ |
|
505 | 505 | self.banner2 = banner2 |
|
506 | 506 | |
|
507 | 507 | # TraceBack handlers: |
|
508 | 508 | |
|
509 | 509 | # Syntax error handler. |
|
510 | 510 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') |
|
511 | 511 | |
|
512 | 512 | # The interactive one is initialized with an offset, meaning we always |
|
513 | 513 | # want to remove the topmost item in the traceback, which is our own |
|
514 | 514 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
515 | 515 | self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain', |
|
516 | 516 | color_scheme='NoColor', |
|
517 | 517 | tb_offset = 1) |
|
518 | 518 | |
|
519 | 519 | # IPython itself shouldn't crash. This will produce a detailed |
|
520 | 520 | # post-mortem if it does. But we only install the crash handler for |
|
521 | 521 | # non-threaded shells, the threaded ones use a normal verbose reporter |
|
522 | 522 | # and lose the crash handler. This is because exceptions in the main |
|
523 | 523 | # thread (such as in GUI code) propagate directly to sys.excepthook, |
|
524 | 524 | # and there's no point in printing crash dumps for every user exception. |
|
525 | 525 | if self.isthreaded: |
|
526 | 526 | sys.excepthook = ultraTB.FormattedTB() |
|
527 | 527 | else: |
|
528 | 528 | from IPython import CrashHandler |
|
529 | 529 | sys.excepthook = CrashHandler.CrashHandler(self) |
|
530 | 530 | |
|
531 | 531 | # The instance will store a pointer to this, so that runtime code |
|
532 | 532 | # (such as magics) can access it. This is because during the |
|
533 | 533 | # read-eval loop, it gets temporarily overwritten (to deal with GUI |
|
534 | 534 | # frameworks). |
|
535 | 535 | self.sys_excepthook = sys.excepthook |
|
536 | 536 | |
|
537 | 537 | # and add any custom exception handlers the user may have specified |
|
538 | 538 | self.set_custom_exc(*custom_exceptions) |
|
539 | 539 | |
|
540 | # Object inspector | |
|
541 | self.inspector = OInspect.Inspector(OInspect.InspectColors, | |
|
542 | PyColorize.ANSICodeColors, | |
|
543 | 'NoColor') | |
|
544 | 540 | # indentation management |
|
545 | 541 | self.autoindent = False |
|
546 | 542 | self.indent_current_nsp = 0 |
|
547 | 543 | |
|
548 | 544 | # Make some aliases automatically |
|
549 | 545 | # Prepare list of shell aliases to auto-define |
|
550 | 546 | if os.name == 'posix': |
|
551 | 547 | auto_alias = ('mkdir mkdir', 'rmdir rmdir', |
|
552 | 548 | 'mv mv -i','rm rm -i','cp cp -i', |
|
553 | 549 | 'cat cat','less less','clear clear', |
|
554 | 550 | # a better ls |
|
555 | 551 | 'ls ls -F', |
|
556 | 552 | # long ls |
|
557 | 553 | 'll ls -lF', |
|
558 | 554 | # color ls |
|
559 | 555 | 'lc ls -F -o --color', |
|
560 | 556 | # ls normal files only |
|
561 | 557 | 'lf ls -F -o --color %l | grep ^-', |
|
562 | 558 | # ls symbolic links |
|
563 | 559 | 'lk ls -F -o --color %l | grep ^l', |
|
564 | 560 | # directories or links to directories, |
|
565 | 561 | 'ldir ls -F -o --color %l | grep /$', |
|
566 | 562 | # things which are executable |
|
567 | 563 | 'lx ls -F -o --color %l | grep ^-..x', |
|
568 | 564 | ) |
|
569 | 565 | elif os.name in ['nt','dos']: |
|
570 | 566 | auto_alias = ('dir dir /on', 'ls dir /on', |
|
571 | 567 | 'ddir dir /ad /on', 'ldir dir /ad /on', |
|
572 | 568 | 'mkdir mkdir','rmdir rmdir','echo echo', |
|
573 | 569 | 'ren ren','cls cls','copy copy') |
|
574 | 570 | else: |
|
575 | 571 | auto_alias = () |
|
576 | 572 | self.auto_alias = map(lambda s:s.split(None,1),auto_alias) |
|
577 | 573 | # Call the actual (public) initializer |
|
578 | 574 | self.init_auto_alias() |
|
579 | 575 | |
|
580 | 576 | # Produce a public API instance |
|
581 | 577 | self.api = IPython.ipapi.IPApi(self) |
|
582 | 578 | |
|
583 | 579 | # track which builtins we add, so we can clean up later |
|
584 | 580 | self.builtins_added = {} |
|
585 | 581 | # This method will add the necessary builtins for operation, but |
|
586 | 582 | # tracking what it did via the builtins_added dict. |
|
587 | 583 | self.add_builtins() |
|
588 | 584 | |
|
589 | 585 | # end __init__ |
|
590 | 586 | |
|
591 | 587 | def pre_config_initialization(self): |
|
592 | 588 | """Pre-configuration init method |
|
593 | 589 | |
|
594 | 590 | This is called before the configuration files are processed to |
|
595 | 591 | prepare the services the config files might need. |
|
596 | 592 | |
|
597 | 593 | self.rc already has reasonable default values at this point. |
|
598 | 594 | """ |
|
599 | 595 | rc = self.rc |
|
600 | 596 | |
|
601 | 597 | self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db") |
|
602 | 598 | |
|
603 | 599 | def post_config_initialization(self): |
|
604 | 600 | """Post configuration init method |
|
605 | 601 | |
|
606 | 602 | This is called after the configuration files have been processed to |
|
607 | 603 | 'finalize' the initialization.""" |
|
608 | 604 | |
|
609 | 605 | rc = self.rc |
|
606 | ||
|
607 | # Object inspector | |
|
608 | self.inspector = OInspect.Inspector(OInspect.InspectColors, | |
|
609 | PyColorize.ANSICodeColors, | |
|
610 | 'NoColor', | |
|
611 | rc.object_info_string_level) | |
|
610 | 612 | |
|
611 | 613 | # Load readline proper |
|
612 | 614 | if rc.readline: |
|
613 | 615 | self.init_readline() |
|
614 | 616 | |
|
615 | 617 | # local shortcut, this is used a LOT |
|
616 | 618 | self.log = self.logger.log |
|
617 | 619 | |
|
618 | 620 | # Initialize cache, set in/out prompts and printing system |
|
619 | 621 | self.outputcache = CachedOutput(self, |
|
620 | 622 | rc.cache_size, |
|
621 | 623 | rc.pprint, |
|
622 | 624 | input_sep = rc.separate_in, |
|
623 | 625 | output_sep = rc.separate_out, |
|
624 | 626 | output_sep2 = rc.separate_out2, |
|
625 | 627 | ps1 = rc.prompt_in1, |
|
626 | 628 | ps2 = rc.prompt_in2, |
|
627 | 629 | ps_out = rc.prompt_out, |
|
628 | 630 | pad_left = rc.prompts_pad_left) |
|
629 | 631 | |
|
630 | 632 | # user may have over-ridden the default print hook: |
|
631 | 633 | try: |
|
632 | 634 | self.outputcache.__class__.display = self.hooks.display |
|
633 | 635 | except AttributeError: |
|
634 | 636 | pass |
|
635 | 637 | |
|
636 | 638 | # I don't like assigning globally to sys, because it means when embedding |
|
637 | 639 | # instances, each embedded instance overrides the previous choice. But |
|
638 | 640 | # sys.displayhook seems to be called internally by exec, so I don't see a |
|
639 | 641 | # way around it. |
|
640 | 642 | sys.displayhook = self.outputcache |
|
641 | 643 | |
|
642 | 644 | # Set user colors (don't do it in the constructor above so that it |
|
643 | 645 | # doesn't crash if colors option is invalid) |
|
644 | 646 | self.magic_colors(rc.colors) |
|
645 | 647 | |
|
646 | 648 | # Set calling of pdb on exceptions |
|
647 | 649 | self.call_pdb = rc.pdb |
|
648 | 650 | |
|
649 | 651 | # Load user aliases |
|
650 | 652 | for alias in rc.alias: |
|
651 | 653 | self.magic_alias(alias) |
|
652 | 654 | self.hooks.late_startup_hook() |
|
653 | 655 | |
|
654 | 656 | for batchfile in [path(arg) for arg in self.rc.args |
|
655 | 657 | if arg.lower().endswith('.ipy')]: |
|
656 | 658 | if not batchfile.isfile(): |
|
657 | 659 | print "No such batch file:", batchfile |
|
658 | 660 | continue |
|
659 | 661 | self.api.runlines(batchfile.text()) |
|
660 | 662 | |
|
661 | 663 | def add_builtins(self): |
|
662 | 664 | """Store ipython references into the builtin namespace. |
|
663 | 665 | |
|
664 | 666 | Some parts of ipython operate via builtins injected here, which hold a |
|
665 | 667 | reference to IPython itself.""" |
|
666 | 668 | |
|
667 | 669 | # TODO: deprecate all except _ip; 'jobs' should be installed |
|
668 | 670 | # by an extension and the rest are under _ip, ipalias is redundant |
|
669 | 671 | builtins_new = dict(__IPYTHON__ = self, |
|
670 | 672 | ip_set_hook = self.set_hook, |
|
671 | 673 | jobs = self.jobs, |
|
672 | 674 | ipmagic = self.ipmagic, |
|
673 | 675 | ipalias = self.ipalias, |
|
674 | 676 | ipsystem = self.ipsystem, |
|
675 | 677 | _ip = self.api |
|
676 | 678 | ) |
|
677 | 679 | for biname,bival in builtins_new.items(): |
|
678 | 680 | try: |
|
679 | 681 | # store the orignal value so we can restore it |
|
680 | 682 | self.builtins_added[biname] = __builtin__.__dict__[biname] |
|
681 | 683 | except KeyError: |
|
682 | 684 | # or mark that it wasn't defined, and we'll just delete it at |
|
683 | 685 | # cleanup |
|
684 | 686 | self.builtins_added[biname] = Undefined |
|
685 | 687 | __builtin__.__dict__[biname] = bival |
|
686 | 688 | |
|
687 | 689 | # Keep in the builtins a flag for when IPython is active. We set it |
|
688 | 690 | # with setdefault so that multiple nested IPythons don't clobber one |
|
689 | 691 | # another. Each will increase its value by one upon being activated, |
|
690 | 692 | # which also gives us a way to determine the nesting level. |
|
691 | 693 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) |
|
692 | 694 | |
|
693 | 695 | def clean_builtins(self): |
|
694 | 696 | """Remove any builtins which might have been added by add_builtins, or |
|
695 | 697 | restore overwritten ones to their previous values.""" |
|
696 | 698 | for biname,bival in self.builtins_added.items(): |
|
697 | 699 | if bival is Undefined: |
|
698 | 700 | del __builtin__.__dict__[biname] |
|
699 | 701 | else: |
|
700 | 702 | __builtin__.__dict__[biname] = bival |
|
701 | 703 | self.builtins_added.clear() |
|
702 | 704 | |
|
703 | 705 | def set_hook(self,name,hook, priority = 50): |
|
704 | 706 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
705 | 707 | |
|
706 | 708 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
707 | 709 | adding your function to one of these hooks, you can modify IPython's |
|
708 | 710 | behavior to call at runtime your own routines.""" |
|
709 | 711 | |
|
710 | 712 | # At some point in the future, this should validate the hook before it |
|
711 | 713 | # accepts it. Probably at least check that the hook takes the number |
|
712 | 714 | # of args it's supposed to. |
|
713 | 715 | dp = getattr(self.hooks, name, None) |
|
714 | 716 | if name not in IPython.hooks.__all__: |
|
715 | 717 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ ) |
|
716 | 718 | if not dp: |
|
717 | 719 | dp = IPython.hooks.CommandChainDispatcher() |
|
718 | 720 | |
|
719 | 721 | f = new.instancemethod(hook,self,self.__class__) |
|
720 | 722 | try: |
|
721 | 723 | dp.add(f,priority) |
|
722 | 724 | except AttributeError: |
|
723 | 725 | # it was not commandchain, plain old func - replace |
|
724 | 726 | dp = f |
|
725 | 727 | |
|
726 | 728 | setattr(self.hooks,name, dp) |
|
727 | 729 | |
|
728 | 730 | |
|
729 | 731 | #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__)) |
|
730 | 732 | |
|
731 | 733 | def set_custom_exc(self,exc_tuple,handler): |
|
732 | 734 | """set_custom_exc(exc_tuple,handler) |
|
733 | 735 | |
|
734 | 736 | Set a custom exception handler, which will be called if any of the |
|
735 | 737 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
736 | 738 | runcode() method. |
|
737 | 739 | |
|
738 | 740 | Inputs: |
|
739 | 741 | |
|
740 | 742 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
741 | 743 | handler for. It is very important that you use a tuple, and NOT A |
|
742 | 744 | LIST here, because of the way Python's except statement works. If |
|
743 | 745 | you only want to trap a single exception, use a singleton tuple: |
|
744 | 746 | |
|
745 | 747 | exc_tuple == (MyCustomException,) |
|
746 | 748 | |
|
747 | 749 | - handler: this must be defined as a function with the following |
|
748 | 750 | basic interface: def my_handler(self,etype,value,tb). |
|
749 | 751 | |
|
750 | 752 | This will be made into an instance method (via new.instancemethod) |
|
751 | 753 | of IPython itself, and it will be called if any of the exceptions |
|
752 | 754 | listed in the exc_tuple are caught. If the handler is None, an |
|
753 | 755 | internal basic one is used, which just prints basic info. |
|
754 | 756 | |
|
755 | 757 | WARNING: by putting in your own exception handler into IPython's main |
|
756 | 758 | execution loop, you run a very good chance of nasty crashes. This |
|
757 | 759 | facility should only be used if you really know what you are doing.""" |
|
758 | 760 | |
|
759 | 761 | assert type(exc_tuple)==type(()) , \ |
|
760 | 762 | "The custom exceptions must be given AS A TUPLE." |
|
761 | 763 | |
|
762 | 764 | def dummy_handler(self,etype,value,tb): |
|
763 | 765 | print '*** Simple custom exception handler ***' |
|
764 | 766 | print 'Exception type :',etype |
|
765 | 767 | print 'Exception value:',value |
|
766 | 768 | print 'Traceback :',tb |
|
767 | 769 | print 'Source code :','\n'.join(self.buffer) |
|
768 | 770 | |
|
769 | 771 | if handler is None: handler = dummy_handler |
|
770 | 772 | |
|
771 | 773 | self.CustomTB = new.instancemethod(handler,self,self.__class__) |
|
772 | 774 | self.custom_exceptions = exc_tuple |
|
773 | 775 | |
|
774 | 776 | def set_custom_completer(self,completer,pos=0): |
|
775 | 777 | """set_custom_completer(completer,pos=0) |
|
776 | 778 | |
|
777 | 779 | Adds a new custom completer function. |
|
778 | 780 | |
|
779 | 781 | The position argument (defaults to 0) is the index in the completers |
|
780 | 782 | list where you want the completer to be inserted.""" |
|
781 | 783 | |
|
782 | 784 | newcomp = new.instancemethod(completer,self.Completer, |
|
783 | 785 | self.Completer.__class__) |
|
784 | 786 | self.Completer.matchers.insert(pos,newcomp) |
|
785 | 787 | |
|
786 | 788 | def _get_call_pdb(self): |
|
787 | 789 | return self._call_pdb |
|
788 | 790 | |
|
789 | 791 | def _set_call_pdb(self,val): |
|
790 | 792 | |
|
791 | 793 | if val not in (0,1,False,True): |
|
792 | 794 | raise ValueError,'new call_pdb value must be boolean' |
|
793 | 795 | |
|
794 | 796 | # store value in instance |
|
795 | 797 | self._call_pdb = val |
|
796 | 798 | |
|
797 | 799 | # notify the actual exception handlers |
|
798 | 800 | self.InteractiveTB.call_pdb = val |
|
799 | 801 | if self.isthreaded: |
|
800 | 802 | try: |
|
801 | 803 | self.sys_excepthook.call_pdb = val |
|
802 | 804 | except: |
|
803 | 805 | warn('Failed to activate pdb for threaded exception handler') |
|
804 | 806 | |
|
805 | 807 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
806 | 808 | 'Control auto-activation of pdb at exceptions') |
|
807 | 809 | |
|
808 | 810 | |
|
809 | 811 | # These special functions get installed in the builtin namespace, to |
|
810 | 812 | # provide programmatic (pure python) access to magics, aliases and system |
|
811 | 813 | # calls. This is important for logging, user scripting, and more. |
|
812 | 814 | |
|
813 | 815 | # We are basically exposing, via normal python functions, the three |
|
814 | 816 | # mechanisms in which ipython offers special call modes (magics for |
|
815 | 817 | # internal control, aliases for direct system access via pre-selected |
|
816 | 818 | # names, and !cmd for calling arbitrary system commands). |
|
817 | 819 | |
|
818 | 820 | def ipmagic(self,arg_s): |
|
819 | 821 | """Call a magic function by name. |
|
820 | 822 | |
|
821 | 823 | Input: a string containing the name of the magic function to call and any |
|
822 | 824 | additional arguments to be passed to the magic. |
|
823 | 825 | |
|
824 | 826 | ipmagic('name -opt foo bar') is equivalent to typing at the ipython |
|
825 | 827 | prompt: |
|
826 | 828 | |
|
827 | 829 | In[1]: %name -opt foo bar |
|
828 | 830 | |
|
829 | 831 | To call a magic without arguments, simply use ipmagic('name'). |
|
830 | 832 | |
|
831 | 833 | This provides a proper Python function to call IPython's magics in any |
|
832 | 834 | valid Python code you can type at the interpreter, including loops and |
|
833 | 835 | compound statements. It is added by IPython to the Python builtin |
|
834 | 836 | namespace upon initialization.""" |
|
835 | 837 | |
|
836 | 838 | args = arg_s.split(' ',1) |
|
837 | 839 | magic_name = args[0] |
|
838 | 840 | magic_name = magic_name.lstrip(self.ESC_MAGIC) |
|
839 | 841 | |
|
840 | 842 | try: |
|
841 | 843 | magic_args = args[1] |
|
842 | 844 | except IndexError: |
|
843 | 845 | magic_args = '' |
|
844 | 846 | fn = getattr(self,'magic_'+magic_name,None) |
|
845 | 847 | if fn is None: |
|
846 | 848 | error("Magic function `%s` not found." % magic_name) |
|
847 | 849 | else: |
|
848 | 850 | magic_args = self.var_expand(magic_args) |
|
849 | 851 | return fn(magic_args) |
|
850 | 852 | |
|
851 | 853 | def ipalias(self,arg_s): |
|
852 | 854 | """Call an alias by name. |
|
853 | 855 | |
|
854 | 856 | Input: a string containing the name of the alias to call and any |
|
855 | 857 | additional arguments to be passed to the magic. |
|
856 | 858 | |
|
857 | 859 | ipalias('name -opt foo bar') is equivalent to typing at the ipython |
|
858 | 860 | prompt: |
|
859 | 861 | |
|
860 | 862 | In[1]: name -opt foo bar |
|
861 | 863 | |
|
862 | 864 | To call an alias without arguments, simply use ipalias('name'). |
|
863 | 865 | |
|
864 | 866 | This provides a proper Python function to call IPython's aliases in any |
|
865 | 867 | valid Python code you can type at the interpreter, including loops and |
|
866 | 868 | compound statements. It is added by IPython to the Python builtin |
|
867 | 869 | namespace upon initialization.""" |
|
868 | 870 | |
|
869 | 871 | args = arg_s.split(' ',1) |
|
870 | 872 | alias_name = args[0] |
|
871 | 873 | try: |
|
872 | 874 | alias_args = args[1] |
|
873 | 875 | except IndexError: |
|
874 | 876 | alias_args = '' |
|
875 | 877 | if alias_name in self.alias_table: |
|
876 | 878 | self.call_alias(alias_name,alias_args) |
|
877 | 879 | else: |
|
878 | 880 | error("Alias `%s` not found." % alias_name) |
|
879 | 881 | |
|
880 | 882 | def ipsystem(self,arg_s): |
|
881 | 883 | """Make a system call, using IPython.""" |
|
882 | 884 | |
|
883 | 885 | self.system(arg_s) |
|
884 | 886 | |
|
885 | 887 | def complete(self,text): |
|
886 | 888 | """Return a sorted list of all possible completions on text. |
|
887 | 889 | |
|
888 | 890 | Inputs: |
|
889 | 891 | |
|
890 | 892 | - text: a string of text to be completed on. |
|
891 | 893 | |
|
892 | 894 | This is a wrapper around the completion mechanism, similar to what |
|
893 | 895 | readline does at the command line when the TAB key is hit. By |
|
894 | 896 | exposing it as a method, it can be used by other non-readline |
|
895 | 897 | environments (such as GUIs) for text completion. |
|
896 | 898 | |
|
897 | 899 | Simple usage example: |
|
898 | 900 | |
|
899 | 901 | In [1]: x = 'hello' |
|
900 | 902 | |
|
901 | 903 | In [2]: __IP.complete('x.l') |
|
902 | 904 | Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']""" |
|
903 | 905 | |
|
904 | 906 | complete = self.Completer.complete |
|
905 | 907 | state = 0 |
|
906 | 908 | # use a dict so we get unique keys, since ipyhton's multiple |
|
907 | 909 | # completers can return duplicates. |
|
908 | 910 | comps = {} |
|
909 | 911 | while True: |
|
910 | 912 | newcomp = complete(text,state) |
|
911 | 913 | if newcomp is None: |
|
912 | 914 | break |
|
913 | 915 | comps[newcomp] = 1 |
|
914 | 916 | state += 1 |
|
915 | 917 | outcomps = comps.keys() |
|
916 | 918 | outcomps.sort() |
|
917 | 919 | return outcomps |
|
918 | 920 | |
|
919 | 921 | def set_completer_frame(self, frame=None): |
|
920 | 922 | if frame: |
|
921 | 923 | self.Completer.namespace = frame.f_locals |
|
922 | 924 | self.Completer.global_namespace = frame.f_globals |
|
923 | 925 | else: |
|
924 | 926 | self.Completer.namespace = self.user_ns |
|
925 | 927 | self.Completer.global_namespace = self.user_global_ns |
|
926 | 928 | |
|
927 | 929 | def init_auto_alias(self): |
|
928 | 930 | """Define some aliases automatically. |
|
929 | 931 | |
|
930 | 932 | These are ALL parameter-less aliases""" |
|
931 | 933 | |
|
932 | 934 | for alias,cmd in self.auto_alias: |
|
933 | 935 | self.alias_table[alias] = (0,cmd) |
|
934 | 936 | |
|
935 | 937 | def alias_table_validate(self,verbose=0): |
|
936 | 938 | """Update information about the alias table. |
|
937 | 939 | |
|
938 | 940 | In particular, make sure no Python keywords/builtins are in it.""" |
|
939 | 941 | |
|
940 | 942 | no_alias = self.no_alias |
|
941 | 943 | for k in self.alias_table.keys(): |
|
942 | 944 | if k in no_alias: |
|
943 | 945 | del self.alias_table[k] |
|
944 | 946 | if verbose: |
|
945 | 947 | print ("Deleting alias <%s>, it's a Python " |
|
946 | 948 | "keyword or builtin." % k) |
|
947 | 949 | |
|
948 | 950 | def set_autoindent(self,value=None): |
|
949 | 951 | """Set the autoindent flag, checking for readline support. |
|
950 | 952 | |
|
951 | 953 | If called with no arguments, it acts as a toggle.""" |
|
952 | 954 | |
|
953 | 955 | if not self.has_readline: |
|
954 | 956 | if os.name == 'posix': |
|
955 | 957 | warn("The auto-indent feature requires the readline library") |
|
956 | 958 | self.autoindent = 0 |
|
957 | 959 | return |
|
958 | 960 | if value is None: |
|
959 | 961 | self.autoindent = not self.autoindent |
|
960 | 962 | else: |
|
961 | 963 | self.autoindent = value |
|
962 | 964 | |
|
963 | 965 | def rc_set_toggle(self,rc_field,value=None): |
|
964 | 966 | """Set or toggle a field in IPython's rc config. structure. |
|
965 | 967 | |
|
966 | 968 | If called with no arguments, it acts as a toggle. |
|
967 | 969 | |
|
968 | 970 | If called with a non-existent field, the resulting AttributeError |
|
969 | 971 | exception will propagate out.""" |
|
970 | 972 | |
|
971 | 973 | rc_val = getattr(self.rc,rc_field) |
|
972 | 974 | if value is None: |
|
973 | 975 | value = not rc_val |
|
974 | 976 | setattr(self.rc,rc_field,value) |
|
975 | 977 | |
|
976 | 978 | def user_setup(self,ipythondir,rc_suffix,mode='install'): |
|
977 | 979 | """Install the user configuration directory. |
|
978 | 980 | |
|
979 | 981 | Can be called when running for the first time or to upgrade the user's |
|
980 | 982 | .ipython/ directory with the mode parameter. Valid modes are 'install' |
|
981 | 983 | and 'upgrade'.""" |
|
982 | 984 | |
|
983 | 985 | def wait(): |
|
984 | 986 | try: |
|
985 | 987 | raw_input("Please press <RETURN> to start IPython.") |
|
986 | 988 | except EOFError: |
|
987 | 989 | print >> Term.cout |
|
988 | 990 | print '*'*70 |
|
989 | 991 | |
|
990 | 992 | cwd = os.getcwd() # remember where we started |
|
991 | 993 | glb = glob.glob |
|
992 | 994 | print '*'*70 |
|
993 | 995 | if mode == 'install': |
|
994 | 996 | print \ |
|
995 | 997 | """Welcome to IPython. I will try to create a personal configuration directory |
|
996 | 998 | where you can customize many aspects of IPython's functionality in:\n""" |
|
997 | 999 | else: |
|
998 | 1000 | print 'I am going to upgrade your configuration in:' |
|
999 | 1001 | |
|
1000 | 1002 | print ipythondir |
|
1001 | 1003 | |
|
1002 | 1004 | rcdirend = os.path.join('IPython','UserConfig') |
|
1003 | 1005 | cfg = lambda d: os.path.join(d,rcdirend) |
|
1004 | 1006 | try: |
|
1005 | 1007 | rcdir = filter(os.path.isdir,map(cfg,sys.path))[0] |
|
1006 | 1008 | except IOError: |
|
1007 | 1009 | warning = """ |
|
1008 | 1010 | Installation error. IPython's directory was not found. |
|
1009 | 1011 | |
|
1010 | 1012 | Check the following: |
|
1011 | 1013 | |
|
1012 | 1014 | The ipython/IPython directory should be in a directory belonging to your |
|
1013 | 1015 | PYTHONPATH environment variable (that is, it should be in a directory |
|
1014 | 1016 | belonging to sys.path). You can copy it explicitly there or just link to it. |
|
1015 | 1017 | |
|
1016 | 1018 | IPython will proceed with builtin defaults. |
|
1017 | 1019 | """ |
|
1018 | 1020 | warn(warning) |
|
1019 | 1021 | wait() |
|
1020 | 1022 | return |
|
1021 | 1023 | |
|
1022 | 1024 | if mode == 'install': |
|
1023 | 1025 | try: |
|
1024 | 1026 | shutil.copytree(rcdir,ipythondir) |
|
1025 | 1027 | os.chdir(ipythondir) |
|
1026 | 1028 | rc_files = glb("ipythonrc*") |
|
1027 | 1029 | for rc_file in rc_files: |
|
1028 | 1030 | os.rename(rc_file,rc_file+rc_suffix) |
|
1029 | 1031 | except: |
|
1030 | 1032 | warning = """ |
|
1031 | 1033 | |
|
1032 | 1034 | There was a problem with the installation: |
|
1033 | 1035 | %s |
|
1034 | 1036 | Try to correct it or contact the developers if you think it's a bug. |
|
1035 | 1037 | IPython will proceed with builtin defaults.""" % sys.exc_info()[1] |
|
1036 | 1038 | warn(warning) |
|
1037 | 1039 | wait() |
|
1038 | 1040 | return |
|
1039 | 1041 | |
|
1040 | 1042 | elif mode == 'upgrade': |
|
1041 | 1043 | try: |
|
1042 | 1044 | os.chdir(ipythondir) |
|
1043 | 1045 | except: |
|
1044 | 1046 | print """ |
|
1045 | 1047 | Can not upgrade: changing to directory %s failed. Details: |
|
1046 | 1048 | %s |
|
1047 | 1049 | """ % (ipythondir,sys.exc_info()[1]) |
|
1048 | 1050 | wait() |
|
1049 | 1051 | return |
|
1050 | 1052 | else: |
|
1051 | 1053 | sources = glb(os.path.join(rcdir,'[A-Za-z]*')) |
|
1052 | 1054 | for new_full_path in sources: |
|
1053 | 1055 | new_filename = os.path.basename(new_full_path) |
|
1054 | 1056 | if new_filename.startswith('ipythonrc'): |
|
1055 | 1057 | new_filename = new_filename + rc_suffix |
|
1056 | 1058 | # The config directory should only contain files, skip any |
|
1057 | 1059 | # directories which may be there (like CVS) |
|
1058 | 1060 | if os.path.isdir(new_full_path): |
|
1059 | 1061 | continue |
|
1060 | 1062 | if os.path.exists(new_filename): |
|
1061 | 1063 | old_file = new_filename+'.old' |
|
1062 | 1064 | if os.path.exists(old_file): |
|
1063 | 1065 | os.remove(old_file) |
|
1064 | 1066 | os.rename(new_filename,old_file) |
|
1065 | 1067 | shutil.copy(new_full_path,new_filename) |
|
1066 | 1068 | else: |
|
1067 | 1069 | raise ValueError,'unrecognized mode for install:',`mode` |
|
1068 | 1070 | |
|
1069 | 1071 | # Fix line-endings to those native to each platform in the config |
|
1070 | 1072 | # directory. |
|
1071 | 1073 | try: |
|
1072 | 1074 | os.chdir(ipythondir) |
|
1073 | 1075 | except: |
|
1074 | 1076 | print """ |
|
1075 | 1077 | Problem: changing to directory %s failed. |
|
1076 | 1078 | Details: |
|
1077 | 1079 | %s |
|
1078 | 1080 | |
|
1079 | 1081 | Some configuration files may have incorrect line endings. This should not |
|
1080 | 1082 | cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) |
|
1081 | 1083 | wait() |
|
1082 | 1084 | else: |
|
1083 | 1085 | for fname in glb('ipythonrc*'): |
|
1084 | 1086 | try: |
|
1085 | 1087 | native_line_ends(fname,backup=0) |
|
1086 | 1088 | except IOError: |
|
1087 | 1089 | pass |
|
1088 | 1090 | |
|
1089 | 1091 | if mode == 'install': |
|
1090 | 1092 | print """ |
|
1091 | 1093 | Successful installation! |
|
1092 | 1094 | |
|
1093 | 1095 | Please read the sections 'Initial Configuration' and 'Quick Tips' in the |
|
1094 | 1096 | IPython manual (there are both HTML and PDF versions supplied with the |
|
1095 | 1097 | distribution) to make sure that your system environment is properly configured |
|
1096 | 1098 | to take advantage of IPython's features. |
|
1097 | 1099 | |
|
1098 | 1100 | Important note: the configuration system has changed! The old system is |
|
1099 | 1101 | still in place, but its setting may be partly overridden by the settings in |
|
1100 | 1102 | "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file |
|
1101 | 1103 | if some of the new settings bother you. |
|
1102 | 1104 | |
|
1103 | 1105 | """ |
|
1104 | 1106 | else: |
|
1105 | 1107 | print """ |
|
1106 | 1108 | Successful upgrade! |
|
1107 | 1109 | |
|
1108 | 1110 | All files in your directory: |
|
1109 | 1111 | %(ipythondir)s |
|
1110 | 1112 | which would have been overwritten by the upgrade were backed up with a .old |
|
1111 | 1113 | extension. If you had made particular customizations in those files you may |
|
1112 | 1114 | want to merge them back into the new files.""" % locals() |
|
1113 | 1115 | wait() |
|
1114 | 1116 | os.chdir(cwd) |
|
1115 | 1117 | # end user_setup() |
|
1116 | 1118 | |
|
1117 | 1119 | def atexit_operations(self): |
|
1118 | 1120 | """This will be executed at the time of exit. |
|
1119 | 1121 | |
|
1120 | 1122 | Saving of persistent data should be performed here. """ |
|
1121 | 1123 | |
|
1122 | 1124 | #print '*** IPython exit cleanup ***' # dbg |
|
1123 | 1125 | # input history |
|
1124 | 1126 | self.savehist() |
|
1125 | 1127 | |
|
1126 | 1128 | # Cleanup all tempfiles left around |
|
1127 | 1129 | for tfile in self.tempfiles: |
|
1128 | 1130 | try: |
|
1129 | 1131 | os.unlink(tfile) |
|
1130 | 1132 | except OSError: |
|
1131 | 1133 | pass |
|
1132 | 1134 | |
|
1133 | 1135 | # save the "persistent data" catch-all dictionary |
|
1134 | 1136 | self.hooks.shutdown_hook() |
|
1135 | 1137 | |
|
1136 | 1138 | def savehist(self): |
|
1137 | 1139 | """Save input history to a file (via readline library).""" |
|
1138 | 1140 | try: |
|
1139 | 1141 | self.readline.write_history_file(self.histfile) |
|
1140 | 1142 | except: |
|
1141 | 1143 | print 'Unable to save IPython command history to file: ' + \ |
|
1142 | 1144 | `self.histfile` |
|
1143 | 1145 | |
|
1144 | 1146 | def pre_readline(self): |
|
1145 | 1147 | """readline hook to be used at the start of each line. |
|
1146 | 1148 | |
|
1147 | 1149 | Currently it handles auto-indent only.""" |
|
1148 | 1150 | |
|
1149 | 1151 | #debugx('self.indent_current_nsp','pre_readline:') |
|
1150 | 1152 | self.readline.insert_text(self.indent_current_str()) |
|
1151 | 1153 | |
|
1152 | 1154 | def init_readline(self): |
|
1153 | 1155 | """Command history completion/saving/reloading.""" |
|
1154 | 1156 | |
|
1155 | 1157 | import IPython.rlineimpl as readline |
|
1156 | 1158 | if not readline.have_readline: |
|
1157 | 1159 | self.has_readline = 0 |
|
1158 | 1160 | self.readline = None |
|
1159 | 1161 | # no point in bugging windows users with this every time: |
|
1160 | 1162 | warn('Readline services not available on this platform.') |
|
1161 | 1163 | else: |
|
1162 | 1164 | sys.modules['readline'] = readline |
|
1163 | 1165 | import atexit |
|
1164 | 1166 | from IPython.completer import IPCompleter |
|
1165 | 1167 | self.Completer = IPCompleter(self, |
|
1166 | 1168 | self.user_ns, |
|
1167 | 1169 | self.user_global_ns, |
|
1168 | 1170 | self.rc.readline_omit__names, |
|
1169 | 1171 | self.alias_table) |
|
1170 | 1172 | |
|
1171 | 1173 | # Platform-specific configuration |
|
1172 | 1174 | if os.name == 'nt': |
|
1173 | 1175 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1174 | 1176 | else: |
|
1175 | 1177 | self.readline_startup_hook = readline.set_startup_hook |
|
1176 | 1178 | |
|
1177 | 1179 | # Load user's initrc file (readline config) |
|
1178 | 1180 | inputrc_name = os.environ.get('INPUTRC') |
|
1179 | 1181 | if inputrc_name is None: |
|
1180 | 1182 | home_dir = get_home_dir() |
|
1181 | 1183 | if home_dir is not None: |
|
1182 | 1184 | inputrc_name = os.path.join(home_dir,'.inputrc') |
|
1183 | 1185 | if os.path.isfile(inputrc_name): |
|
1184 | 1186 | try: |
|
1185 | 1187 | readline.read_init_file(inputrc_name) |
|
1186 | 1188 | except: |
|
1187 | 1189 | warn('Problems reading readline initialization file <%s>' |
|
1188 | 1190 | % inputrc_name) |
|
1189 | 1191 | |
|
1190 | 1192 | self.has_readline = 1 |
|
1191 | 1193 | self.readline = readline |
|
1192 | 1194 | # save this in sys so embedded copies can restore it properly |
|
1193 | 1195 | sys.ipcompleter = self.Completer.complete |
|
1194 | 1196 | readline.set_completer(self.Completer.complete) |
|
1195 | 1197 | |
|
1196 | 1198 | # Configure readline according to user's prefs |
|
1197 | 1199 | for rlcommand in self.rc.readline_parse_and_bind: |
|
1198 | 1200 | readline.parse_and_bind(rlcommand) |
|
1199 | 1201 | |
|
1200 | 1202 | # remove some chars from the delimiters list |
|
1201 | 1203 | delims = readline.get_completer_delims() |
|
1202 | 1204 | delims = delims.translate(string._idmap, |
|
1203 | 1205 | self.rc.readline_remove_delims) |
|
1204 | 1206 | readline.set_completer_delims(delims) |
|
1205 | 1207 | # otherwise we end up with a monster history after a while: |
|
1206 | 1208 | readline.set_history_length(1000) |
|
1207 | 1209 | try: |
|
1208 | 1210 | #print '*** Reading readline history' # dbg |
|
1209 | 1211 | readline.read_history_file(self.histfile) |
|
1210 | 1212 | except IOError: |
|
1211 | 1213 | pass # It doesn't exist yet. |
|
1212 | 1214 | |
|
1213 | 1215 | atexit.register(self.atexit_operations) |
|
1214 | 1216 | del atexit |
|
1215 | 1217 | |
|
1216 | 1218 | # Configure auto-indent for all platforms |
|
1217 | 1219 | self.set_autoindent(self.rc.autoindent) |
|
1218 | 1220 | |
|
1219 | 1221 | def _should_recompile(self,e): |
|
1220 | 1222 | """Utility routine for edit_syntax_error""" |
|
1221 | 1223 | |
|
1222 | 1224 | if e.filename in ('<ipython console>','<input>','<string>', |
|
1223 | 1225 | '<console>','<BackgroundJob compilation>', |
|
1224 | 1226 | None): |
|
1225 | 1227 | |
|
1226 | 1228 | return False |
|
1227 | 1229 | try: |
|
1228 | 1230 | if (self.rc.autoedit_syntax and |
|
1229 | 1231 | not ask_yes_no('Return to editor to correct syntax error? ' |
|
1230 | 1232 | '[Y/n] ','y')): |
|
1231 | 1233 | return False |
|
1232 | 1234 | except EOFError: |
|
1233 | 1235 | return False |
|
1234 | 1236 | |
|
1235 | 1237 | def int0(x): |
|
1236 | 1238 | try: |
|
1237 | 1239 | return int(x) |
|
1238 | 1240 | except TypeError: |
|
1239 | 1241 | return 0 |
|
1240 | 1242 | # always pass integer line and offset values to editor hook |
|
1241 | 1243 | self.hooks.fix_error_editor(e.filename, |
|
1242 | 1244 | int0(e.lineno),int0(e.offset),e.msg) |
|
1243 | 1245 | return True |
|
1244 | 1246 | |
|
1245 | 1247 | def edit_syntax_error(self): |
|
1246 | 1248 | """The bottom half of the syntax error handler called in the main loop. |
|
1247 | 1249 | |
|
1248 | 1250 | Loop until syntax error is fixed or user cancels. |
|
1249 | 1251 | """ |
|
1250 | 1252 | |
|
1251 | 1253 | while self.SyntaxTB.last_syntax_error: |
|
1252 | 1254 | # copy and clear last_syntax_error |
|
1253 | 1255 | err = self.SyntaxTB.clear_err_state() |
|
1254 | 1256 | if not self._should_recompile(err): |
|
1255 | 1257 | return |
|
1256 | 1258 | try: |
|
1257 | 1259 | # may set last_syntax_error again if a SyntaxError is raised |
|
1258 | 1260 | self.safe_execfile(err.filename,self.shell.user_ns) |
|
1259 | 1261 | except: |
|
1260 | 1262 | self.showtraceback() |
|
1261 | 1263 | else: |
|
1262 | 1264 | try: |
|
1263 | 1265 | f = file(err.filename) |
|
1264 | 1266 | try: |
|
1265 | 1267 | sys.displayhook(f.read()) |
|
1266 | 1268 | finally: |
|
1267 | 1269 | f.close() |
|
1268 | 1270 | except: |
|
1269 | 1271 | self.showtraceback() |
|
1270 | 1272 | |
|
1271 | 1273 | def showsyntaxerror(self, filename=None): |
|
1272 | 1274 | """Display the syntax error that just occurred. |
|
1273 | 1275 | |
|
1274 | 1276 | This doesn't display a stack trace because there isn't one. |
|
1275 | 1277 | |
|
1276 | 1278 | If a filename is given, it is stuffed in the exception instead |
|
1277 | 1279 | of what was there before (because Python's parser always uses |
|
1278 | 1280 | "<string>" when reading from a string). |
|
1279 | 1281 | """ |
|
1280 | 1282 | etype, value, last_traceback = sys.exc_info() |
|
1281 | 1283 | |
|
1282 | 1284 | # See note about these variables in showtraceback() below |
|
1283 | 1285 | sys.last_type = etype |
|
1284 | 1286 | sys.last_value = value |
|
1285 | 1287 | sys.last_traceback = last_traceback |
|
1286 | 1288 | |
|
1287 | 1289 | if filename and etype is SyntaxError: |
|
1288 | 1290 | # Work hard to stuff the correct filename in the exception |
|
1289 | 1291 | try: |
|
1290 | 1292 | msg, (dummy_filename, lineno, offset, line) = value |
|
1291 | 1293 | except: |
|
1292 | 1294 | # Not the format we expect; leave it alone |
|
1293 | 1295 | pass |
|
1294 | 1296 | else: |
|
1295 | 1297 | # Stuff in the right filename |
|
1296 | 1298 | try: |
|
1297 | 1299 | # Assume SyntaxError is a class exception |
|
1298 | 1300 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1299 | 1301 | except: |
|
1300 | 1302 | # If that failed, assume SyntaxError is a string |
|
1301 | 1303 | value = msg, (filename, lineno, offset, line) |
|
1302 | 1304 | self.SyntaxTB(etype,value,[]) |
|
1303 | 1305 | |
|
1304 | 1306 | def debugger(self): |
|
1305 | 1307 | """Call the pdb debugger.""" |
|
1306 | 1308 | |
|
1307 | 1309 | if not self.rc.pdb: |
|
1308 | 1310 | return |
|
1309 | 1311 | pdb.pm() |
|
1310 | 1312 | |
|
1311 | 1313 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None): |
|
1312 | 1314 | """Display the exception that just occurred. |
|
1313 | 1315 | |
|
1314 | 1316 | If nothing is known about the exception, this is the method which |
|
1315 | 1317 | should be used throughout the code for presenting user tracebacks, |
|
1316 | 1318 | rather than directly invoking the InteractiveTB object. |
|
1317 | 1319 | |
|
1318 | 1320 | A specific showsyntaxerror() also exists, but this method can take |
|
1319 | 1321 | care of calling it if needed, so unless you are explicitly catching a |
|
1320 | 1322 | SyntaxError exception, don't try to analyze the stack manually and |
|
1321 | 1323 | simply call this method.""" |
|
1322 | 1324 | |
|
1323 | 1325 | # Though this won't be called by syntax errors in the input line, |
|
1324 | 1326 | # there may be SyntaxError cases whith imported code. |
|
1325 | 1327 | if exc_tuple is None: |
|
1326 | 1328 | etype, value, tb = sys.exc_info() |
|
1327 | 1329 | else: |
|
1328 | 1330 | etype, value, tb = exc_tuple |
|
1329 | 1331 | if etype is SyntaxError: |
|
1330 | 1332 | self.showsyntaxerror(filename) |
|
1331 | 1333 | else: |
|
1332 | 1334 | # WARNING: these variables are somewhat deprecated and not |
|
1333 | 1335 | # necessarily safe to use in a threaded environment, but tools |
|
1334 | 1336 | # like pdb depend on their existence, so let's set them. If we |
|
1335 | 1337 | # find problems in the field, we'll need to revisit their use. |
|
1336 | 1338 | sys.last_type = etype |
|
1337 | 1339 | sys.last_value = value |
|
1338 | 1340 | sys.last_traceback = tb |
|
1339 | 1341 | |
|
1340 | 1342 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) |
|
1341 | 1343 | if self.InteractiveTB.call_pdb and self.has_readline: |
|
1342 | 1344 | # pdb mucks up readline, fix it back |
|
1343 | 1345 | self.readline.set_completer(self.Completer.complete) |
|
1344 | 1346 | |
|
1345 | 1347 | def mainloop(self,banner=None): |
|
1346 | 1348 | """Creates the local namespace and starts the mainloop. |
|
1347 | 1349 | |
|
1348 | 1350 | If an optional banner argument is given, it will override the |
|
1349 | 1351 | internally created default banner.""" |
|
1350 | 1352 | |
|
1351 | 1353 | if self.rc.c: # Emulate Python's -c option |
|
1352 | 1354 | self.exec_init_cmd() |
|
1353 | 1355 | if banner is None: |
|
1354 | 1356 | if not self.rc.banner: |
|
1355 | 1357 | banner = '' |
|
1356 | 1358 | # banner is string? Use it directly! |
|
1357 | 1359 | elif isinstance(self.rc.banner,basestring): |
|
1358 | 1360 | banner = self.rc.banner |
|
1359 | 1361 | else: |
|
1360 | 1362 | banner = self.BANNER+self.banner2 |
|
1361 | 1363 | |
|
1362 | 1364 | self.interact(banner) |
|
1363 | 1365 | |
|
1364 | 1366 | def exec_init_cmd(self): |
|
1365 | 1367 | """Execute a command given at the command line. |
|
1366 | 1368 | |
|
1367 | 1369 | This emulates Python's -c option.""" |
|
1368 | 1370 | |
|
1369 | 1371 | #sys.argv = ['-c'] |
|
1370 | 1372 | self.push(self.rc.c) |
|
1371 | 1373 | |
|
1372 | 1374 | def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0): |
|
1373 | 1375 | """Embeds IPython into a running python program. |
|
1374 | 1376 | |
|
1375 | 1377 | Input: |
|
1376 | 1378 | |
|
1377 | 1379 | - header: An optional header message can be specified. |
|
1378 | 1380 | |
|
1379 | 1381 | - local_ns, global_ns: working namespaces. If given as None, the |
|
1380 | 1382 | IPython-initialized one is updated with __main__.__dict__, so that |
|
1381 | 1383 | program variables become visible but user-specific configuration |
|
1382 | 1384 | remains possible. |
|
1383 | 1385 | |
|
1384 | 1386 | - stack_depth: specifies how many levels in the stack to go to |
|
1385 | 1387 | looking for namespaces (when local_ns and global_ns are None). This |
|
1386 | 1388 | allows an intermediate caller to make sure that this function gets |
|
1387 | 1389 | the namespace from the intended level in the stack. By default (0) |
|
1388 | 1390 | it will get its locals and globals from the immediate caller. |
|
1389 | 1391 | |
|
1390 | 1392 | Warning: it's possible to use this in a program which is being run by |
|
1391 | 1393 | IPython itself (via %run), but some funny things will happen (a few |
|
1392 | 1394 | globals get overwritten). In the future this will be cleaned up, as |
|
1393 | 1395 | there is no fundamental reason why it can't work perfectly.""" |
|
1394 | 1396 | |
|
1395 | 1397 | # Get locals and globals from caller |
|
1396 | 1398 | if local_ns is None or global_ns is None: |
|
1397 | 1399 | call_frame = sys._getframe(stack_depth).f_back |
|
1398 | 1400 | |
|
1399 | 1401 | if local_ns is None: |
|
1400 | 1402 | local_ns = call_frame.f_locals |
|
1401 | 1403 | if global_ns is None: |
|
1402 | 1404 | global_ns = call_frame.f_globals |
|
1403 | 1405 | |
|
1404 | 1406 | # Update namespaces and fire up interpreter |
|
1405 | 1407 | |
|
1406 | 1408 | # The global one is easy, we can just throw it in |
|
1407 | 1409 | self.user_global_ns = global_ns |
|
1408 | 1410 | |
|
1409 | 1411 | # but the user/local one is tricky: ipython needs it to store internal |
|
1410 | 1412 | # data, but we also need the locals. We'll copy locals in the user |
|
1411 | 1413 | # one, but will track what got copied so we can delete them at exit. |
|
1412 | 1414 | # This is so that a later embedded call doesn't see locals from a |
|
1413 | 1415 | # previous call (which most likely existed in a separate scope). |
|
1414 | 1416 | local_varnames = local_ns.keys() |
|
1415 | 1417 | self.user_ns.update(local_ns) |
|
1416 | 1418 | |
|
1417 | 1419 | # Patch for global embedding to make sure that things don't overwrite |
|
1418 | 1420 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> |
|
1419 | 1421 | # FIXME. Test this a bit more carefully (the if.. is new) |
|
1420 | 1422 | if local_ns is None and global_ns is None: |
|
1421 | 1423 | self.user_global_ns.update(__main__.__dict__) |
|
1422 | 1424 | |
|
1423 | 1425 | # make sure the tab-completer has the correct frame information, so it |
|
1424 | 1426 | # actually completes using the frame's locals/globals |
|
1425 | 1427 | self.set_completer_frame() |
|
1426 | 1428 | |
|
1427 | 1429 | # before activating the interactive mode, we need to make sure that |
|
1428 | 1430 | # all names in the builtin namespace needed by ipython point to |
|
1429 | 1431 | # ourselves, and not to other instances. |
|
1430 | 1432 | self.add_builtins() |
|
1431 | 1433 | |
|
1432 | 1434 | self.interact(header) |
|
1433 | 1435 | |
|
1434 | 1436 | # now, purge out the user namespace from anything we might have added |
|
1435 | 1437 | # from the caller's local namespace |
|
1436 | 1438 | delvar = self.user_ns.pop |
|
1437 | 1439 | for var in local_varnames: |
|
1438 | 1440 | delvar(var,None) |
|
1439 | 1441 | # and clean builtins we may have overridden |
|
1440 | 1442 | self.clean_builtins() |
|
1441 | 1443 | |
|
1442 | 1444 | def interact(self, banner=None): |
|
1443 | 1445 | """Closely emulate the interactive Python console. |
|
1444 | 1446 | |
|
1445 | 1447 | The optional banner argument specify the banner to print |
|
1446 | 1448 | before the first interaction; by default it prints a banner |
|
1447 | 1449 | similar to the one printed by the real Python interpreter, |
|
1448 | 1450 | followed by the current class name in parentheses (so as not |
|
1449 | 1451 | to confuse this with the real interpreter -- since it's so |
|
1450 | 1452 | close!). |
|
1451 | 1453 | |
|
1452 | 1454 | """ |
|
1453 | 1455 | cprt = 'Type "copyright", "credits" or "license" for more information.' |
|
1454 | 1456 | if banner is None: |
|
1455 | 1457 | self.write("Python %s on %s\n%s\n(%s)\n" % |
|
1456 | 1458 | (sys.version, sys.platform, cprt, |
|
1457 | 1459 | self.__class__.__name__)) |
|
1458 | 1460 | else: |
|
1459 | 1461 | self.write(banner) |
|
1460 | 1462 | |
|
1461 | 1463 | more = 0 |
|
1462 | 1464 | |
|
1463 | 1465 | # Mark activity in the builtins |
|
1464 | 1466 | __builtin__.__dict__['__IPYTHON__active'] += 1 |
|
1465 | 1467 | |
|
1466 | 1468 | # exit_now is set by a call to %Exit or %Quit |
|
1467 | 1469 | self.exit_now = False |
|
1468 | 1470 | while not self.exit_now: |
|
1469 | 1471 | if more: |
|
1470 | 1472 | prompt = self.outputcache.prompt2 |
|
1471 | 1473 | if self.autoindent: |
|
1472 | 1474 | self.readline_startup_hook(self.pre_readline) |
|
1473 | 1475 | else: |
|
1474 | 1476 | prompt = self.outputcache.prompt1 |
|
1475 | 1477 | try: |
|
1476 | 1478 | line = self.raw_input(prompt,more) |
|
1477 | 1479 | if self.autoindent: |
|
1478 | 1480 | self.readline_startup_hook(None) |
|
1479 | 1481 | except KeyboardInterrupt: |
|
1480 | 1482 | self.write('\nKeyboardInterrupt\n') |
|
1481 | 1483 | self.resetbuffer() |
|
1482 | 1484 | # keep cache in sync with the prompt counter: |
|
1483 | 1485 | self.outputcache.prompt_count -= 1 |
|
1484 | 1486 | |
|
1485 | 1487 | if self.autoindent: |
|
1486 | 1488 | self.indent_current_nsp = 0 |
|
1487 | 1489 | more = 0 |
|
1488 | 1490 | except EOFError: |
|
1489 | 1491 | if self.autoindent: |
|
1490 | 1492 | self.readline_startup_hook(None) |
|
1491 | 1493 | self.write('\n') |
|
1492 | 1494 | self.exit() |
|
1493 | 1495 | except bdb.BdbQuit: |
|
1494 | 1496 | warn('The Python debugger has exited with a BdbQuit exception.\n' |
|
1495 | 1497 | 'Because of how pdb handles the stack, it is impossible\n' |
|
1496 | 1498 | 'for IPython to properly format this particular exception.\n' |
|
1497 | 1499 | 'IPython will resume normal operation.') |
|
1498 | 1500 | except: |
|
1499 | 1501 | # exceptions here are VERY RARE, but they can be triggered |
|
1500 | 1502 | # asynchronously by signal handlers, for example. |
|
1501 | 1503 | self.showtraceback() |
|
1502 | 1504 | else: |
|
1503 | 1505 | more = self.push(line) |
|
1504 | 1506 | if (self.SyntaxTB.last_syntax_error and |
|
1505 | 1507 | self.rc.autoedit_syntax): |
|
1506 | 1508 | self.edit_syntax_error() |
|
1507 | 1509 | |
|
1508 | 1510 | # We are off again... |
|
1509 | 1511 | __builtin__.__dict__['__IPYTHON__active'] -= 1 |
|
1510 | 1512 | |
|
1511 | 1513 | def excepthook(self, etype, value, tb): |
|
1512 | 1514 | """One more defense for GUI apps that call sys.excepthook. |
|
1513 | 1515 | |
|
1514 | 1516 | GUI frameworks like wxPython trap exceptions and call |
|
1515 | 1517 | sys.excepthook themselves. I guess this is a feature that |
|
1516 | 1518 | enables them to keep running after exceptions that would |
|
1517 | 1519 | otherwise kill their mainloop. This is a bother for IPython |
|
1518 | 1520 | which excepts to catch all of the program exceptions with a try: |
|
1519 | 1521 | except: statement. |
|
1520 | 1522 | |
|
1521 | 1523 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1522 | 1524 | any app directly invokes sys.excepthook, it will look to the user like |
|
1523 | 1525 | IPython crashed. In order to work around this, we can disable the |
|
1524 | 1526 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1525 | 1527 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1526 | 1528 | call sys.excepthook will generate a regular-looking exception from |
|
1527 | 1529 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1528 | 1530 | crashes. |
|
1529 | 1531 | |
|
1530 | 1532 | This hook should be used sparingly, only in places which are not likely |
|
1531 | 1533 | to be true IPython errors. |
|
1532 | 1534 | """ |
|
1533 | 1535 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1534 | 1536 | |
|
1535 | 1537 | def transform_alias(self, alias,rest=''): |
|
1536 | 1538 | """ Transform alias to system command string |
|
1537 | 1539 | |
|
1538 | 1540 | """ |
|
1539 | 1541 | nargs,cmd = self.alias_table[alias] |
|
1540 | 1542 | if ' ' in cmd and os.path.isfile(cmd): |
|
1541 | 1543 | cmd = '"%s"' % cmd |
|
1542 | 1544 | |
|
1543 | 1545 | # Expand the %l special to be the user's input line |
|
1544 | 1546 | if cmd.find('%l') >= 0: |
|
1545 | 1547 | cmd = cmd.replace('%l',rest) |
|
1546 | 1548 | rest = '' |
|
1547 | 1549 | if nargs==0: |
|
1548 | 1550 | # Simple, argument-less aliases |
|
1549 | 1551 | cmd = '%s %s' % (cmd,rest) |
|
1550 | 1552 | else: |
|
1551 | 1553 | # Handle aliases with positional arguments |
|
1552 | 1554 | args = rest.split(None,nargs) |
|
1553 | 1555 | if len(args)< nargs: |
|
1554 | 1556 | error('Alias <%s> requires %s arguments, %s given.' % |
|
1555 | 1557 | (alias,nargs,len(args))) |
|
1556 | 1558 | return None |
|
1557 | 1559 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) |
|
1558 | 1560 | # Now call the macro, evaluating in the user's namespace |
|
1559 | 1561 | |
|
1560 | 1562 | return cmd |
|
1561 | 1563 | |
|
1562 | 1564 | def call_alias(self,alias,rest=''): |
|
1563 | 1565 | """Call an alias given its name and the rest of the line. |
|
1564 | 1566 | |
|
1565 | 1567 | This is only used to provide backwards compatibility for users of |
|
1566 | 1568 | ipalias(), use of which is not recommended for anymore.""" |
|
1567 | 1569 | |
|
1568 | 1570 | # Now call the macro, evaluating in the user's namespace |
|
1569 | 1571 | cmd = self.transform_alias(alias, rest) |
|
1570 | 1572 | try: |
|
1571 | 1573 | self.system(cmd) |
|
1572 | 1574 | except: |
|
1573 | 1575 | self.showtraceback() |
|
1574 | 1576 | |
|
1575 | 1577 | def indent_current_str(self): |
|
1576 | 1578 | """return the current level of indentation as a string""" |
|
1577 | 1579 | return self.indent_current_nsp * ' ' |
|
1578 | 1580 | |
|
1579 | 1581 | def autoindent_update(self,line): |
|
1580 | 1582 | """Keep track of the indent level.""" |
|
1581 | 1583 | |
|
1582 | 1584 | #debugx('line') |
|
1583 | 1585 | #debugx('self.indent_current_nsp') |
|
1584 | 1586 | if self.autoindent: |
|
1585 | 1587 | if line: |
|
1586 | 1588 | inisp = num_ini_spaces(line) |
|
1587 | 1589 | if inisp < self.indent_current_nsp: |
|
1588 | 1590 | self.indent_current_nsp = inisp |
|
1589 | 1591 | |
|
1590 | 1592 | if line[-1] == ':': |
|
1591 | 1593 | self.indent_current_nsp += 4 |
|
1592 | 1594 | elif dedent_re.match(line): |
|
1593 | 1595 | self.indent_current_nsp -= 4 |
|
1594 | 1596 | else: |
|
1595 | 1597 | self.indent_current_nsp = 0 |
|
1596 | 1598 | |
|
1597 | 1599 | def runlines(self,lines): |
|
1598 | 1600 | """Run a string of one or more lines of source. |
|
1599 | 1601 | |
|
1600 | 1602 | This method is capable of running a string containing multiple source |
|
1601 | 1603 | lines, as if they had been entered at the IPython prompt. Since it |
|
1602 | 1604 | exposes IPython's processing machinery, the given strings can contain |
|
1603 | 1605 | magic calls (%magic), special shell access (!cmd), etc.""" |
|
1604 | 1606 | |
|
1605 | 1607 | # We must start with a clean buffer, in case this is run from an |
|
1606 | 1608 | # interactive IPython session (via a magic, for example). |
|
1607 | 1609 | self.resetbuffer() |
|
1608 | 1610 | lines = lines.split('\n') |
|
1609 | 1611 | more = 0 |
|
1610 | 1612 | for line in lines: |
|
1611 | 1613 | # skip blank lines so we don't mess up the prompt counter, but do |
|
1612 | 1614 | # NOT skip even a blank line if we are in a code block (more is |
|
1613 | 1615 | # true) |
|
1614 | 1616 | if line or more: |
|
1615 | 1617 | more = self.push(self.prefilter(line,more)) |
|
1616 | 1618 | # IPython's runsource returns None if there was an error |
|
1617 | 1619 | # compiling the code. This allows us to stop processing right |
|
1618 | 1620 | # away, so the user gets the error message at the right place. |
|
1619 | 1621 | if more is None: |
|
1620 | 1622 | break |
|
1621 | 1623 | # final newline in case the input didn't have it, so that the code |
|
1622 | 1624 | # actually does get executed |
|
1623 | 1625 | if more: |
|
1624 | 1626 | self.push('\n') |
|
1625 | 1627 | |
|
1626 | 1628 | def runsource(self, source, filename='<input>', symbol='single'): |
|
1627 | 1629 | """Compile and run some source in the interpreter. |
|
1628 | 1630 | |
|
1629 | 1631 | Arguments are as for compile_command(). |
|
1630 | 1632 | |
|
1631 | 1633 | One several things can happen: |
|
1632 | 1634 | |
|
1633 | 1635 | 1) The input is incorrect; compile_command() raised an |
|
1634 | 1636 | exception (SyntaxError or OverflowError). A syntax traceback |
|
1635 | 1637 | will be printed by calling the showsyntaxerror() method. |
|
1636 | 1638 | |
|
1637 | 1639 | 2) The input is incomplete, and more input is required; |
|
1638 | 1640 | compile_command() returned None. Nothing happens. |
|
1639 | 1641 | |
|
1640 | 1642 | 3) The input is complete; compile_command() returned a code |
|
1641 | 1643 | object. The code is executed by calling self.runcode() (which |
|
1642 | 1644 | also handles run-time exceptions, except for SystemExit). |
|
1643 | 1645 | |
|
1644 | 1646 | The return value is: |
|
1645 | 1647 | |
|
1646 | 1648 | - True in case 2 |
|
1647 | 1649 | |
|
1648 | 1650 | - False in the other cases, unless an exception is raised, where |
|
1649 | 1651 | None is returned instead. This can be used by external callers to |
|
1650 | 1652 | know whether to continue feeding input or not. |
|
1651 | 1653 | |
|
1652 | 1654 | The return value can be used to decide whether to use sys.ps1 or |
|
1653 | 1655 | sys.ps2 to prompt the next line.""" |
|
1654 | 1656 | |
|
1655 | 1657 | try: |
|
1656 | 1658 | code = self.compile(source,filename,symbol) |
|
1657 | 1659 | except (OverflowError, SyntaxError, ValueError): |
|
1658 | 1660 | # Case 1 |
|
1659 | 1661 | self.showsyntaxerror(filename) |
|
1660 | 1662 | return None |
|
1661 | 1663 | |
|
1662 | 1664 | if code is None: |
|
1663 | 1665 | # Case 2 |
|
1664 | 1666 | return True |
|
1665 | 1667 | |
|
1666 | 1668 | # Case 3 |
|
1667 | 1669 | # We store the code object so that threaded shells and |
|
1668 | 1670 | # custom exception handlers can access all this info if needed. |
|
1669 | 1671 | # The source corresponding to this can be obtained from the |
|
1670 | 1672 | # buffer attribute as '\n'.join(self.buffer). |
|
1671 | 1673 | self.code_to_run = code |
|
1672 | 1674 | # now actually execute the code object |
|
1673 | 1675 | if self.runcode(code) == 0: |
|
1674 | 1676 | return False |
|
1675 | 1677 | else: |
|
1676 | 1678 | return None |
|
1677 | 1679 | |
|
1678 | 1680 | def runcode(self,code_obj): |
|
1679 | 1681 | """Execute a code object. |
|
1680 | 1682 | |
|
1681 | 1683 | When an exception occurs, self.showtraceback() is called to display a |
|
1682 | 1684 | traceback. |
|
1683 | 1685 | |
|
1684 | 1686 | Return value: a flag indicating whether the code to be run completed |
|
1685 | 1687 | successfully: |
|
1686 | 1688 | |
|
1687 | 1689 | - 0: successful execution. |
|
1688 | 1690 | - 1: an error occurred. |
|
1689 | 1691 | """ |
|
1690 | 1692 | |
|
1691 | 1693 | # Set our own excepthook in case the user code tries to call it |
|
1692 | 1694 | # directly, so that the IPython crash handler doesn't get triggered |
|
1693 | 1695 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
1694 | 1696 | |
|
1695 | 1697 | # we save the original sys.excepthook in the instance, in case config |
|
1696 | 1698 | # code (such as magics) needs access to it. |
|
1697 | 1699 | self.sys_excepthook = old_excepthook |
|
1698 | 1700 | outflag = 1 # happens in more places, so it's easier as default |
|
1699 | 1701 | try: |
|
1700 | 1702 | try: |
|
1701 | 1703 | # Embedded instances require separate global/local namespaces |
|
1702 | 1704 | # so they can see both the surrounding (local) namespace and |
|
1703 | 1705 | # the module-level globals when called inside another function. |
|
1704 | 1706 | if self.embedded: |
|
1705 | 1707 | exec code_obj in self.user_global_ns, self.user_ns |
|
1706 | 1708 | # Normal (non-embedded) instances should only have a single |
|
1707 | 1709 | # namespace for user code execution, otherwise functions won't |
|
1708 | 1710 | # see interactive top-level globals. |
|
1709 | 1711 | else: |
|
1710 | 1712 | exec code_obj in self.user_ns |
|
1711 | 1713 | finally: |
|
1712 | 1714 | # Reset our crash handler in place |
|
1713 | 1715 | sys.excepthook = old_excepthook |
|
1714 | 1716 | except SystemExit: |
|
1715 | 1717 | self.resetbuffer() |
|
1716 | 1718 | self.showtraceback() |
|
1717 | 1719 | warn("Type exit or quit to exit IPython " |
|
1718 | 1720 | "(%Exit or %Quit do so unconditionally).",level=1) |
|
1719 | 1721 | except self.custom_exceptions: |
|
1720 | 1722 | etype,value,tb = sys.exc_info() |
|
1721 | 1723 | self.CustomTB(etype,value,tb) |
|
1722 | 1724 | except: |
|
1723 | 1725 | self.showtraceback() |
|
1724 | 1726 | else: |
|
1725 | 1727 | outflag = 0 |
|
1726 | 1728 | if softspace(sys.stdout, 0): |
|
1727 | 1729 | |
|
1728 | 1730 | # Flush out code object which has been run (and source) |
|
1729 | 1731 | self.code_to_run = None |
|
1730 | 1732 | return outflag |
|
1731 | 1733 | |
|
1732 | 1734 | def push(self, line): |
|
1733 | 1735 | """Push a line to the interpreter. |
|
1734 | 1736 | |
|
1735 | 1737 | The line should not have a trailing newline; it may have |
|
1736 | 1738 | internal newlines. The line is appended to a buffer and the |
|
1737 | 1739 | interpreter's runsource() method is called with the |
|
1738 | 1740 | concatenated contents of the buffer as source. If this |
|
1739 | 1741 | indicates that the command was executed or invalid, the buffer |
|
1740 | 1742 | is reset; otherwise, the command is incomplete, and the buffer |
|
1741 | 1743 | is left as it was after the line was appended. The return |
|
1742 | 1744 | value is 1 if more input is required, 0 if the line was dealt |
|
1743 | 1745 | with in some way (this is the same as runsource()). |
|
1744 | 1746 | """ |
|
1745 | 1747 | |
|
1746 | 1748 | # autoindent management should be done here, and not in the |
|
1747 | 1749 | # interactive loop, since that one is only seen by keyboard input. We |
|
1748 | 1750 | # need this done correctly even for code run via runlines (which uses |
|
1749 | 1751 | # push). |
|
1750 | 1752 | |
|
1751 | 1753 | #print 'push line: <%s>' % line # dbg |
|
1752 | 1754 | self.autoindent_update(line) |
|
1753 | 1755 | |
|
1754 | 1756 | self.buffer.append(line) |
|
1755 | 1757 | more = self.runsource('\n'.join(self.buffer), self.filename) |
|
1756 | 1758 | if not more: |
|
1757 | 1759 | self.resetbuffer() |
|
1758 | 1760 | return more |
|
1759 | 1761 | |
|
1760 | 1762 | def resetbuffer(self): |
|
1761 | 1763 | """Reset the input buffer.""" |
|
1762 | 1764 | self.buffer[:] = [] |
|
1763 | 1765 | |
|
1764 | 1766 | def raw_input(self,prompt='',continue_prompt=False): |
|
1765 | 1767 | """Write a prompt and read a line. |
|
1766 | 1768 | |
|
1767 | 1769 | The returned line does not include the trailing newline. |
|
1768 | 1770 | When the user enters the EOF key sequence, EOFError is raised. |
|
1769 | 1771 | |
|
1770 | 1772 | Optional inputs: |
|
1771 | 1773 | |
|
1772 | 1774 | - prompt(''): a string to be printed to prompt the user. |
|
1773 | 1775 | |
|
1774 | 1776 | - continue_prompt(False): whether this line is the first one or a |
|
1775 | 1777 | continuation in a sequence of inputs. |
|
1776 | 1778 | """ |
|
1777 | 1779 | |
|
1778 | 1780 | line = raw_input_original(prompt) |
|
1779 | 1781 | |
|
1780 | 1782 | # Try to be reasonably smart about not re-indenting pasted input more |
|
1781 | 1783 | # than necessary. We do this by trimming out the auto-indent initial |
|
1782 | 1784 | # spaces, if the user's actual input started itself with whitespace. |
|
1783 | 1785 | #debugx('self.buffer[-1]') |
|
1784 | 1786 | |
|
1785 | 1787 | if self.autoindent: |
|
1786 | 1788 | if num_ini_spaces(line) > self.indent_current_nsp: |
|
1787 | 1789 | line = line[self.indent_current_nsp:] |
|
1788 | 1790 | self.indent_current_nsp = 0 |
|
1789 | 1791 | |
|
1790 | 1792 | # store the unfiltered input before the user has any chance to modify |
|
1791 | 1793 | # it. |
|
1792 | 1794 | if line.strip(): |
|
1793 | 1795 | if continue_prompt: |
|
1794 | 1796 | self.input_hist_raw[-1] += '%s\n' % line |
|
1795 | 1797 | else: |
|
1796 | 1798 | self.input_hist_raw.append('%s\n' % line) |
|
1797 | 1799 | |
|
1798 | 1800 | try: |
|
1799 | 1801 | lineout = self.prefilter(line,continue_prompt) |
|
1800 | 1802 | except: |
|
1801 | 1803 | # blanket except, in case a user-defined prefilter crashes, so it |
|
1802 | 1804 | # can't take all of ipython with it. |
|
1803 | 1805 | self.showtraceback() |
|
1804 | 1806 | return lineout |
|
1805 | 1807 | |
|
1806 | 1808 | def split_user_input(self,line): |
|
1807 | 1809 | """Split user input into pre-char, function part and rest.""" |
|
1808 | 1810 | |
|
1809 | 1811 | lsplit = self.line_split.match(line) |
|
1810 | 1812 | if lsplit is None: # no regexp match returns None |
|
1811 | 1813 | try: |
|
1812 | 1814 | iFun,theRest = line.split(None,1) |
|
1813 | 1815 | except ValueError: |
|
1814 | 1816 | iFun,theRest = line,'' |
|
1815 | 1817 | pre = re.match('^(\s*)(.*)',line).groups()[0] |
|
1816 | 1818 | else: |
|
1817 | 1819 | pre,iFun,theRest = lsplit.groups() |
|
1818 | 1820 | |
|
1819 | 1821 | #print 'line:<%s>' % line # dbg |
|
1820 | 1822 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg |
|
1821 | 1823 | return pre,iFun.strip(),theRest |
|
1822 | 1824 | |
|
1823 | 1825 | def _prefilter(self, line, continue_prompt): |
|
1824 | 1826 | """Calls different preprocessors, depending on the form of line.""" |
|
1825 | 1827 | |
|
1826 | 1828 | # All handlers *must* return a value, even if it's blank (''). |
|
1827 | 1829 | |
|
1828 | 1830 | # Lines are NOT logged here. Handlers should process the line as |
|
1829 | 1831 | # needed, update the cache AND log it (so that the input cache array |
|
1830 | 1832 | # stays synced). |
|
1831 | 1833 | |
|
1832 | 1834 | # This function is _very_ delicate, and since it's also the one which |
|
1833 | 1835 | # determines IPython's response to user input, it must be as efficient |
|
1834 | 1836 | # as possible. For this reason it has _many_ returns in it, trying |
|
1835 | 1837 | # always to exit as quickly as it can figure out what it needs to do. |
|
1836 | 1838 | |
|
1837 | 1839 | # This function is the main responsible for maintaining IPython's |
|
1838 | 1840 | # behavior respectful of Python's semantics. So be _very_ careful if |
|
1839 | 1841 | # making changes to anything here. |
|
1840 | 1842 | |
|
1841 | 1843 | #..................................................................... |
|
1842 | 1844 | # Code begins |
|
1843 | 1845 | |
|
1844 | 1846 | #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg |
|
1845 | 1847 | |
|
1846 | 1848 | # save the line away in case we crash, so the post-mortem handler can |
|
1847 | 1849 | # record it |
|
1848 | 1850 | self._last_input_line = line |
|
1849 | 1851 | |
|
1850 | 1852 | #print '***line: <%s>' % line # dbg |
|
1851 | 1853 | |
|
1852 | 1854 | # the input history needs to track even empty lines |
|
1853 | 1855 | stripped = line.strip() |
|
1854 | 1856 | |
|
1855 | 1857 | if not stripped: |
|
1856 | 1858 | if not continue_prompt: |
|
1857 | 1859 | self.outputcache.prompt_count -= 1 |
|
1858 | 1860 | return self.handle_normal(line,continue_prompt) |
|
1859 | 1861 | #return self.handle_normal('',continue_prompt) |
|
1860 | 1862 | |
|
1861 | 1863 | # print '***cont',continue_prompt # dbg |
|
1862 | 1864 | # special handlers are only allowed for single line statements |
|
1863 | 1865 | if continue_prompt and not self.rc.multi_line_specials: |
|
1864 | 1866 | return self.handle_normal(line,continue_prompt) |
|
1865 | 1867 | |
|
1866 | 1868 | |
|
1867 | 1869 | # For the rest, we need the structure of the input |
|
1868 | 1870 | pre,iFun,theRest = self.split_user_input(line) |
|
1869 | 1871 | |
|
1870 | 1872 | # See whether any pre-existing handler can take care of it |
|
1871 | 1873 | |
|
1872 | 1874 | rewritten = self.hooks.input_prefilter(stripped) |
|
1873 | 1875 | if rewritten != stripped: # ok, some prefilter did something |
|
1874 | 1876 | rewritten = pre + rewritten # add indentation |
|
1875 | 1877 | return self.handle_normal(rewritten) |
|
1876 | 1878 | |
|
1877 | ||
|
1878 | ||
|
1879 | ||
|
1880 | 1879 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
1881 | 1880 | |
|
1882 | 1881 | # First check for explicit escapes in the last/first character |
|
1883 | 1882 | handler = None |
|
1884 | 1883 | if line[-1] == self.ESC_HELP: |
|
1885 | 1884 | handler = self.esc_handlers.get(line[-1]) # the ? can be at the end |
|
1886 | 1885 | if handler is None: |
|
1887 | 1886 | # look at the first character of iFun, NOT of line, so we skip |
|
1888 | 1887 | # leading whitespace in multiline input |
|
1889 | 1888 | handler = self.esc_handlers.get(iFun[0:1]) |
|
1890 | 1889 | if handler is not None: |
|
1891 | 1890 | return handler(line,continue_prompt,pre,iFun,theRest) |
|
1892 | 1891 | # Emacs ipython-mode tags certain input lines |
|
1893 | 1892 | if line.endswith('# PYTHON-MODE'): |
|
1894 | 1893 | return self.handle_emacs(line,continue_prompt) |
|
1895 | 1894 | |
|
1896 | 1895 | # Next, check if we can automatically execute this thing |
|
1897 | 1896 | |
|
1898 | 1897 | # Allow ! in multi-line statements if multi_line_specials is on: |
|
1899 | 1898 | if continue_prompt and self.rc.multi_line_specials and \ |
|
1900 | 1899 | iFun.startswith(self.ESC_SHELL): |
|
1901 | 1900 | return self.handle_shell_escape(line,continue_prompt, |
|
1902 | 1901 | pre=pre,iFun=iFun, |
|
1903 | 1902 | theRest=theRest) |
|
1904 | 1903 | |
|
1905 | 1904 | # Let's try to find if the input line is a magic fn |
|
1906 | 1905 | oinfo = None |
|
1907 | 1906 | if hasattr(self,'magic_'+iFun): |
|
1908 | 1907 | # WARNING: _ofind uses getattr(), so it can consume generators and |
|
1909 | 1908 | # cause other side effects. |
|
1910 | 1909 | oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic |
|
1911 | 1910 | if oinfo['ismagic']: |
|
1912 | 1911 | # Be careful not to call magics when a variable assignment is |
|
1913 | 1912 | # being made (ls='hi', for example) |
|
1914 | 1913 | if self.rc.automagic and \ |
|
1915 | 1914 | (len(theRest)==0 or theRest[0] not in '!=()<>,') and \ |
|
1916 | 1915 | (self.rc.multi_line_specials or not continue_prompt): |
|
1917 | 1916 | return self.handle_magic(line,continue_prompt, |
|
1918 | 1917 | pre,iFun,theRest) |
|
1919 | 1918 | else: |
|
1920 | 1919 | return self.handle_normal(line,continue_prompt) |
|
1921 | 1920 | |
|
1922 | 1921 | # If the rest of the line begins with an (in)equality, assginment or |
|
1923 | 1922 | # function call, we should not call _ofind but simply execute it. |
|
1924 | 1923 | # This avoids spurious geattr() accesses on objects upon assignment. |
|
1925 | 1924 | # |
|
1926 | 1925 | # It also allows users to assign to either alias or magic names true |
|
1927 | 1926 | # python variables (the magic/alias systems always take second seat to |
|
1928 | 1927 | # true python code). |
|
1929 | 1928 | if theRest and theRest[0] in '!=()': |
|
1930 | 1929 | return self.handle_normal(line,continue_prompt) |
|
1931 | 1930 | |
|
1932 | 1931 | if oinfo is None: |
|
1933 | 1932 | # let's try to ensure that _oinfo is ONLY called when autocall is |
|
1934 | 1933 | # on. Since it has inevitable potential side effects, at least |
|
1935 | 1934 | # having autocall off should be a guarantee to the user that no |
|
1936 | 1935 | # weird things will happen. |
|
1937 | 1936 | |
|
1938 | 1937 | if self.rc.autocall: |
|
1939 | 1938 | oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic |
|
1940 | 1939 | else: |
|
1941 | 1940 | # in this case, all that's left is either an alias or |
|
1942 | 1941 | # processing the line normally. |
|
1943 | 1942 | if iFun in self.alias_table: |
|
1944 | return self.handle_alias(line,continue_prompt, | |
|
1945 | pre,iFun,theRest) | |
|
1943 | # if autocall is off, by not running _ofind we won't know | |
|
1944 | # whether the given name may also exist in one of the | |
|
1945 | # user's namespace. At this point, it's best to do a | |
|
1946 | # quick check just to be sure that we don't let aliases | |
|
1947 | # shadow variables. | |
|
1948 | head = iFun.split('.',1)[0] | |
|
1949 | if head in self.user_ns or head in self.internal_ns \ | |
|
1950 | or head in __builtin__.__dict__: | |
|
1951 | return self.handle_normal(line,continue_prompt) | |
|
1952 | else: | |
|
1953 | return self.handle_alias(line,continue_prompt, | |
|
1954 | pre,iFun,theRest) | |
|
1946 | 1955 | |
|
1947 | 1956 | else: |
|
1948 | 1957 | return self.handle_normal(line,continue_prompt) |
|
1949 | 1958 | |
|
1950 | 1959 | if not oinfo['found']: |
|
1951 | 1960 | return self.handle_normal(line,continue_prompt) |
|
1952 | 1961 | else: |
|
1953 | 1962 | #print 'pre<%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
1954 | 1963 | if oinfo['isalias']: |
|
1955 | 1964 | return self.handle_alias(line,continue_prompt, |
|
1956 | 1965 | pre,iFun,theRest) |
|
1957 | 1966 | |
|
1958 | 1967 | if (self.rc.autocall |
|
1959 | 1968 | and |
|
1960 | 1969 | ( |
|
1961 | 1970 | #only consider exclusion re if not "," or ";" autoquoting |
|
1962 | 1971 | (pre == self.ESC_QUOTE or pre == self.ESC_QUOTE2 |
|
1963 | 1972 | or pre == self.ESC_PAREN) or |
|
1964 | 1973 | (not self.re_exclude_auto.match(theRest))) |
|
1965 | 1974 | and |
|
1966 | 1975 | self.re_fun_name.match(iFun) and |
|
1967 | 1976 | callable(oinfo['obj'])) : |
|
1968 | 1977 | #print 'going auto' # dbg |
|
1969 | 1978 | return self.handle_auto(line,continue_prompt, |
|
1970 | 1979 | pre,iFun,theRest,oinfo['obj']) |
|
1971 | 1980 | else: |
|
1972 | 1981 | #print 'was callable?', callable(oinfo['obj']) # dbg |
|
1973 | 1982 | return self.handle_normal(line,continue_prompt) |
|
1974 | 1983 | |
|
1975 | 1984 | # If we get here, we have a normal Python line. Log and return. |
|
1976 | 1985 | return self.handle_normal(line,continue_prompt) |
|
1977 | 1986 | |
|
1978 | 1987 | def _prefilter_dumb(self, line, continue_prompt): |
|
1979 | 1988 | """simple prefilter function, for debugging""" |
|
1980 | 1989 | return self.handle_normal(line,continue_prompt) |
|
1981 | 1990 | |
|
1982 | 1991 | # Set the default prefilter() function (this can be user-overridden) |
|
1983 | 1992 | prefilter = _prefilter |
|
1984 | 1993 | |
|
1985 | 1994 | def handle_normal(self,line,continue_prompt=None, |
|
1986 | 1995 | pre=None,iFun=None,theRest=None): |
|
1987 | 1996 | """Handle normal input lines. Use as a template for handlers.""" |
|
1988 | 1997 | |
|
1989 | 1998 | # With autoindent on, we need some way to exit the input loop, and I |
|
1990 | 1999 | # don't want to force the user to have to backspace all the way to |
|
1991 | 2000 | # clear the line. The rule will be in this case, that either two |
|
1992 | 2001 | # lines of pure whitespace in a row, or a line of pure whitespace but |
|
1993 | 2002 | # of a size different to the indent level, will exit the input loop. |
|
1994 | 2003 | |
|
1995 | 2004 | if (continue_prompt and self.autoindent and line.isspace() and |
|
1996 | 2005 | (0 < abs(len(line) - self.indent_current_nsp) <= 2 or |
|
1997 | 2006 | (self.buffer[-1]).isspace() )): |
|
1998 | 2007 | line = '' |
|
1999 | 2008 | |
|
2000 | 2009 | self.log(line,continue_prompt) |
|
2001 | 2010 | return line |
|
2002 | 2011 | |
|
2003 | 2012 | def handle_alias(self,line,continue_prompt=None, |
|
2004 | 2013 | pre=None,iFun=None,theRest=None): |
|
2005 | 2014 | """Handle alias input lines. """ |
|
2006 | 2015 | |
|
2007 | 2016 | # pre is needed, because it carries the leading whitespace. Otherwise |
|
2008 | 2017 | # aliases won't work in indented sections. |
|
2009 | 2018 | transformed = self.transform_alias(iFun, theRest) |
|
2010 | 2019 | line_out = '%s_ip.system(%s)' % (pre, make_quoted_expr( transformed )) |
|
2011 | 2020 | self.log(line_out,continue_prompt) |
|
2012 | 2021 | return line_out |
|
2013 | 2022 | |
|
2014 | 2023 | def handle_shell_escape(self, line, continue_prompt=None, |
|
2015 | 2024 | pre=None,iFun=None,theRest=None): |
|
2016 | 2025 | """Execute the line in a shell, empty return value""" |
|
2017 | 2026 | |
|
2018 | 2027 | #print 'line in :', `line` # dbg |
|
2019 | 2028 | # Example of a special handler. Others follow a similar pattern. |
|
2020 | 2029 | if line.lstrip().startswith('!!'): |
|
2021 | 2030 | # rewrite iFun/theRest to properly hold the call to %sx and |
|
2022 | 2031 | # the actual command to be executed, so handle_magic can work |
|
2023 | 2032 | # correctly |
|
2024 | 2033 | theRest = '%s %s' % (iFun[2:],theRest) |
|
2025 | 2034 | iFun = 'sx' |
|
2026 | 2035 | return self.handle_magic('%ssx %s' % (self.ESC_MAGIC, |
|
2027 | 2036 | line.lstrip()[2:]), |
|
2028 | 2037 | continue_prompt,pre,iFun,theRest) |
|
2029 | 2038 | else: |
|
2030 | 2039 | cmd=line.lstrip().lstrip('!') |
|
2031 | 2040 | line_out = '%s_ip.system(%s)' % (pre,make_quoted_expr(cmd)) |
|
2032 | 2041 | # update cache/log and return |
|
2033 | 2042 | self.log(line_out,continue_prompt) |
|
2034 | 2043 | return line_out |
|
2035 | 2044 | |
|
2036 | 2045 | def handle_magic(self, line, continue_prompt=None, |
|
2037 | 2046 | pre=None,iFun=None,theRest=None): |
|
2038 | 2047 | """Execute magic functions.""" |
|
2039 | 2048 | |
|
2040 | 2049 | |
|
2041 | 2050 | cmd = '%s_ip.magic(%s)' % (pre,make_quoted_expr(iFun + " " + theRest)) |
|
2042 | 2051 | self.log(cmd,continue_prompt) |
|
2043 | 2052 | #print 'in handle_magic, cmd=<%s>' % cmd # dbg |
|
2044 | 2053 | return cmd |
|
2045 | 2054 | |
|
2046 | 2055 | def handle_auto(self, line, continue_prompt=None, |
|
2047 | 2056 | pre=None,iFun=None,theRest=None,obj=None): |
|
2048 | 2057 | """Hande lines which can be auto-executed, quoting if requested.""" |
|
2049 | 2058 | |
|
2050 | 2059 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
2051 | 2060 | |
|
2052 | 2061 | # This should only be active for single-line input! |
|
2053 | 2062 | if continue_prompt: |
|
2054 | 2063 | self.log(line,continue_prompt) |
|
2055 | 2064 | return line |
|
2056 | 2065 | |
|
2057 | 2066 | auto_rewrite = True |
|
2058 | 2067 | |
|
2059 | 2068 | if pre == self.ESC_QUOTE: |
|
2060 | 2069 | # Auto-quote splitting on whitespace |
|
2061 | 2070 | newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) ) |
|
2062 | 2071 | elif pre == self.ESC_QUOTE2: |
|
2063 | 2072 | # Auto-quote whole string |
|
2064 | 2073 | newcmd = '%s("%s")' % (iFun,theRest) |
|
2065 | 2074 | elif pre == self.ESC_PAREN: |
|
2066 | 2075 | newcmd = '%s(%s)' % (iFun,",".join(theRest.split())) |
|
2067 | 2076 | else: |
|
2068 | 2077 | # Auto-paren. |
|
2069 | 2078 | # We only apply it to argument-less calls if the autocall |
|
2070 | 2079 | # parameter is set to 2. We only need to check that autocall is < |
|
2071 | 2080 | # 2, since this function isn't called unless it's at least 1. |
|
2072 | 2081 | if not theRest and (self.rc.autocall < 2): |
|
2073 | 2082 | newcmd = '%s %s' % (iFun,theRest) |
|
2074 | 2083 | auto_rewrite = False |
|
2075 | 2084 | else: |
|
2076 | 2085 | if theRest.startswith('['): |
|
2077 | 2086 | if hasattr(obj,'__getitem__'): |
|
2078 | 2087 | # Don't autocall in this case: item access for an object |
|
2079 | 2088 | # which is BOTH callable and implements __getitem__. |
|
2080 | 2089 | newcmd = '%s %s' % (iFun,theRest) |
|
2081 | 2090 | auto_rewrite = False |
|
2082 | 2091 | else: |
|
2083 | 2092 | # if the object doesn't support [] access, go ahead and |
|
2084 | 2093 | # autocall |
|
2085 | 2094 | newcmd = '%s(%s)' % (iFun.rstrip(),theRest) |
|
2086 | 2095 | elif theRest.endswith(';'): |
|
2087 | 2096 | newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1]) |
|
2088 | 2097 | else: |
|
2089 | 2098 | newcmd = '%s(%s)' % (iFun.rstrip(), theRest) |
|
2090 | 2099 | |
|
2091 | 2100 | if auto_rewrite: |
|
2092 | 2101 | print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd |
|
2093 | 2102 | # log what is now valid Python, not the actual user input (without the |
|
2094 | 2103 | # final newline) |
|
2095 | 2104 | self.log(newcmd,continue_prompt) |
|
2096 | 2105 | return newcmd |
|
2097 | 2106 | |
|
2098 | 2107 | def handle_help(self, line, continue_prompt=None, |
|
2099 | 2108 | pre=None,iFun=None,theRest=None): |
|
2100 | 2109 | """Try to get some help for the object. |
|
2101 | 2110 | |
|
2102 | 2111 | obj? or ?obj -> basic information. |
|
2103 | 2112 | obj?? or ??obj -> more details. |
|
2104 | 2113 | """ |
|
2105 | 2114 | |
|
2106 | 2115 | # We need to make sure that we don't process lines which would be |
|
2107 | 2116 | # otherwise valid python, such as "x=1 # what?" |
|
2108 | 2117 | try: |
|
2109 | 2118 | codeop.compile_command(line) |
|
2110 | 2119 | except SyntaxError: |
|
2111 | 2120 | # We should only handle as help stuff which is NOT valid syntax |
|
2112 | 2121 | if line[0]==self.ESC_HELP: |
|
2113 | 2122 | line = line[1:] |
|
2114 | 2123 | elif line[-1]==self.ESC_HELP: |
|
2115 | 2124 | line = line[:-1] |
|
2116 | 2125 | self.log('#?'+line) |
|
2117 | 2126 | if line: |
|
2118 | 2127 | self.magic_pinfo(line) |
|
2119 | 2128 | else: |
|
2120 | 2129 | page(self.usage,screen_lines=self.rc.screen_length) |
|
2121 | 2130 | return '' # Empty string is needed here! |
|
2122 | 2131 | except: |
|
2123 | 2132 | # Pass any other exceptions through to the normal handler |
|
2124 | 2133 | return self.handle_normal(line,continue_prompt) |
|
2125 | 2134 | else: |
|
2126 | 2135 | # If the code compiles ok, we should handle it normally |
|
2127 | 2136 | return self.handle_normal(line,continue_prompt) |
|
2128 | 2137 | |
|
2129 | 2138 | def getapi(self): |
|
2130 | 2139 | """ Get an IPApi object for this shell instance |
|
2131 | 2140 | |
|
2132 | 2141 | Getting an IPApi object is always preferable to accessing the shell |
|
2133 | 2142 | directly, but this holds true especially for extensions. |
|
2134 | 2143 | |
|
2135 | 2144 | It should always be possible to implement an extension with IPApi |
|
2136 | 2145 | alone. If not, contact maintainer to request an addition. |
|
2137 | 2146 | |
|
2138 | 2147 | """ |
|
2139 | 2148 | return self.api |
|
2140 | 2149 | |
|
2141 | 2150 | def handle_emacs(self,line,continue_prompt=None, |
|
2142 | 2151 | pre=None,iFun=None,theRest=None): |
|
2143 | 2152 | """Handle input lines marked by python-mode.""" |
|
2144 | 2153 | |
|
2145 | 2154 | # Currently, nothing is done. Later more functionality can be added |
|
2146 | 2155 | # here if needed. |
|
2147 | 2156 | |
|
2148 | 2157 | # The input cache shouldn't be updated |
|
2149 | 2158 | |
|
2150 | 2159 | return line |
|
2151 | 2160 | |
|
2152 | 2161 | def mktempfile(self,data=None): |
|
2153 | 2162 | """Make a new tempfile and return its filename. |
|
2154 | 2163 | |
|
2155 | 2164 | This makes a call to tempfile.mktemp, but it registers the created |
|
2156 | 2165 | filename internally so ipython cleans it up at exit time. |
|
2157 | 2166 | |
|
2158 | 2167 | Optional inputs: |
|
2159 | 2168 | |
|
2160 | 2169 | - data(None): if data is given, it gets written out to the temp file |
|
2161 | 2170 | immediately, and the file is closed again.""" |
|
2162 | 2171 | |
|
2163 | 2172 | filename = tempfile.mktemp('.py','ipython_edit_') |
|
2164 | 2173 | self.tempfiles.append(filename) |
|
2165 | 2174 | |
|
2166 | 2175 | if data: |
|
2167 | 2176 | tmp_file = open(filename,'w') |
|
2168 | 2177 | tmp_file.write(data) |
|
2169 | 2178 | tmp_file.close() |
|
2170 | 2179 | return filename |
|
2171 | 2180 | |
|
2172 | 2181 | def write(self,data): |
|
2173 | 2182 | """Write a string to the default output""" |
|
2174 | 2183 | Term.cout.write(data) |
|
2175 | 2184 | |
|
2176 | 2185 | def write_err(self,data): |
|
2177 | 2186 | """Write a string to the default error output""" |
|
2178 | 2187 | Term.cerr.write(data) |
|
2179 | 2188 | |
|
2180 | 2189 | def exit(self): |
|
2181 | 2190 | """Handle interactive exit. |
|
2182 | 2191 | |
|
2183 | 2192 | This method sets the exit_now attribute.""" |
|
2184 | 2193 | |
|
2185 | 2194 | if self.rc.confirm_exit: |
|
2186 | 2195 | if ask_yes_no('Do you really want to exit ([y]/n)?','y'): |
|
2187 | 2196 | self.exit_now = True |
|
2188 | 2197 | else: |
|
2189 | 2198 | self.exit_now = True |
|
2190 | 2199 | return self.exit_now |
|
2191 | 2200 | |
|
2192 | 2201 | def safe_execfile(self,fname,*where,**kw): |
|
2193 | 2202 | fname = os.path.expanduser(fname) |
|
2194 | 2203 | |
|
2195 | 2204 | # find things also in current directory |
|
2196 | 2205 | dname = os.path.dirname(fname) |
|
2197 | 2206 | if not sys.path.count(dname): |
|
2198 | 2207 | sys.path.append(dname) |
|
2199 | 2208 | |
|
2200 | 2209 | try: |
|
2201 | 2210 | xfile = open(fname) |
|
2202 | 2211 | except: |
|
2203 | 2212 | print >> Term.cerr, \ |
|
2204 | 2213 | 'Could not open file <%s> for safe execution.' % fname |
|
2205 | 2214 | return None |
|
2206 | 2215 | |
|
2207 | 2216 | kw.setdefault('islog',0) |
|
2208 | 2217 | kw.setdefault('quiet',1) |
|
2209 | 2218 | kw.setdefault('exit_ignore',0) |
|
2210 | 2219 | first = xfile.readline() |
|
2211 | 2220 | loghead = str(self.loghead_tpl).split('\n',1)[0].strip() |
|
2212 | 2221 | xfile.close() |
|
2213 | 2222 | # line by line execution |
|
2214 | 2223 | if first.startswith(loghead) or kw['islog']: |
|
2215 | 2224 | print 'Loading log file <%s> one line at a time...' % fname |
|
2216 | 2225 | if kw['quiet']: |
|
2217 | 2226 | stdout_save = sys.stdout |
|
2218 | 2227 | sys.stdout = StringIO.StringIO() |
|
2219 | 2228 | try: |
|
2220 | 2229 | globs,locs = where[0:2] |
|
2221 | 2230 | except: |
|
2222 | 2231 | try: |
|
2223 | 2232 | globs = locs = where[0] |
|
2224 | 2233 | except: |
|
2225 | 2234 | globs = locs = globals() |
|
2226 | 2235 | badblocks = [] |
|
2227 | 2236 | |
|
2228 | 2237 | # we also need to identify indented blocks of code when replaying |
|
2229 | 2238 | # logs and put them together before passing them to an exec |
|
2230 | 2239 | # statement. This takes a bit of regexp and look-ahead work in the |
|
2231 | 2240 | # file. It's easiest if we swallow the whole thing in memory |
|
2232 | 2241 | # first, and manually walk through the lines list moving the |
|
2233 | 2242 | # counter ourselves. |
|
2234 | 2243 | indent_re = re.compile('\s+\S') |
|
2235 | 2244 | xfile = open(fname) |
|
2236 | 2245 | filelines = xfile.readlines() |
|
2237 | 2246 | xfile.close() |
|
2238 | 2247 | nlines = len(filelines) |
|
2239 | 2248 | lnum = 0 |
|
2240 | 2249 | while lnum < nlines: |
|
2241 | 2250 | line = filelines[lnum] |
|
2242 | 2251 | lnum += 1 |
|
2243 | 2252 | # don't re-insert logger status info into cache |
|
2244 | 2253 | if line.startswith('#log#'): |
|
2245 | 2254 | continue |
|
2246 | 2255 | else: |
|
2247 | 2256 | # build a block of code (maybe a single line) for execution |
|
2248 | 2257 | block = line |
|
2249 | 2258 | try: |
|
2250 | 2259 | next = filelines[lnum] # lnum has already incremented |
|
2251 | 2260 | except: |
|
2252 | 2261 | next = None |
|
2253 | 2262 | while next and indent_re.match(next): |
|
2254 | 2263 | block += next |
|
2255 | 2264 | lnum += 1 |
|
2256 | 2265 | try: |
|
2257 | 2266 | next = filelines[lnum] |
|
2258 | 2267 | except: |
|
2259 | 2268 | next = None |
|
2260 | 2269 | # now execute the block of one or more lines |
|
2261 | 2270 | try: |
|
2262 | 2271 | exec block in globs,locs |
|
2263 | 2272 | except SystemExit: |
|
2264 | 2273 | pass |
|
2265 | 2274 | except: |
|
2266 | 2275 | badblocks.append(block.rstrip()) |
|
2267 | 2276 | if kw['quiet']: # restore stdout |
|
2268 | 2277 | sys.stdout.close() |
|
2269 | 2278 | sys.stdout = stdout_save |
|
2270 | 2279 | print 'Finished replaying log file <%s>' % fname |
|
2271 | 2280 | if badblocks: |
|
2272 | 2281 | print >> sys.stderr, ('\nThe following lines/blocks in file ' |
|
2273 | 2282 | '<%s> reported errors:' % fname) |
|
2274 | 2283 | |
|
2275 | 2284 | for badline in badblocks: |
|
2276 | 2285 | print >> sys.stderr, badline |
|
2277 | 2286 | else: # regular file execution |
|
2278 | 2287 | try: |
|
2279 | 2288 | execfile(fname,*where) |
|
2280 | 2289 | except SyntaxError: |
|
2281 | 2290 | self.showsyntaxerror() |
|
2282 | 2291 | warn('Failure executing file: <%s>' % fname) |
|
2283 | 2292 | except SystemExit,status: |
|
2284 | 2293 | if not kw['exit_ignore']: |
|
2285 | 2294 | self.showtraceback() |
|
2286 | 2295 | warn('Failure executing file: <%s>' % fname) |
|
2287 | 2296 | except: |
|
2288 | 2297 | self.showtraceback() |
|
2289 | 2298 | warn('Failure executing file: <%s>' % fname) |
|
2290 | 2299 | |
|
2291 | 2300 | #************************* end of file <iplib.py> ***************************** |
@@ -1,755 +1,757 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 132 |
|
|
9 | $Id: ipmaker.py 1329 2006-05-26 07:52:45Z fperez $""" | |
|
10 | 10 | |
|
11 | 11 | #***************************************************************************** |
|
12 | 12 | # Copyright (C) 2001-2006 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.ipstruct import Struct |
|
50 | 50 | from IPython.OutputTrap import OutputTrap |
|
51 | 51 | from IPython.ConfigLoader import ConfigLoader |
|
52 | 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 | # add personal .ipython dir to sys.path so that users can put things in |
|
131 | 131 | # there for customization |
|
132 | 132 | sys.path.append(ipythondir) |
|
133 | 133 | |
|
134 | 134 | sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran |
|
135 | 135 | |
|
136 | 136 | # we need the directory where IPython itself is installed |
|
137 | 137 | import IPython |
|
138 | 138 | IPython_dir = os.path.dirname(IPython.__file__) |
|
139 | 139 | del IPython |
|
140 | 140 | |
|
141 | 141 | #------------------------------------------------------------------------- |
|
142 | 142 | # Command line handling |
|
143 | 143 | |
|
144 | 144 | # Valid command line options (uses DPyGetOpt syntax, like Perl's |
|
145 | 145 | # GetOpt::Long) |
|
146 | 146 | |
|
147 | 147 | # Any key not listed here gets deleted even if in the file (like session |
|
148 | 148 | # or profile). That's deliberate, to maintain the rc namespace clean. |
|
149 | 149 | |
|
150 | 150 | # Each set of options appears twice: under _conv only the names are |
|
151 | 151 | # listed, indicating which type they must be converted to when reading the |
|
152 | 152 | # ipythonrc file. And under DPyGetOpt they are listed with the regular |
|
153 | 153 | # DPyGetOpt syntax (=s,=i,:f,etc). |
|
154 | 154 | |
|
155 | 155 | # Make sure there's a space before each end of line (they get auto-joined!) |
|
156 | 156 | cmdline_opts = ('autocall=i autoindent! automagic! banner! cache_size|cs=i ' |
|
157 | 157 | 'c=s classic|cl color_info! colors=s confirm_exit! ' |
|
158 |
'debug! deep_reload! editor=s log|l messages! nosep |
|
|
158 | 'debug! deep_reload! editor=s log|l messages! nosep ' | |
|
159 | 'object_info_string_level=i pdb! ' | |
|
159 | 160 | 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s ' |
|
160 | 161 | 'quick screen_length|sl=i prompts_pad_left=i ' |
|
161 | 162 | 'logfile|lf=s logplay|lp=s profile|p=s ' |
|
162 | 163 | 'readline! readline_merge_completions! ' |
|
163 | 164 | 'readline_omit__names! ' |
|
164 | 165 | 'rcfile=s separate_in|si=s separate_out|so=s ' |
|
165 | 166 | 'separate_out2|so2=s xmode=s wildcards_case_sensitive! ' |
|
166 | 167 | 'magic_docstrings system_verbose! ' |
|
167 | 168 | 'multi_line_specials! ' |
|
168 | 169 | 'wxversion=s ' |
|
169 | 170 | 'autoedit_syntax!') |
|
170 | 171 | |
|
171 | 172 | # Options that can *only* appear at the cmd line (not in rcfiles). |
|
172 | 173 | |
|
173 | 174 | # The "ignore" option is a kludge so that Emacs buffers don't crash, since |
|
174 | 175 | # the 'C-c !' command in emacs automatically appends a -i option at the end. |
|
175 | 176 | cmdline_only = ('help ignore|i ipythondir=s Version upgrade ' |
|
176 | 177 | 'gthread! qthread! wthread! pylab! tk!') |
|
177 | 178 | |
|
178 | 179 | # Build the actual name list to be used by DPyGetOpt |
|
179 | 180 | opts_names = qw(cmdline_opts) + qw(cmdline_only) |
|
180 | 181 | |
|
181 | 182 | # Set sensible command line defaults. |
|
182 | 183 | # This should have everything from cmdline_opts and cmdline_only |
|
183 | 184 | opts_def = Struct(autocall = 1, |
|
184 | 185 | autoedit_syntax = 0, |
|
185 | 186 | autoindent = 0, |
|
186 | 187 | automagic = 1, |
|
187 | 188 | banner = 1, |
|
188 | 189 | cache_size = 1000, |
|
189 | 190 | c = '', |
|
190 | 191 | classic = 0, |
|
191 | 192 | colors = 'NoColor', |
|
192 | 193 | color_info = 0, |
|
193 | 194 | confirm_exit = 1, |
|
194 | 195 | debug = 0, |
|
195 | 196 | deep_reload = 0, |
|
196 | 197 | editor = '0', |
|
197 | 198 | help = 0, |
|
198 | 199 | ignore = 0, |
|
199 | 200 | ipythondir = ipythondir, |
|
200 | 201 | log = 0, |
|
201 | 202 | logfile = '', |
|
202 | 203 | logplay = '', |
|
203 | 204 | multi_line_specials = 1, |
|
204 | 205 | messages = 1, |
|
206 | object_info_string_level = 0, | |
|
205 | 207 | nosep = 0, |
|
206 | 208 | pdb = 0, |
|
207 | 209 | pprint = 0, |
|
208 | 210 | profile = '', |
|
209 | 211 | prompt_in1 = 'In [\\#]: ', |
|
210 | 212 | prompt_in2 = ' .\\D.: ', |
|
211 | 213 | prompt_out = 'Out[\\#]: ', |
|
212 | 214 | prompts_pad_left = 1, |
|
213 | 215 | quick = 0, |
|
214 | 216 | readline = 1, |
|
215 | 217 | readline_merge_completions = 1, |
|
216 | 218 | readline_omit__names = 0, |
|
217 | 219 | rcfile = 'ipythonrc' + rc_suffix, |
|
218 | 220 | screen_length = 0, |
|
219 | 221 | separate_in = '\n', |
|
220 | 222 | separate_out = '\n', |
|
221 | 223 | separate_out2 = '', |
|
222 | 224 | system_verbose = 0, |
|
223 | 225 | gthread = 0, |
|
224 | 226 | qthread = 0, |
|
225 | 227 | wthread = 0, |
|
226 | 228 | pylab = 0, |
|
227 | 229 | tk = 0, |
|
228 | 230 | upgrade = 0, |
|
229 | 231 | Version = 0, |
|
230 | 232 | xmode = 'Verbose', |
|
231 | 233 | wildcards_case_sensitive = 1, |
|
232 | 234 | wxversion = '0', |
|
233 | 235 | magic_docstrings = 0, # undocumented, for doc generation |
|
234 | 236 | ) |
|
235 | 237 | |
|
236 | 238 | # Things that will *only* appear in rcfiles (not at the command line). |
|
237 | 239 | # Make sure there's a space before each end of line (they get auto-joined!) |
|
238 | 240 | rcfile_opts = { qwflat: 'include import_mod import_all execfile ', |
|
239 | 241 | qw_lol: 'import_some ', |
|
240 | 242 | # for things with embedded whitespace: |
|
241 | 243 | list_strings:'execute alias readline_parse_and_bind ', |
|
242 | 244 | # Regular strings need no conversion: |
|
243 | 245 | None:'readline_remove_delims ', |
|
244 | 246 | } |
|
245 | 247 | # Default values for these |
|
246 | 248 | rc_def = Struct(include = [], |
|
247 | 249 | import_mod = [], |
|
248 | 250 | import_all = [], |
|
249 | 251 | import_some = [[]], |
|
250 | 252 | execute = [], |
|
251 | 253 | execfile = [], |
|
252 | 254 | alias = [], |
|
253 | 255 | readline_parse_and_bind = [], |
|
254 | 256 | readline_remove_delims = '', |
|
255 | 257 | ) |
|
256 | 258 | |
|
257 | 259 | # Build the type conversion dictionary from the above tables: |
|
258 | 260 | typeconv = rcfile_opts.copy() |
|
259 | 261 | typeconv.update(optstr2types(cmdline_opts)) |
|
260 | 262 | |
|
261 | 263 | # FIXME: the None key appears in both, put that back together by hand. Ugly! |
|
262 | 264 | typeconv[None] += ' ' + rcfile_opts[None] |
|
263 | 265 | |
|
264 | 266 | # Remove quotes at ends of all strings (used to protect spaces) |
|
265 | 267 | typeconv[unquote_ends] = typeconv[None] |
|
266 | 268 | del typeconv[None] |
|
267 | 269 | |
|
268 | 270 | # Build the list we'll use to make all config decisions with defaults: |
|
269 | 271 | opts_all = opts_def.copy() |
|
270 | 272 | opts_all.update(rc_def) |
|
271 | 273 | |
|
272 | 274 | # Build conflict resolver for recursive loading of config files: |
|
273 | 275 | # - preserve means the outermost file maintains the value, it is not |
|
274 | 276 | # overwritten if an included file has the same key. |
|
275 | 277 | # - add_flip applies + to the two values, so it better make sense to add |
|
276 | 278 | # those types of keys. But it flips them first so that things loaded |
|
277 | 279 | # deeper in the inclusion chain have lower precedence. |
|
278 | 280 | conflict = {'preserve': ' '.join([ typeconv[int], |
|
279 | 281 | typeconv[unquote_ends] ]), |
|
280 | 282 | 'add_flip': ' '.join([ typeconv[qwflat], |
|
281 | 283 | typeconv[qw_lol], |
|
282 | 284 | typeconv[list_strings] ]) |
|
283 | 285 | } |
|
284 | 286 | |
|
285 | 287 | # Now actually process the command line |
|
286 | 288 | getopt = DPyGetOpt.DPyGetOpt() |
|
287 | 289 | getopt.setIgnoreCase(0) |
|
288 | 290 | |
|
289 | 291 | getopt.parseConfiguration(opts_names) |
|
290 | 292 | |
|
291 | 293 | try: |
|
292 | 294 | getopt.processArguments(argv) |
|
293 | 295 | except: |
|
294 | 296 | print cmd_line_usage |
|
295 | 297 | warn('\nError in Arguments: ' + `sys.exc_value`) |
|
296 | 298 | sys.exit(1) |
|
297 | 299 | |
|
298 | 300 | # convert the options dict to a struct for much lighter syntax later |
|
299 | 301 | opts = Struct(getopt.optionValues) |
|
300 | 302 | args = getopt.freeValues |
|
301 | 303 | |
|
302 | 304 | # this is the struct (which has default values at this point) with which |
|
303 | 305 | # we make all decisions: |
|
304 | 306 | opts_all.update(opts) |
|
305 | 307 | |
|
306 | 308 | # Options that force an immediate exit |
|
307 | 309 | if opts_all.help: |
|
308 | 310 | page(cmd_line_usage) |
|
309 | 311 | sys.exit() |
|
310 | 312 | |
|
311 | 313 | if opts_all.Version: |
|
312 | 314 | print __version__ |
|
313 | 315 | sys.exit() |
|
314 | 316 | |
|
315 | 317 | if opts_all.magic_docstrings: |
|
316 | 318 | IP.magic_magic('-latex') |
|
317 | 319 | sys.exit() |
|
318 | 320 | |
|
319 | 321 | # Create user config directory if it doesn't exist. This must be done |
|
320 | 322 | # *after* getting the cmd line options. |
|
321 | 323 | if not os.path.isdir(opts_all.ipythondir): |
|
322 | 324 | IP.user_setup(opts_all.ipythondir,rc_suffix,'install') |
|
323 | 325 | |
|
324 | 326 | # upgrade user config files while preserving a copy of the originals |
|
325 | 327 | if opts_all.upgrade: |
|
326 | 328 | IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade') |
|
327 | 329 | |
|
328 | 330 | # check mutually exclusive options in the *original* command line |
|
329 | 331 | mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'), |
|
330 | 332 | qw('classic profile'),qw('classic rcfile')]) |
|
331 | 333 | |
|
332 | 334 | # Fix up sys.argv to omit the ipython call, for consistency with how |
|
333 | 335 | # Python itself operates (the inconsistency can break user scripts which |
|
334 | 336 | # rely on the Python behavior when run under ipython). |
|
335 | 337 | sys.argv[:] = sys.argv[1:] |
|
336 | 338 | |
|
337 | 339 | #--------------------------------------------------------------------------- |
|
338 | 340 | # Log replay |
|
339 | 341 | |
|
340 | 342 | # if -logplay, we need to 'become' the other session. That basically means |
|
341 | 343 | # replacing the current command line environment with that of the old |
|
342 | 344 | # session and moving on. |
|
343 | 345 | |
|
344 | 346 | # this is needed so that later we know we're in session reload mode, as |
|
345 | 347 | # opts_all will get overwritten: |
|
346 | 348 | load_logplay = 0 |
|
347 | 349 | |
|
348 | 350 | if opts_all.logplay: |
|
349 | 351 | load_logplay = opts_all.logplay |
|
350 | 352 | opts_debug_save = opts_all.debug |
|
351 | 353 | try: |
|
352 | 354 | logplay = open(opts_all.logplay) |
|
353 | 355 | except IOError: |
|
354 | 356 | if opts_all.debug: IP.InteractiveTB() |
|
355 | 357 | warn('Could not open logplay file '+`opts_all.logplay`) |
|
356 | 358 | # restore state as if nothing had happened and move on, but make |
|
357 | 359 | # sure that later we don't try to actually load the session file |
|
358 | 360 | logplay = None |
|
359 | 361 | load_logplay = 0 |
|
360 | 362 | del opts_all.logplay |
|
361 | 363 | else: |
|
362 | 364 | try: |
|
363 | 365 | logplay.readline() |
|
364 | 366 | logplay.readline(); |
|
365 | 367 | # this reloads that session's command line |
|
366 | 368 | cmd = logplay.readline()[6:] |
|
367 | 369 | exec cmd |
|
368 | 370 | # restore the true debug flag given so that the process of |
|
369 | 371 | # session loading itself can be monitored. |
|
370 | 372 | opts.debug = opts_debug_save |
|
371 | 373 | # save the logplay flag so later we don't overwrite the log |
|
372 | 374 | opts.logplay = load_logplay |
|
373 | 375 | # now we must update our own structure with defaults |
|
374 | 376 | opts_all.update(opts) |
|
375 | 377 | # now load args |
|
376 | 378 | cmd = logplay.readline()[6:] |
|
377 | 379 | exec cmd |
|
378 | 380 | logplay.close() |
|
379 | 381 | except: |
|
380 | 382 | logplay.close() |
|
381 | 383 | if opts_all.debug: IP.InteractiveTB() |
|
382 | 384 | warn("Logplay file lacking full configuration information.\n" |
|
383 | 385 | "I'll try to read it, but some things may not work.") |
|
384 | 386 | |
|
385 | 387 | #------------------------------------------------------------------------- |
|
386 | 388 | # set up output traps: catch all output from files, being run, modules |
|
387 | 389 | # loaded, etc. Then give it to the user in a clean form at the end. |
|
388 | 390 | |
|
389 | 391 | msg_out = 'Output messages. ' |
|
390 | 392 | msg_err = 'Error messages. ' |
|
391 | 393 | msg_sep = '\n' |
|
392 | 394 | msg = Struct(config = OutputTrap('Configuration Loader',msg_out, |
|
393 | 395 | msg_err,msg_sep,debug, |
|
394 | 396 | quiet_out=1), |
|
395 | 397 | user_exec = OutputTrap('User File Execution',msg_out, |
|
396 | 398 | msg_err,msg_sep,debug), |
|
397 | 399 | logplay = OutputTrap('Log Loader',msg_out, |
|
398 | 400 | msg_err,msg_sep,debug), |
|
399 | 401 | summary = '' |
|
400 | 402 | ) |
|
401 | 403 | |
|
402 | 404 | #------------------------------------------------------------------------- |
|
403 | 405 | # Process user ipythonrc-type configuration files |
|
404 | 406 | |
|
405 | 407 | # turn on output trapping and log to msg.config |
|
406 | 408 | # remember that with debug on, trapping is actually disabled |
|
407 | 409 | msg.config.trap_all() |
|
408 | 410 | |
|
409 | 411 | # look for rcfile in current or default directory |
|
410 | 412 | try: |
|
411 | 413 | opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir) |
|
412 | 414 | except IOError: |
|
413 | 415 | if opts_all.debug: IP.InteractiveTB() |
|
414 | 416 | warn('Configuration file %s not found. Ignoring request.' |
|
415 | 417 | % (opts_all.rcfile) ) |
|
416 | 418 | |
|
417 | 419 | # 'profiles' are a shorthand notation for config filenames |
|
418 | 420 | if opts_all.profile: |
|
419 | 421 | |
|
420 | 422 | try: |
|
421 | 423 | opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile |
|
422 | 424 | + rc_suffix, |
|
423 | 425 | opts_all.ipythondir) |
|
424 | 426 | except IOError: |
|
425 | 427 | if opts_all.debug: IP.InteractiveTB() |
|
426 | 428 | opts.profile = '' # remove profile from options if invalid |
|
427 | 429 | # We won't warn anymore, primary method is ipy_profile_PROFNAME |
|
428 | 430 | # which does trigger a warning. |
|
429 | 431 | |
|
430 | 432 | # load the config file |
|
431 | 433 | rcfiledata = None |
|
432 | 434 | if opts_all.quick: |
|
433 | 435 | print 'Launching IPython in quick mode. No config file read.' |
|
434 | 436 | elif opts_all.classic: |
|
435 | 437 | print 'Launching IPython in classic mode. No config file read.' |
|
436 | 438 | elif opts_all.rcfile: |
|
437 | 439 | try: |
|
438 | 440 | cfg_loader = ConfigLoader(conflict) |
|
439 | 441 | rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv, |
|
440 | 442 | 'include',opts_all.ipythondir, |
|
441 | 443 | purge = 1, |
|
442 | 444 | unique = conflict['preserve']) |
|
443 | 445 | except: |
|
444 | 446 | IP.InteractiveTB() |
|
445 | 447 | warn('Problems loading configuration file '+ |
|
446 | 448 | `opts_all.rcfile`+ |
|
447 | 449 | '\nStarting with default -bare bones- configuration.') |
|
448 | 450 | else: |
|
449 | 451 | warn('No valid configuration file found in either currrent directory\n'+ |
|
450 | 452 | 'or in the IPython config. directory: '+`opts_all.ipythondir`+ |
|
451 | 453 | '\nProceeding with internal defaults.') |
|
452 | 454 | |
|
453 | 455 | #------------------------------------------------------------------------ |
|
454 | 456 | # Set exception handlers in mode requested by user. |
|
455 | 457 | otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode |
|
456 | 458 | IP.magic_xmode(opts_all.xmode) |
|
457 | 459 | otrap.release_out() |
|
458 | 460 | |
|
459 | 461 | #------------------------------------------------------------------------ |
|
460 | 462 | # Execute user config |
|
461 | 463 | |
|
462 | 464 | # Create a valid config structure with the right precedence order: |
|
463 | 465 | # defaults < rcfile < command line. This needs to be in the instance, so |
|
464 | 466 | # that method calls below that rely on it find it. |
|
465 | 467 | IP.rc = rc_def.copy() |
|
466 | 468 | |
|
467 | 469 | # Work with a local alias inside this routine to avoid unnecessary |
|
468 | 470 | # attribute lookups. |
|
469 | 471 | IP_rc = IP.rc |
|
470 | 472 | |
|
471 | 473 | IP_rc.update(opts_def) |
|
472 | 474 | if rcfiledata: |
|
473 | 475 | # now we can update |
|
474 | 476 | IP_rc.update(rcfiledata) |
|
475 | 477 | IP_rc.update(opts) |
|
476 | 478 | IP_rc.update(rc_override) |
|
477 | 479 | |
|
478 | 480 | # Store the original cmd line for reference: |
|
479 | 481 | IP_rc.opts = opts |
|
480 | 482 | IP_rc.args = args |
|
481 | 483 | |
|
482 | 484 | # create a *runtime* Struct like rc for holding parameters which may be |
|
483 | 485 | # created and/or modified by runtime user extensions. |
|
484 | 486 | IP.runtime_rc = Struct() |
|
485 | 487 | |
|
486 | 488 | # from this point on, all config should be handled through IP_rc, |
|
487 | 489 | # opts* shouldn't be used anymore. |
|
488 | 490 | |
|
489 | 491 | |
|
490 | 492 | # update IP_rc with some special things that need manual |
|
491 | 493 | # tweaks. Basically options which affect other options. I guess this |
|
492 | 494 | # should just be written so that options are fully orthogonal and we |
|
493 | 495 | # wouldn't worry about this stuff! |
|
494 | 496 | |
|
495 | 497 | if IP_rc.classic: |
|
496 | 498 | IP_rc.quick = 1 |
|
497 | 499 | IP_rc.cache_size = 0 |
|
498 | 500 | IP_rc.pprint = 0 |
|
499 | 501 | IP_rc.prompt_in1 = '>>> ' |
|
500 | 502 | IP_rc.prompt_in2 = '... ' |
|
501 | 503 | IP_rc.prompt_out = '' |
|
502 | 504 | IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0' |
|
503 | 505 | IP_rc.colors = 'NoColor' |
|
504 | 506 | IP_rc.xmode = 'Plain' |
|
505 | 507 | |
|
506 | 508 | IP.pre_config_initialization() |
|
507 | 509 | # configure readline |
|
508 | 510 | # Define the history file for saving commands in between sessions |
|
509 | 511 | if IP_rc.profile: |
|
510 | 512 | histfname = 'history-%s' % IP_rc.profile |
|
511 | 513 | else: |
|
512 | 514 | histfname = 'history' |
|
513 | 515 | IP.histfile = os.path.join(opts_all.ipythondir,histfname) |
|
514 | 516 | |
|
515 | 517 | # update exception handlers with rc file status |
|
516 | 518 | otrap.trap_out() # I don't want these messages ever. |
|
517 | 519 | IP.magic_xmode(IP_rc.xmode) |
|
518 | 520 | otrap.release_out() |
|
519 | 521 | |
|
520 | 522 | # activate logging if requested and not reloading a log |
|
521 | 523 | if IP_rc.logplay: |
|
522 | 524 | IP.magic_logstart(IP_rc.logplay + ' append') |
|
523 | 525 | elif IP_rc.logfile: |
|
524 | 526 | IP.magic_logstart(IP_rc.logfile) |
|
525 | 527 | elif IP_rc.log: |
|
526 | 528 | IP.magic_logstart() |
|
527 | 529 | |
|
528 | 530 | # find user editor so that it we don't have to look it up constantly |
|
529 | 531 | if IP_rc.editor.strip()=='0': |
|
530 | 532 | try: |
|
531 | 533 | ed = os.environ['EDITOR'] |
|
532 | 534 | except KeyError: |
|
533 | 535 | if os.name == 'posix': |
|
534 | 536 | ed = 'vi' # the only one guaranteed to be there! |
|
535 | 537 | else: |
|
536 | 538 | ed = 'notepad' # same in Windows! |
|
537 | 539 | IP_rc.editor = ed |
|
538 | 540 | |
|
539 | 541 | # Keep track of whether this is an embedded instance or not (useful for |
|
540 | 542 | # post-mortems). |
|
541 | 543 | IP_rc.embedded = IP.embedded |
|
542 | 544 | |
|
543 | 545 | # Recursive reload |
|
544 | 546 | try: |
|
545 | 547 | from IPython import deep_reload |
|
546 | 548 | if IP_rc.deep_reload: |
|
547 | 549 | __builtin__.reload = deep_reload.reload |
|
548 | 550 | else: |
|
549 | 551 | __builtin__.dreload = deep_reload.reload |
|
550 | 552 | del deep_reload |
|
551 | 553 | except ImportError: |
|
552 | 554 | pass |
|
553 | 555 | |
|
554 | 556 | # Save the current state of our namespace so that the interactive shell |
|
555 | 557 | # can later know which variables have been created by us from config files |
|
556 | 558 | # and loading. This way, loading a file (in any way) is treated just like |
|
557 | 559 | # defining things on the command line, and %who works as expected. |
|
558 | 560 | |
|
559 | 561 | # DON'T do anything that affects the namespace beyond this point! |
|
560 | 562 | IP.internal_ns.update(__main__.__dict__) |
|
561 | 563 | |
|
562 | 564 | #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who |
|
563 | 565 | |
|
564 | 566 | # Now run through the different sections of the users's config |
|
565 | 567 | if IP_rc.debug: |
|
566 | 568 | print 'Trying to execute the following configuration structure:' |
|
567 | 569 | print '(Things listed first are deeper in the inclusion tree and get' |
|
568 | 570 | print 'loaded first).\n' |
|
569 | 571 | pprint(IP_rc.__dict__) |
|
570 | 572 | |
|
571 | 573 | for mod in IP_rc.import_mod: |
|
572 | 574 | try: |
|
573 | 575 | exec 'import '+mod in IP.user_ns |
|
574 | 576 | except : |
|
575 | 577 | IP.InteractiveTB() |
|
576 | 578 | import_fail_info(mod) |
|
577 | 579 | |
|
578 | 580 | for mod_fn in IP_rc.import_some: |
|
579 | 581 | if mod_fn == []: break |
|
580 | 582 | mod,fn = mod_fn[0],','.join(mod_fn[1:]) |
|
581 | 583 | try: |
|
582 | 584 | exec 'from '+mod+' import '+fn in IP.user_ns |
|
583 | 585 | except : |
|
584 | 586 | IP.InteractiveTB() |
|
585 | 587 | import_fail_info(mod,fn) |
|
586 | 588 | |
|
587 | 589 | for mod in IP_rc.import_all: |
|
588 | 590 | try: |
|
589 | 591 | exec 'from '+mod+' import *' in IP.user_ns |
|
590 | 592 | except : |
|
591 | 593 | IP.InteractiveTB() |
|
592 | 594 | import_fail_info(mod) |
|
593 | 595 | |
|
594 | 596 | for code in IP_rc.execute: |
|
595 | 597 | try: |
|
596 | 598 | exec code in IP.user_ns |
|
597 | 599 | except: |
|
598 | 600 | IP.InteractiveTB() |
|
599 | 601 | warn('Failure executing code: ' + `code`) |
|
600 | 602 | |
|
601 | 603 | # Execute the files the user wants in ipythonrc |
|
602 | 604 | for file in IP_rc.execfile: |
|
603 | 605 | try: |
|
604 | 606 | file = filefind(file,sys.path+[IPython_dir]) |
|
605 | 607 | except IOError: |
|
606 | 608 | warn(itpl('File $file not found. Skipping it.')) |
|
607 | 609 | else: |
|
608 | 610 | IP.safe_execfile(os.path.expanduser(file),IP.user_ns) |
|
609 | 611 | |
|
610 | 612 | # finally, try importing ipy_*_conf for final configuration |
|
611 | 613 | try: |
|
612 | 614 | import ipy_system_conf |
|
613 | 615 | except ImportError: |
|
614 | 616 | if opts_all.debug: IP.InteractiveTB() |
|
615 | 617 | warn("Could not import 'ipy_system_conf'") |
|
616 | 618 | except: |
|
617 | 619 | IP.InteractiveTB() |
|
618 | 620 | import_fail_info('ipy_system_conf') |
|
619 | 621 | |
|
620 | 622 | if opts_all.profile: |
|
621 | 623 | profmodname = 'ipy_profile_' + opts_all.profile |
|
622 | 624 | try: |
|
623 | 625 | __import__(profmodname) |
|
624 | 626 | except ImportError: |
|
625 | 627 | # only warn if ipythonrc-PROFNAME didn't exist |
|
626 | 628 | if opts.profile =='': |
|
627 | 629 | warn("Could not start with profile '%s'!\n ('%s/%s.py' does not exist? run '%%upgrade')" % ( |
|
628 | 630 | opts_all.profile, ipythondir, profmodname) |
|
629 | 631 | |
|
630 | 632 | ) |
|
631 | 633 | except: |
|
632 | 634 | print "Error importing",profmodname |
|
633 | 635 | IP.InteractiveTB() |
|
634 | 636 | import_fail_info(profmodname) |
|
635 | 637 | |
|
636 | 638 | try: |
|
637 | 639 | import ipy_user_conf |
|
638 | 640 | except ImportError: |
|
639 | 641 | if opts_all.debug: IP.InteractiveTB() |
|
640 | 642 | warn("Could not import user config!\n ('%s/ipy_user_conf.py' does not exist? Please run '%%upgrade')\n" % |
|
641 | 643 | ipythondir) |
|
642 | 644 | except: |
|
643 | 645 | print "Error importing ipy_user_conf" |
|
644 | 646 | IP.InteractiveTB() |
|
645 | 647 | import_fail_info("ipy_user_conf") |
|
646 | 648 | |
|
647 | 649 | |
|
648 | 650 | # release stdout and stderr and save config log into a global summary |
|
649 | 651 | msg.config.release_all() |
|
650 | 652 | if IP_rc.messages: |
|
651 | 653 | msg.summary += msg.config.summary_all() |
|
652 | 654 | |
|
653 | 655 | #------------------------------------------------------------------------ |
|
654 | 656 | # Setup interactive session |
|
655 | 657 | |
|
656 | 658 | # Now we should be fully configured. We can then execute files or load |
|
657 | 659 | # things only needed for interactive use. Then we'll open the shell. |
|
658 | 660 | |
|
659 | 661 | # Take a snapshot of the user namespace before opening the shell. That way |
|
660 | 662 | # we'll be able to identify which things were interactively defined and |
|
661 | 663 | # which were defined through config files. |
|
662 | 664 | IP.user_config_ns = IP.user_ns.copy() |
|
663 | 665 | |
|
664 | 666 | # Force reading a file as if it were a session log. Slower but safer. |
|
665 | 667 | if load_logplay: |
|
666 | 668 | print 'Replaying log...' |
|
667 | 669 | try: |
|
668 | 670 | if IP_rc.debug: |
|
669 | 671 | logplay_quiet = 0 |
|
670 | 672 | else: |
|
671 | 673 | logplay_quiet = 1 |
|
672 | 674 | |
|
673 | 675 | msg.logplay.trap_all() |
|
674 | 676 | IP.safe_execfile(load_logplay,IP.user_ns, |
|
675 | 677 | islog = 1, quiet = logplay_quiet) |
|
676 | 678 | msg.logplay.release_all() |
|
677 | 679 | if IP_rc.messages: |
|
678 | 680 | msg.summary += msg.logplay.summary_all() |
|
679 | 681 | except: |
|
680 | 682 | warn('Problems replaying logfile %s.' % load_logplay) |
|
681 | 683 | IP.InteractiveTB() |
|
682 | 684 | |
|
683 | 685 | # Load remaining files in command line |
|
684 | 686 | msg.user_exec.trap_all() |
|
685 | 687 | |
|
686 | 688 | # Do NOT execute files named in the command line as scripts to be loaded |
|
687 | 689 | # by embedded instances. Doing so has the potential for an infinite |
|
688 | 690 | # recursion if there are exceptions thrown in the process. |
|
689 | 691 | |
|
690 | 692 | # XXX FIXME: the execution of user files should be moved out to after |
|
691 | 693 | # ipython is fully initialized, just as if they were run via %run at the |
|
692 | 694 | # ipython prompt. This would also give them the benefit of ipython's |
|
693 | 695 | # nice tracebacks. |
|
694 | 696 | |
|
695 | 697 | if (not embedded and IP_rc.args and |
|
696 | 698 | not IP_rc.args[0].lower().endswith('.ipy')): |
|
697 | 699 | name_save = IP.user_ns['__name__'] |
|
698 | 700 | IP.user_ns['__name__'] = '__main__' |
|
699 | 701 | # Set our own excepthook in case the user code tries to call it |
|
700 | 702 | # directly. This prevents triggering the IPython crash handler. |
|
701 | 703 | old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook |
|
702 | 704 | |
|
703 | 705 | save_argv = sys.argv[:] # save it for later restoring |
|
704 | 706 | |
|
705 | 707 | sys.argv = args |
|
706 | 708 | |
|
707 | 709 | try: |
|
708 | 710 | IP.safe_execfile(args[0], IP.user_ns) |
|
709 | 711 | finally: |
|
710 | 712 | # Reset our crash handler in place |
|
711 | 713 | sys.excepthook = old_excepthook |
|
712 | 714 | sys.argv = save_argv |
|
713 | 715 | IP.user_ns['__name__'] = name_save |
|
714 | 716 | |
|
715 | 717 | msg.user_exec.release_all() |
|
716 | 718 | if IP_rc.messages: |
|
717 | 719 | msg.summary += msg.user_exec.summary_all() |
|
718 | 720 | |
|
719 | 721 | # since we can't specify a null string on the cmd line, 0 is the equivalent: |
|
720 | 722 | if IP_rc.nosep: |
|
721 | 723 | IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0' |
|
722 | 724 | if IP_rc.separate_in == '0': IP_rc.separate_in = '' |
|
723 | 725 | if IP_rc.separate_out == '0': IP_rc.separate_out = '' |
|
724 | 726 | if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = '' |
|
725 | 727 | IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n') |
|
726 | 728 | IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n') |
|
727 | 729 | IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n') |
|
728 | 730 | |
|
729 | 731 | # Determine how many lines at the bottom of the screen are needed for |
|
730 | 732 | # showing prompts, so we can know wheter long strings are to be printed or |
|
731 | 733 | # paged: |
|
732 | 734 | num_lines_bot = IP_rc.separate_in.count('\n')+1 |
|
733 | 735 | IP_rc.screen_length = IP_rc.screen_length - num_lines_bot |
|
734 | 736 | |
|
735 | 737 | # configure startup banner |
|
736 | 738 | if IP_rc.c: # regular python doesn't print the banner with -c |
|
737 | 739 | IP_rc.banner = 0 |
|
738 | 740 | if IP_rc.banner: |
|
739 | 741 | BANN_P = IP.BANNER_PARTS |
|
740 | 742 | else: |
|
741 | 743 | BANN_P = [] |
|
742 | 744 | |
|
743 | 745 | if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile) |
|
744 | 746 | |
|
745 | 747 | # add message log (possibly empty) |
|
746 | 748 | if msg.summary: BANN_P.append(msg.summary) |
|
747 | 749 | # Final banner is a string |
|
748 | 750 | IP.BANNER = '\n'.join(BANN_P) |
|
749 | 751 | |
|
750 | 752 | # Finalize the IPython instance. This assumes the rc structure is fully |
|
751 | 753 | # in place. |
|
752 | 754 | IP.post_config_initialization() |
|
753 | 755 | |
|
754 | 756 | return IP |
|
755 | 757 | #************************ end of file <ipmaker.py> ************************** |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
General Comments 0
You need to be logged in to leave comments.
Login now