##// END OF EJS Templates
Fix bug where output prompts were coming *after* output values....
Fernando Perez -
Show More
@@ -1,635 +1,637 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 Classes for handling input/output prompts.
4 4 """
5 5
6 6 #*****************************************************************************
7 7 # Copyright (C) 2008-2009 The IPython Development Team
8 8 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
9 9 #
10 10 # Distributed under the terms of the BSD License. The full license is in
11 11 # the file COPYING, distributed as part of this software.
12 12 #*****************************************************************************
13 13
14 14 #****************************************************************************
15 15 # Required modules
16 16 import __builtin__
17 17 import os
18 18 import socket
19 19 import sys
20 20 import time
21 21
22 22 # IPython's own
23 23 from IPython.utils import coloransi
24 24 from IPython.core import release
25 25 from IPython.external.Itpl import ItplNS
26 26 from IPython.core.error import TryNext
27 27 from IPython.utils.ipstruct import Struct
28 28 from IPython.core.macro import Macro
29 29 import IPython.utils.generics
30 30
31 31 from IPython.utils.genutils import *
32 32
33 33 #****************************************************************************
34 34 #Color schemes for Prompts.
35 35
36 36 PromptColors = coloransi.ColorSchemeTable()
37 37 InputColors = coloransi.InputTermColors # just a shorthand
38 38 Colors = coloransi.TermColors # just a shorthand
39 39
40 40 PromptColors.add_scheme(coloransi.ColorScheme(
41 41 'NoColor',
42 42 in_prompt = InputColors.NoColor, # Input prompt
43 43 in_number = InputColors.NoColor, # Input prompt number
44 44 in_prompt2 = InputColors.NoColor, # Continuation prompt
45 45 in_normal = InputColors.NoColor, # color off (usu. Colors.Normal)
46 46
47 47 out_prompt = Colors.NoColor, # Output prompt
48 48 out_number = Colors.NoColor, # Output prompt number
49 49
50 50 normal = Colors.NoColor # color off (usu. Colors.Normal)
51 51 ))
52 52
53 53 # make some schemes as instances so we can copy them for modification easily:
54 54 __PColLinux = coloransi.ColorScheme(
55 55 'Linux',
56 56 in_prompt = InputColors.Green,
57 57 in_number = InputColors.LightGreen,
58 58 in_prompt2 = InputColors.Green,
59 59 in_normal = InputColors.Normal, # color off (usu. Colors.Normal)
60 60
61 61 out_prompt = Colors.Red,
62 62 out_number = Colors.LightRed,
63 63
64 64 normal = Colors.Normal
65 65 )
66 66 # Don't forget to enter it into the table!
67 67 PromptColors.add_scheme(__PColLinux)
68 68
69 69 # Slightly modified Linux for light backgrounds
70 70 __PColLightBG = __PColLinux.copy('LightBG')
71 71
72 72 __PColLightBG.colors.update(
73 73 in_prompt = InputColors.Blue,
74 74 in_number = InputColors.LightBlue,
75 75 in_prompt2 = InputColors.Blue
76 76 )
77 77 PromptColors.add_scheme(__PColLightBG)
78 78
79 79 del Colors,InputColors
80 80
81 81 #-----------------------------------------------------------------------------
82 82 def multiple_replace(dict, text):
83 83 """ Replace in 'text' all occurences of any key in the given
84 84 dictionary by its corresponding value. Returns the new string."""
85 85
86 86 # Function by Xavier Defrang, originally found at:
87 87 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330
88 88
89 89 # Create a regular expression from the dictionary keys
90 90 regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
91 91 # For each match, look-up corresponding value in dictionary
92 92 return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
93 93
94 94 #-----------------------------------------------------------------------------
95 95 # Special characters that can be used in prompt templates, mainly bash-like
96 96
97 97 # If $HOME isn't defined (Windows), make it an absurd string so that it can
98 98 # never be expanded out into '~'. Basically anything which can never be a
99 99 # reasonable directory name will do, we just want the $HOME -> '~' operation
100 100 # to become a no-op. We pre-compute $HOME here so it's not done on every
101 101 # prompt call.
102 102
103 103 # FIXME:
104 104
105 105 # - This should be turned into a class which does proper namespace management,
106 106 # since the prompt specials need to be evaluated in a certain namespace.
107 107 # Currently it's just globals, which need to be managed manually by code
108 108 # below.
109 109
110 110 # - I also need to split up the color schemes from the prompt specials
111 111 # somehow. I don't have a clean design for that quite yet.
112 112
113 113 HOME = os.environ.get("HOME","//////:::::ZZZZZ,,,~~~")
114 114
115 115 # We precompute a few more strings here for the prompt_specials, which are
116 116 # fixed once ipython starts. This reduces the runtime overhead of computing
117 117 # prompt strings.
118 118 USER = os.environ.get("USER")
119 119 HOSTNAME = socket.gethostname()
120 120 HOSTNAME_SHORT = HOSTNAME.split(".")[0]
121 121 ROOT_SYMBOL = "$#"[os.name=='nt' or os.getuid()==0]
122 122
123 123 prompt_specials_color = {
124 124 # Prompt/history count
125 125 '%n' : '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
126 126 r'\#': '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
127 127 # Just the prompt counter number, WITHOUT any coloring wrappers, so users
128 128 # can get numbers displayed in whatever color they want.
129 129 r'\N': '${self.cache.prompt_count}',
130 130
131 131 # Prompt/history count, with the actual digits replaced by dots. Used
132 132 # mainly in continuation prompts (prompt_in2)
133 133 #r'\D': '${"."*len(str(self.cache.prompt_count))}',
134 134 # More robust form of the above expression, that uses __builtins__
135 135 r'\D': '${"."*__builtins__.len(__builtins__.str(self.cache.prompt_count))}',
136 136
137 137 # Current working directory
138 138 r'\w': '${os.getcwd()}',
139 139 # Current time
140 140 r'\t' : '${time.strftime("%H:%M:%S")}',
141 141 # Basename of current working directory.
142 142 # (use os.sep to make this portable across OSes)
143 143 r'\W' : '${os.getcwd().split("%s")[-1]}' % os.sep,
144 144 # These X<N> are an extension to the normal bash prompts. They return
145 145 # N terms of the path, after replacing $HOME with '~'
146 146 r'\X0': '${os.getcwd().replace("%s","~")}' % HOME,
147 147 r'\X1': '${self.cwd_filt(1)}',
148 148 r'\X2': '${self.cwd_filt(2)}',
149 149 r'\X3': '${self.cwd_filt(3)}',
150 150 r'\X4': '${self.cwd_filt(4)}',
151 151 r'\X5': '${self.cwd_filt(5)}',
152 152 # Y<N> are similar to X<N>, but they show '~' if it's the directory
153 153 # N+1 in the list. Somewhat like %cN in tcsh.
154 154 r'\Y0': '${self.cwd_filt2(0)}',
155 155 r'\Y1': '${self.cwd_filt2(1)}',
156 156 r'\Y2': '${self.cwd_filt2(2)}',
157 157 r'\Y3': '${self.cwd_filt2(3)}',
158 158 r'\Y4': '${self.cwd_filt2(4)}',
159 159 r'\Y5': '${self.cwd_filt2(5)}',
160 160 # Hostname up to first .
161 161 r'\h': HOSTNAME_SHORT,
162 162 # Full hostname
163 163 r'\H': HOSTNAME,
164 164 # Username of current user
165 165 r'\u': USER,
166 166 # Escaped '\'
167 167 '\\\\': '\\',
168 168 # Newline
169 169 r'\n': '\n',
170 170 # Carriage return
171 171 r'\r': '\r',
172 172 # Release version
173 173 r'\v': release.version,
174 174 # Root symbol ($ or #)
175 175 r'\$': ROOT_SYMBOL,
176 176 }
177 177
178 178 # A copy of the prompt_specials dictionary but with all color escapes removed,
179 179 # so we can correctly compute the prompt length for the auto_rewrite method.
180 180 prompt_specials_nocolor = prompt_specials_color.copy()
181 181 prompt_specials_nocolor['%n'] = '${self.cache.prompt_count}'
182 182 prompt_specials_nocolor[r'\#'] = '${self.cache.prompt_count}'
183 183
184 184 # Add in all the InputTermColors color escapes as valid prompt characters.
185 185 # They all get added as \\C_COLORNAME, so that we don't have any conflicts
186 186 # with a color name which may begin with a letter used by any other of the
187 187 # allowed specials. This of course means that \\C will never be allowed for
188 188 # anything else.
189 189 input_colors = coloransi.InputTermColors
190 190 for _color in dir(input_colors):
191 191 if _color[0] != '_':
192 192 c_name = r'\C_'+_color
193 193 prompt_specials_color[c_name] = getattr(input_colors,_color)
194 194 prompt_specials_nocolor[c_name] = ''
195 195
196 196 # we default to no color for safety. Note that prompt_specials is a global
197 197 # variable used by all prompt objects.
198 198 prompt_specials = prompt_specials_nocolor
199 199
200 200 #-----------------------------------------------------------------------------
201 201 def str_safe(arg):
202 202 """Convert to a string, without ever raising an exception.
203 203
204 204 If str(arg) fails, <ERROR: ... > is returned, where ... is the exception
205 205 error message."""
206 206
207 207 try:
208 208 out = str(arg)
209 209 except UnicodeError:
210 210 try:
211 211 out = arg.encode('utf_8','replace')
212 212 except Exception,msg:
213 213 # let's keep this little duplication here, so that the most common
214 214 # case doesn't suffer from a double try wrapping.
215 215 out = '<ERROR: %s>' % msg
216 216 except Exception,msg:
217 217 out = '<ERROR: %s>' % msg
218 218 return out
219 219
220 220 class BasePrompt(object):
221 221 """Interactive prompt similar to Mathematica's."""
222 222
223 223 def _get_p_template(self):
224 224 return self._p_template
225 225
226 226 def _set_p_template(self,val):
227 227 self._p_template = val
228 228 self.set_p_str()
229 229
230 230 p_template = property(_get_p_template,_set_p_template,
231 231 doc='Template for prompt string creation')
232 232
233 233 def __init__(self,cache,sep,prompt,pad_left=False):
234 234
235 235 # Hack: we access information about the primary prompt through the
236 236 # cache argument. We need this, because we want the secondary prompt
237 237 # to be aligned with the primary one. Color table info is also shared
238 238 # by all prompt classes through the cache. Nice OO spaghetti code!
239 239 self.cache = cache
240 240 self.sep = sep
241 241
242 242 # regexp to count the number of spaces at the end of a prompt
243 243 # expression, useful for prompt auto-rewriting
244 244 self.rspace = re.compile(r'(\s*)$')
245 245 # Flag to left-pad prompt strings to match the length of the primary
246 246 # prompt
247 247 self.pad_left = pad_left
248 248
249 249 # Set template to create each actual prompt (where numbers change).
250 250 # Use a property
251 251 self.p_template = prompt
252 252 self.set_p_str()
253 253
254 254 def set_p_str(self):
255 255 """ Set the interpolating prompt strings.
256 256
257 257 This must be called every time the color settings change, because the
258 258 prompt_specials global may have changed."""
259 259
260 260 import os,time # needed in locals for prompt string handling
261 261 loc = locals()
262 262 try:
263 263 self.p_str = ItplNS('%s%s%s' %
264 264 ('${self.sep}${self.col_p}',
265 265 multiple_replace(prompt_specials, self.p_template),
266 266 '${self.col_norm}'),self.cache.user_ns,loc)
267 267
268 268 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
269 269 self.p_template),
270 270 self.cache.user_ns,loc)
271 271 except:
272 272 print "Illegal prompt template (check $ usage!):",self.p_template
273 273 self.p_str = self.p_template
274 274 self.p_str_nocolor = self.p_template
275 275
276 276 def write(self,msg): # dbg
277 277 sys.stdout.write(msg)
278 278 return ''
279 279
280 280 def __str__(self):
281 281 """Return a string form of the prompt.
282 282
283 283 This for is useful for continuation and output prompts, since it is
284 284 left-padded to match lengths with the primary one (if the
285 285 self.pad_left attribute is set)."""
286 286
287 287 out_str = str_safe(self.p_str)
288 288 if self.pad_left:
289 289 # We must find the amount of padding required to match lengths,
290 290 # taking the color escapes (which are invisible on-screen) into
291 291 # account.
292 292 esc_pad = len(out_str) - len(str_safe(self.p_str_nocolor))
293 293 format = '%%%ss' % (len(str(self.cache.last_prompt))+esc_pad)
294 294 return format % out_str
295 295 else:
296 296 return out_str
297 297
298 298 # these path filters are put in as methods so that we can control the
299 299 # namespace where the prompt strings get evaluated
300 300 def cwd_filt(self,depth):
301 301 """Return the last depth elements of the current working directory.
302 302
303 303 $HOME is always replaced with '~'.
304 304 If depth==0, the full path is returned."""
305 305
306 306 cwd = os.getcwd().replace(HOME,"~")
307 307 out = os.sep.join(cwd.split(os.sep)[-depth:])
308 308 if out:
309 309 return out
310 310 else:
311 311 return os.sep
312 312
313 313 def cwd_filt2(self,depth):
314 314 """Return the last depth elements of the current working directory.
315 315
316 316 $HOME is always replaced with '~'.
317 317 If depth==0, the full path is returned."""
318 318
319 319 full_cwd = os.getcwd()
320 320 cwd = full_cwd.replace(HOME,"~").split(os.sep)
321 321 if '~' in cwd and len(cwd) == depth+1:
322 322 depth += 1
323 323 drivepart = ''
324 324 if sys.platform == 'win32' and len(cwd) > depth:
325 325 drivepart = os.path.splitdrive(full_cwd)[0]
326 326 out = drivepart + '/'.join(cwd[-depth:])
327 327
328 328 if out:
329 329 return out
330 330 else:
331 331 return os.sep
332 332
333 333 def __nonzero__(self):
334 334 """Implement boolean behavior.
335 335
336 336 Checks whether the p_str attribute is non-empty"""
337 337
338 338 return bool(self.p_template)
339 339
340 340 class Prompt1(BasePrompt):
341 341 """Input interactive prompt similar to Mathematica's."""
342 342
343 343 def __init__(self,cache,sep='\n',prompt='In [\\#]: ',pad_left=True):
344 344 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
345 345
346 346 def set_colors(self):
347 347 self.set_p_str()
348 348 Colors = self.cache.color_table.active_colors # shorthand
349 349 self.col_p = Colors.in_prompt
350 350 self.col_num = Colors.in_number
351 351 self.col_norm = Colors.in_normal
352 352 # We need a non-input version of these escapes for the '--->'
353 353 # auto-call prompts used in the auto_rewrite() method.
354 354 self.col_p_ni = self.col_p.replace('\001','').replace('\002','')
355 355 self.col_norm_ni = Colors.normal
356 356
357 357 def __str__(self):
358 358 self.cache.prompt_count += 1
359 359 self.cache.last_prompt = str_safe(self.p_str_nocolor).split('\n')[-1]
360 360 return str_safe(self.p_str)
361 361
362 362 def auto_rewrite(self):
363 363 """Print a string of the form '--->' which lines up with the previous
364 364 input string. Useful for systems which re-write the user input when
365 365 handling automatically special syntaxes."""
366 366
367 367 curr = str(self.cache.last_prompt)
368 368 nrspaces = len(self.rspace.search(curr).group())
369 369 return '%s%s>%s%s' % (self.col_p_ni,'-'*(len(curr)-nrspaces-1),
370 370 ' '*nrspaces,self.col_norm_ni)
371 371
372 372 class PromptOut(BasePrompt):
373 373 """Output interactive prompt similar to Mathematica's."""
374 374
375 375 def __init__(self,cache,sep='',prompt='Out[\\#]: ',pad_left=True):
376 376 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
377 377 if not self.p_template:
378 378 self.__str__ = lambda: ''
379 379
380 380 def set_colors(self):
381 381 self.set_p_str()
382 382 Colors = self.cache.color_table.active_colors # shorthand
383 383 self.col_p = Colors.out_prompt
384 384 self.col_num = Colors.out_number
385 385 self.col_norm = Colors.normal
386 386
387 387 class Prompt2(BasePrompt):
388 388 """Interactive continuation prompt."""
389 389
390 390 def __init__(self,cache,prompt=' .\\D.: ',pad_left=True):
391 391 self.cache = cache
392 392 self.p_template = prompt
393 393 self.pad_left = pad_left
394 394 self.set_p_str()
395 395
396 396 def set_p_str(self):
397 397 import os,time # needed in locals for prompt string handling
398 398 loc = locals()
399 399 self.p_str = ItplNS('%s%s%s' %
400 400 ('${self.col_p2}',
401 401 multiple_replace(prompt_specials, self.p_template),
402 402 '$self.col_norm'),
403 403 self.cache.user_ns,loc)
404 404 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
405 405 self.p_template),
406 406 self.cache.user_ns,loc)
407 407
408 408 def set_colors(self):
409 409 self.set_p_str()
410 410 Colors = self.cache.color_table.active_colors
411 411 self.col_p2 = Colors.in_prompt2
412 412 self.col_norm = Colors.in_normal
413 413 # FIXME (2004-06-16) HACK: prevent crashes for users who haven't
414 414 # updated their prompt_in2 definitions. Remove eventually.
415 415 self.col_p = Colors.out_prompt
416 416 self.col_num = Colors.out_number
417 417
418 418
419 419 #-----------------------------------------------------------------------------
420 420 class CachedOutput:
421 421 """Class for printing output from calculations while keeping a cache of
422 422 reults. It dynamically creates global variables prefixed with _ which
423 423 contain these results.
424 424
425 425 Meant to be used as a sys.displayhook replacement, providing numbered
426 426 prompts and cache services.
427 427
428 428 Initialize with initial and final values for cache counter (this defines
429 429 the maximum size of the cache."""
430 430
431 431 def __init__(self,shell,cache_size,Pprint,
432 432 colors='NoColor',input_sep='\n',
433 433 output_sep='\n',output_sep2='',
434 434 ps1 = None, ps2 = None,ps_out = None,pad_left=True):
435 435
436 436 cache_size_min = 3
437 437 if cache_size <= 0:
438 438 self.do_full_cache = 0
439 439 cache_size = 0
440 440 elif cache_size < cache_size_min:
441 441 self.do_full_cache = 0
442 442 cache_size = 0
443 443 warn('caching was disabled (min value for cache size is %s).' %
444 444 cache_size_min,level=3)
445 445 else:
446 446 self.do_full_cache = 1
447 447
448 448 self.cache_size = cache_size
449 449 self.input_sep = input_sep
450 450
451 451 # we need a reference to the user-level namespace
452 452 self.shell = shell
453 453 self.user_ns = shell.user_ns
454 454 # and to the user's input
455 455 self.input_hist = shell.input_hist
456 456 # and to the user's logger, for logging output
457 457 self.logger = shell.logger
458 458
459 459 # Set input prompt strings and colors
460 460 if cache_size == 0:
461 461 if ps1.find('%n') > -1 or ps1.find(r'\#') > -1 \
462 462 or ps1.find(r'\N') > -1:
463 463 ps1 = '>>> '
464 464 if ps2.find('%n') > -1 or ps2.find(r'\#') > -1 \
465 465 or ps2.find(r'\N') > -1:
466 466 ps2 = '... '
467 467 self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
468 468 self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
469 469 self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
470 470
471 471 self.color_table = PromptColors
472 472 self.prompt1 = Prompt1(self,sep=input_sep,prompt=self.ps1_str,
473 473 pad_left=pad_left)
474 474 self.prompt2 = Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
475 475 self.prompt_out = PromptOut(self,sep='',prompt=self.ps_out_str,
476 476 pad_left=pad_left)
477 477 self.set_colors(colors)
478 478
479 479 # other more normal stuff
480 480 # b/c each call to the In[] prompt raises it by 1, even the first.
481 481 self.prompt_count = 0
482 482 # Store the last prompt string each time, we need it for aligning
483 483 # continuation and auto-rewrite prompts
484 484 self.last_prompt = ''
485 485 self.Pprint = Pprint
486 486 self.output_sep = output_sep
487 487 self.output_sep2 = output_sep2
488 488 self._,self.__,self.___ = '','',''
489 489 self.pprint_types = map(type,[(),[],{}])
490 490
491 491 # these are deliberately global:
492 492 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
493 493 self.user_ns.update(to_user_ns)
494 494
495 495 def _set_prompt_str(self,p_str,cache_def,no_cache_def):
496 496 if p_str is None:
497 497 if self.do_full_cache:
498 498 return cache_def
499 499 else:
500 500 return no_cache_def
501 501 else:
502 502 return p_str
503 503
504 504 def set_colors(self,colors):
505 505 """Set the active color scheme and configure colors for the three
506 506 prompt subsystems."""
507 507
508 508 # FIXME: the prompt_specials global should be gobbled inside this
509 509 # class instead. Do it when cleaning up the whole 3-prompt system.
510 510 global prompt_specials
511 511 if colors.lower()=='nocolor':
512 512 prompt_specials = prompt_specials_nocolor
513 513 else:
514 514 prompt_specials = prompt_specials_color
515 515
516 516 self.color_table.set_active_scheme(colors)
517 517 self.prompt1.set_colors()
518 518 self.prompt2.set_colors()
519 519 self.prompt_out.set_colors()
520 520
521 521 def __call__(self,arg=None):
522 522 """Printing with history cache management.
523 523
524 524 This is invoked everytime the interpreter needs to print, and is
525 525 activated by setting the variable sys.displayhook to it."""
526 526
527 527 # If something injected a '_' variable in __builtin__, delete
528 528 # ipython's automatic one so we don't clobber that. gettext() in
529 529 # particular uses _, so we need to stay away from it.
530 530 if '_' in __builtin__.__dict__:
531 531 try:
532 532 del self.user_ns['_']
533 533 except KeyError:
534 534 pass
535 535 if arg is not None:
536
537 # and now call a possibly user-defined print mechanism
538 try:
539 manipulated_val = self.display(arg)
540 except TypeError:
541 # If the user's display hook didn't return a string we can
542 # print, we're done. Happens commonly if they return None
543 return
544
545 # user display hooks can change the variable to be stored in
546 # output history
547 if manipulated_val is not None:
548 arg = manipulated_val
549
550 536 cout_write = Term.cout.write # fast lookup
551 537 # first handle the cache and counters
552 538
553 539 # do not print output if input ends in ';'
554 540 try:
555 541 if self.input_hist[self.prompt_count].endswith(';\n'):
556 542 return
557 543 except IndexError:
558 544 # some uses of ipshellembed may fail here
559 545 pass
560 546 # don't use print, puts an extra space
561 547 cout_write(self.output_sep)
562 548 outprompt = self.shell.hooks.generate_output_prompt()
563 549 # print "Got prompt: ", outprompt
564 550 if self.do_full_cache:
565 551 cout_write(outprompt)
566 552 else:
567 553 print "self.do_full_cache = False"
568 554
555 # and now call a possibly user-defined print mechanism. Note that
556 # self.display typically prints as a side-effect, we don't do any
557 # printing to stdout here.
558 try:
559 manipulated_val = self.display(arg)
560 except TypeError:
561 # If the user's display hook didn't return a string we can
562 # print, we're done. Happens commonly if they return None
563 cout_write('\n')
564 return
565
566 # user display hooks can change the variable to be stored in
567 # output history
568 if manipulated_val is not None:
569 arg = manipulated_val
570
569 571 # avoid recursive reference when displaying _oh/Out
570 572 if arg is not self.user_ns['_oh']:
571 573 self.update(arg)
572 574
573 575 if self.logger.log_output:
574 576 self.logger.log_write(repr(arg),'output')
575 577 cout_write(self.output_sep2)
576 578 Term.cout.flush()
577 579
578 580 def _display(self,arg):
579 581 """Default printer method, uses pprint.
580 582
581 583 Do ip.set_hook("result_display", my_displayhook) for custom result
582 584 display, e.g. when your own objects need special formatting.
583 585 """
584 586 try:
585 587 return IPython.utils.generics.result_display(arg)
586 588 except TryNext:
587 589 return self.shell.hooks.result_display(arg)
588 590
589 591 # Assign the default display method:
590 592 display = _display
591 593
592 594 def update(self,arg):
593 595 #print '***cache_count', self.cache_count # dbg
594 596 if len(self.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
595 597 warn('Output cache limit (currently '+
596 598 `self.cache_size`+' entries) hit.\n'
597 599 'Flushing cache and resetting history counter...\n'
598 600 'The only history variables available will be _,__,___ and _1\n'
599 601 'with the current result.')
600 602
601 603 self.flush()
602 604 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
603 605 # we cause buggy behavior for things like gettext).
604 606 if '_' not in __builtin__.__dict__:
605 607 self.___ = self.__
606 608 self.__ = self._
607 609 self._ = arg
608 610 self.user_ns.update({'_':self._,'__':self.__,'___':self.___})
609 611
610 612 # hackish access to top-level namespace to create _1,_2... dynamically
611 613 to_main = {}
612 614 if self.do_full_cache:
613 615 new_result = '_'+`self.prompt_count`
614 616 to_main[new_result] = arg
615 617 self.user_ns.update(to_main)
616 618 self.user_ns['_oh'][self.prompt_count] = arg
617 619
618 620 def flush(self):
619 621 if not self.do_full_cache:
620 622 raise ValueError,"You shouldn't have reached the cache flush "\
621 623 "if full caching is not enabled!"
622 624 # delete auto-generated vars from global namespace
623 625
624 626 for n in range(1,self.prompt_count + 1):
625 627 key = '_'+`n`
626 628 try:
627 629 del self.user_ns[key]
628 630 except: pass
629 631 self.user_ns['_oh'].clear()
630 632
631 633 if '_' not in __builtin__.__dict__:
632 634 self.user_ns.update({'_':None,'__':None, '___':None})
633 635 import gc
634 636 gc.collect() # xxx needed?
635 637
@@ -1,40 +1,41 b''
1 1 # coding: utf-8
2 2 """
3 3 A simple class for quitting IPython.
4 4
5 5 Authors
6 6 -------
7 7 * Fernando Perez
8 8 * Brian Granger
9 9 """
10 10
11 11 #-----------------------------------------------------------------------------
12 12 # Copyright (C) 2008-2009 The IPython Development Team
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 #-----------------------------------------------------------------------------
19 19 # Imports
20 20 #-----------------------------------------------------------------------------
21 21
22 22 import sys
23 23
24 24 class Quitter(object):
25 25 """Simple class to handle exit, similar to Python 2.5's.
26 26
27 27 It handles exiting in an ipython-safe manner, which the one in Python 2.5
28 28 doesn't do (obviously, since it doesn't know about ipython)."""
29 29
30 30 def __init__(self, shell, name):
31 31 self.shell = shell
32 32 self.name = name
33 33
34 34 def __str__(self):
35 35 return 'Type %s() to exit.' % self.name
36 36
37 37 def __call__(self):
38 38 self.shell.ask_exit()
39 return 'Bye.'
39 40
40 41 __repr__ = __call__
General Comments 0
You need to be logged in to leave comments. Login now