##// END OF EJS Templates
Reworking magic %hist, %macro and %edit commands to work with new history system.
Thomas Kluyver -
Show More
@@ -1,589 +1,592 b''
1 1 """ History related magics and functionality """
2 2 #-----------------------------------------------------------------------------
3 3 # Copyright (C) 2010 The IPython Development Team.
4 4 #
5 5 # Distributed under the terms of the BSD License.
6 6 #
7 7 # The full license is in the file COPYING.txt, distributed with this software.
8 8 #-----------------------------------------------------------------------------
9 9
10 10 #-----------------------------------------------------------------------------
11 11 # Imports
12 12 #-----------------------------------------------------------------------------
13 13 from __future__ import print_function
14 14
15 15 # Stdlib imports
16 16 import atexit
17 17 import fnmatch
18 18 import json
19 19 import os
20 20 import sys
21 21 import threading
22 22 import time
23 23
24 24 # Our own packages
25 25 import IPython.utils.io
26 26
27 27 from IPython.testing import decorators as testdec
28 28 from IPython.utils.pickleshare import PickleShareDB
29 29 from IPython.utils.io import ask_yes_no
30 30 from IPython.utils.warn import warn
31 31
32 32 #-----------------------------------------------------------------------------
33 33 # Classes and functions
34 34 #-----------------------------------------------------------------------------
35 35
36 36 class HistoryManager(object):
37 37 """A class to organize all history-related functionality in one place.
38 38 """
39 39 # Public interface
40 40
41 41 # An instance of the IPython shell we are attached to
42 42 shell = None
43 43 # A list to hold processed history
44 44 input_hist_parsed = None
45 45 # A list to hold raw history (as typed by user)
46 46 input_hist_raw = None
47 47 # A list of directories visited during session
48 48 dir_hist = None
49 49 # A dict of output history, keyed with ints from the shell's execution count
50 50 output_hist = None
51 51 # String with path to the history file
52 52 hist_file = None
53 53 # PickleShareDB instance holding the raw data for the shadow history
54 54 shadow_db = None
55 55 # ShadowHist instance with the actual shadow history
56 56 shadow_hist = None
57 57
58 58 # Private interface
59 59 # Variables used to store the three last inputs from the user. On each new
60 60 # history update, we populate the user's namespace with these, shifted as
61 61 # necessary.
62 62 _i00, _i, _ii, _iii = '','','',''
63 63
64 64 # A set with all forms of the exit command, so that we don't store them in
65 65 # the history (it's annoying to rewind the first entry and land on an exit
66 66 # call).
67 67 _exit_commands = None
68 68
69 def __init__(self, shell):
69 def __init__(self, shell, load_history=False):
70 70 """Create a new history manager associated with a shell instance.
71
72 If load_history is true, it will load the history from file and set the
73 session offset so that the next line typed can be retrieved as #1.
71 74 """
72 75 # We need a pointer back to the shell for various tasks.
73 76 self.shell = shell
74 77
75 78 # List of input with multi-line handling.
76 79 self.input_hist_parsed = []
77 80 # This one will hold the 'raw' input history, without any
78 81 # pre-processing. This will allow users to retrieve the input just as
79 82 # it was exactly typed in by the user, with %hist -r.
80 83 self.input_hist_raw = []
84
85 # Offset so the first line of the current session is #1
86 self.session_offset = -1
81 87
82 88 # list of visited directories
83 89 try:
84 90 self.dir_hist = [os.getcwd()]
85 91 except OSError:
86 92 self.dir_hist = []
87 93
88 94 # dict of output history
89 95 self.output_hist = {}
90 96
91 97 # Now the history file
92 98 if shell.profile:
93 99 histfname = 'history-%s' % shell.profile
94 100 else:
95 101 histfname = 'history'
96 102 self.hist_file = os.path.join(shell.ipython_dir, histfname + '.json')
97 103
98 104 # Objects related to shadow history management
99 105 self._init_shadow_hist()
100 106
101 107 self._i00, self._i, self._ii, self._iii = '','','',''
102 108
103 109 self._exit_commands = set(['Quit', 'quit', 'Exit', 'exit', '%Quit',
104 110 '%quit', '%Exit', '%exit'])
105 111
106 112 # Object is fully initialized, we can now call methods on it.
107 113
108 # Fill the history zero entry, user counter starts at 1
109 self.store_inputs('\n', '\n')
114 if load_history:
115 self.reload_history()
116 self.session_offset = len(self.input_hist_raw) -1
110 117
111 118 # Create and start the autosaver.
112 119 self.autosave_flag = threading.Event()
113 120 self.autosave_timer = HistorySaveThread(self.autosave_flag, 60)
114 121 self.autosave_timer.start()
115 122 # Register the autosave handler to be triggered as a post execute
116 123 # callback.
117 124 self.shell.register_post_execute(self.autosave_if_due)
125
118 126
119 127 def _init_shadow_hist(self):
120 128 try:
121 129 self.shadow_db = PickleShareDB(os.path.join(
122 130 self.shell.ipython_dir, 'db'))
123 131 except UnicodeDecodeError:
124 132 print("Your ipython_dir can't be decoded to unicode!")
125 133 print("Please set HOME environment variable to something that")
126 134 print(r"only has ASCII characters, e.g. c:\home")
127 135 print("Now it is", self.ipython_dir)
128 136 sys.exit()
129 137 self.shadow_hist = ShadowHist(self.shadow_db, self.shell)
130 138
131 139 def populate_readline_history(self):
132 140 """Populate the readline history from the raw history.
133 141
134 142 We only store one copy of the raw history, which is persisted to a json
135 143 file on disk. The readline history is repopulated from the contents of
136 144 this file."""
137 145
138 146 try:
139 147 self.shell.readline.clear_history()
140 148 except AttributeError:
141 149 pass
142 150 else:
143 151 for h in self.input_hist_raw:
144 152 if not h.isspace():
145 153 for line in h.splitlines():
146 154 self.shell.readline.add_history(line)
147 155
148 156 def save_history(self):
149 157 """Save input history to a file (via readline library)."""
150 158 hist = dict(raw=self.input_hist_raw, #[-self.shell.history_length:],
151 159 parsed=self.input_hist_parsed) #[-self.shell.history_length:])
152 160 with open(self.hist_file,'wt') as hfile:
153 161 json.dump(hist, hfile,
154 162 sort_keys=True, indent=4)
155 163
156 164 def autosave_if_due(self):
157 165 """Check if the autosave event is set; if so, save history. We do it
158 166 this way so that the save takes place in the main thread."""
159 167 if self.autosave_flag.is_set():
160 168 self.save_history()
161 169 self.autosave_flag.clear()
162 170
163 171 def reload_history(self):
164 172 """Reload the input history from disk file."""
165 173
166 174 with open(self.hist_file,'rt') as hfile:
167 175 try:
168 176 hist = json.load(hfile)
169 177 except ValueError: # Ignore it if JSON is corrupt.
170 178 return
171 179 self.input_hist_parsed = hist['parsed']
172 180 self.input_hist_raw = hist['raw']
173 181 if self.shell.has_readline:
174 182 self.populate_readline_history()
175 183
176 184 def get_history(self, index=None, raw=False, output=True):
177 185 """Get the history list.
178 186
179 187 Get the input and output history.
180 188
181 189 Parameters
182 190 ----------
183 191 index : n or (n1, n2) or None
184 If n, then the last entries. If a tuple, then all in
192 If n, then the last n entries. If a tuple, then all in
185 193 range(n1, n2). If None, then all entries. Raises IndexError if
186 194 the format of index is incorrect.
187 195 raw : bool
188 196 If True, return the raw input.
189 197 output : bool
190 198 If True, then return the output as well.
191 199
192 200 Returns
193 201 -------
194 202 If output is True, then return a dict of tuples, keyed by the prompt
195 203 numbers and with values of (input, output). If output is False, then
196 a dict, keyed by the prompt number with the values of input. Raises
197 IndexError if no history is found.
204 a dict, keyed by the prompt number with the values of input.
198 205 """
199 206 if raw:
200 207 input_hist = self.input_hist_raw
201 208 else:
202 209 input_hist = self.input_hist_parsed
203 210 if output:
204 211 output_hist = self.output_hist
212
205 213 n = len(input_hist)
214 offset = self.session_offset
206 215 if index is None:
207 start=0; stop=n
216 start=offset+1; stop=n
208 217 elif isinstance(index, int):
209 218 start=n-index; stop=n
210 elif isinstance(index, tuple) and len(index) == 2:
211 start=index[0]; stop=index[1]
219 elif len(index) == 2:
220 start = index[0] + offset
221 stop = index[1] + offset
212 222 else:
213 223 raise IndexError('Not a valid index for the input history: %r'
214 224 % index)
215 225 hist = {}
216 226 for i in range(start, stop):
217 227 if output:
218 hist[i] = (input_hist[i], output_hist.get(i))
228 hist[i-offset] = (input_hist[i], output_hist.get(i-offset))
219 229 else:
220 hist[i] = input_hist[i]
221 if not hist:
222 raise IndexError('No history for range of indices: %r' % index)
230 hist[i-offset] = input_hist[i]
223 231 return hist
224 232
225 233 def store_inputs(self, source, source_raw=None):
226 234 """Store source and raw input in history and create input cache
227 235 variables _i*.
228 236
229 237 Parameters
230 238 ----------
231 239 source : str
232 240 Python input.
233 241
234 242 source_raw : str, optional
235 243 If given, this is the raw input without any IPython transformations
236 244 applied to it. If not given, ``source`` is used.
237 245 """
238 246 if source_raw is None:
239 247 source_raw = source
240 248
241 249 # do not store exit/quit commands
242 250 if source_raw.strip() in self._exit_commands:
243 251 return
244 252
245 253 self.input_hist_parsed.append(source.rstrip())
246 254 self.input_hist_raw.append(source_raw.rstrip())
247 255 self.shadow_hist.add(source)
248 256
249 257 # update the auto _i variables
250 258 self._iii = self._ii
251 259 self._ii = self._i
252 260 self._i = self._i00
253 261 self._i00 = source_raw
254 262
255 263 # hackish access to user namespace to create _i1,_i2... dynamically
256 264 new_i = '_i%s' % self.shell.execution_count
257 265 to_main = {'_i': self._i,
258 266 '_ii': self._ii,
259 267 '_iii': self._iii,
260 268 new_i : self._i00 }
261 269 self.shell.user_ns.update(to_main)
262 270
263 271 def sync_inputs(self):
264 272 """Ensure raw and translated histories have same length."""
265 273 if len(self.input_hist_parsed) != len (self.input_hist_raw):
266 274 self.input_hist_raw[:] = self.input_hist_parsed
267 275
268 276 def reset(self):
269 277 """Clear all histories managed by this object."""
270 278 self.input_hist_parsed[:] = []
271 279 self.input_hist_raw[:] = []
272 280 self.output_hist.clear()
273 281 # The directory history can't be completely empty
274 282 self.dir_hist[:] = [os.getcwd()]
275 283
276 284 class HistorySaveThread(threading.Thread):
277 285 """This thread makes IPython save history periodically.
278 286
279 287 Without this class, IPython would only save the history on a clean exit.
280 288 This saves the history periodically (the current default is once per
281 289 minute), so that it is not lost in the event of a crash.
282 290
283 291 The implementation sets an event to indicate that history should be saved.
284 292 The actual save is carried out after executing a user command, to avoid
285 293 thread issues.
286 294 """
287 295 daemon = True
288 296
289 297 def __init__(self, autosave_flag, time_interval=60):
290 298 threading.Thread.__init__(self)
291 299 self.time_interval = time_interval
292 300 self.autosave_flag = autosave_flag
293 301 self.exit_now = threading.Event()
294 302 # Ensure the thread is stopped tidily when exiting normally
295 303 atexit.register(self.stop)
296 304
297 305 def run(self):
298 306 while True:
299 307 self.exit_now.wait(self.time_interval)
300 308 if self.exit_now.is_set():
301 309 break
302 310 self.autosave_flag.set()
303 311
304 312 def stop(self):
305 313 """Safely and quickly stop the autosave timer thread."""
306 314 self.exit_now.set()
307 315 self.join()
308 316
309 317 @testdec.skip_doctest
310 318 def magic_history(self, parameter_s = ''):
311 319 """Print input history (_i<n> variables), with most recent last.
312 320
313 321 %history -> print at most 40 inputs (some may be multi-line)\\
314 322 %history n -> print at most n inputs\\
315 323 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
316 324
317 325 By default, input history is printed without line numbers so it can be
318 326 directly pasted into an editor.
319 327
320 328 With -n, each input's number <n> is shown, and is accessible as the
321 329 automatically generated variable _i<n> as well as In[<n>]. Multi-line
322 330 statements are printed starting at a new line for easy copy/paste.
323 331
324 332 Options:
325 333
326 334 -n: print line numbers for each input.
327 335 This feature is only available if numbered prompts are in use.
328 336
329 337 -o: also print outputs for each input.
330 338
331 339 -p: print classic '>>>' python prompts before each input. This is useful
332 340 for making documentation, and in conjunction with -o, for producing
333 341 doctest-ready output.
334 342
335 343 -r: (default) print the 'raw' history, i.e. the actual commands you typed.
336 344
337 345 -t: print the 'translated' history, as IPython understands it. IPython
338 346 filters your input and converts it all into valid Python source before
339 347 executing it (things like magics or aliases are turned into function
340 348 calls, for example). With this option, you'll see the native history
341 349 instead of the user-entered version: '%cd /' will be seen as
342 350 'get_ipython().magic("%cd /")' instead of '%cd /'.
343 351
344 352 -g: treat the arg as a pattern to grep for in (full) history.
345 353 This includes the "shadow history" (almost all commands ever written).
346 354 Use '%hist -g' to show full shadow history (may be very long).
347 355 In shadow history, every index nuwber starts with 0.
348 356
349 357 -f FILENAME: instead of printing the output to the screen, redirect it to
350 358 the given file. The file is always overwritten, though IPython asks for
351 359 confirmation first if it already exists.
352 360
353 361 Examples
354 362 --------
355 363 ::
356 364
357 365 In [6]: %hist -n 4 6
358 366 4:a = 12
359 367 5:print a**2
360 368
361 369 """
362 370
363 371 if not self.shell.displayhook.do_full_cache:
364 372 print('This feature is only available if numbered prompts are in use.')
365 373 return
366 374 opts,args = self.parse_options(parameter_s,'gnoptsrf:',mode='list')
375
376 # For brevity
377 history_manager = self.shell.history_manager
367 378
368 379 # Check if output to specific file was requested.
369 380 try:
370 381 outfname = opts['f']
371 382 except KeyError:
372 383 outfile = IPython.utils.io.Term.cout # default
373 384 # We don't want to close stdout at the end!
374 385 close_at_end = False
375 386 else:
376 387 if os.path.exists(outfname):
377 388 if not ask_yes_no("File %r exists. Overwrite?" % outfname):
378 389 print('Aborting.')
379 390 return
380 391
381 392 outfile = open(outfname,'w')
382 393 close_at_end = True
383
384 if 't' in opts:
385 input_hist = self.shell.history_manager.input_hist_parsed
386 elif 'r' in opts:
387 input_hist = self.shell.history_manager.input_hist_raw
388 else:
389 # Raw history is the default
390 input_hist = self.shell.history_manager.input_hist_raw
394
395 print_nums = 'n' in opts
396 print_outputs = 'o' in opts
397 pyprompts = 'p' in opts
398 # Raw history is the default
399 raw = not('t' in opts)
391 400
392 401 default_length = 40
393 402 pattern = None
394 403 if 'g' in opts:
395 init = 1
396 final = len(input_hist)
404 index = None
397 405 parts = parameter_s.split(None, 1)
398 406 if len(parts) == 1:
399 407 parts += '*'
400 408 head, pattern = parts
401 409 pattern = "*" + pattern + "*"
402 410 elif len(args) == 0:
403 final = len(input_hist)-1
404 init = max(1,final-default_length)
411 index = None
405 412 elif len(args) == 1:
406 final = len(input_hist)
407 init = max(1, final-int(args[0]))
413 index = int(args[0])
408 414 elif len(args) == 2:
409 init, final = map(int, args)
415 index = map(int, args)
410 416 else:
411 417 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
412 418 print(self.magic_hist.__doc__, file=IPython.utils.io.Term.cout)
413 419 return
420
421 hist = history_manager.get_history(index, raw, print_outputs)
414 422
415 width = len(str(final))
423 width = len(str(max(hist.iterkeys())))
416 424 line_sep = ['','\n']
417 print_nums = 'n' in opts
418 print_outputs = 'o' in opts
419 pyprompts = 'p' in opts
420 425
421 426 found = False
422 427 if pattern is not None:
423 sh = self.shell.history_manager.shadowhist.all()
428 sh = history_manager.shadow_hist.all()
424 429 for idx, s in sh:
425 430 if fnmatch.fnmatch(s, pattern):
426 431 print("0%d: %s" %(idx, s.expandtabs(4)), file=outfile)
427 432 found = True
428 433
429 434 if found:
430 435 print("===", file=outfile)
431 436 print("shadow history ends, fetch by %rep <number> (must start with 0)",
432 437 file=outfile)
433 438 print("=== start of normal history ===", file=outfile)
434 439
435 for in_num in range(init, final):
440 for in_num, inline in sorted(hist.iteritems()):
436 441 # Print user history with tabs expanded to 4 spaces. The GUI clients
437 442 # use hard tabs for easier usability in auto-indented code, but we want
438 443 # to produce PEP-8 compliant history for safe pasting into an editor.
439 inline = input_hist[in_num].expandtabs(4).rstrip()+'\n'
444 if print_outputs:
445 inline, output = inline
446 inline = inline.expandtabs(4).rstrip()
440 447
441 448 if pattern is not None and not fnmatch.fnmatch(inline, pattern):
442 449 continue
443 450
444 multiline = int(inline.count('\n') > 1)
451 multiline = "\n" in inline
445 452 if print_nums:
446 453 print('%s:%s' % (str(in_num).ljust(width), line_sep[multiline]),
447 file=outfile)
454 file=outfile, end='')
448 455 if pyprompts:
449 print('>>>', file=outfile)
456 inline = ">>> " + inline
450 457 if multiline:
451 458 lines = inline.splitlines()
452 459 print('\n... '.join(lines), file=outfile)
453 460 print('... ', file=outfile)
454 461 else:
455 print(inline, end='', file=outfile)
462 print(inline, file=outfile)
456 463 else:
457 print(inline, end='', file=outfile)
458 if print_outputs:
459 output = self.shell.history_manager.output_hist.get(in_num)
460 if output is not None:
461 print(repr(output), file=outfile)
464 print(inline, file=outfile)
465 if print_outputs and output:
466 print(repr(output), file=outfile)
462 467
463 468 if close_at_end:
464 469 outfile.close()
465 470
466
467 def magic_hist(self, parameter_s=''):
468 """Alternate name for %history."""
469 return self.magic_history(parameter_s)
471 # %hist is an alternative name
472 magic_hist = magic_history
470 473
471 474
472 475 def rep_f(self, arg):
473 476 r""" Repeat a command, or get command to input line for editing
474 477
475 478 - %rep (no arguments):
476 479
477 480 Place a string version of last computation result (stored in the special '_'
478 481 variable) to the next input prompt. Allows you to create elaborate command
479 482 lines without using copy-paste::
480 483
481 484 $ l = ["hei", "vaan"]
482 485 $ "".join(l)
483 486 ==> heivaan
484 487 $ %rep
485 488 $ heivaan_ <== cursor blinking
486 489
487 490 %rep 45
488 491
489 492 Place history line 45 to next input prompt. Use %hist to find out the
490 493 number.
491 494
492 495 %rep 1-4 6-7 3
493 496
494 497 Repeat the specified lines immediately. Input slice syntax is the same as
495 498 in %macro and %save.
496 499
497 500 %rep foo
498 501
499 502 Place the most recent line that has the substring "foo" to next input.
500 503 (e.g. 'svn ci -m foobar').
501 504 """
502 505
503 506 opts,args = self.parse_options(arg,'',mode='list')
504 507 if not args:
505 508 self.set_next_input(str(self.shell.user_ns["_"]))
506 509 return
507 510
508 511 if len(args) == 1 and not '-' in args[0]:
509 512 arg = args[0]
510 513 if len(arg) > 1 and arg.startswith('0'):
511 514 # get from shadow hist
512 515 num = int(arg[1:])
513 516 line = self.shell.shadowhist.get(num)
514 517 self.set_next_input(str(line))
515 518 return
516 519 try:
517 520 num = int(args[0])
518 521 self.set_next_input(str(self.shell.input_hist_raw[num]).rstrip())
519 522 return
520 523 except ValueError:
521 524 pass
522 525
523 526 for h in reversed(self.shell.input_hist_raw):
524 527 if 'rep' in h:
525 528 continue
526 529 if fnmatch.fnmatch(h,'*' + arg + '*'):
527 530 self.set_next_input(str(h).rstrip())
528 531 return
529 532
530 533 try:
531 534 lines = self.extract_input_slices(args, True)
532 535 print("lines", lines)
533 536 self.run_cell(lines)
534 537 except ValueError:
535 538 print("Not found in recent history:", args)
536 539
537 540
538 541 _sentinel = object()
539 542
540 543 class ShadowHist(object):
541 544 def __init__(self, db, shell):
542 545 # cmd => idx mapping
543 546 self.curidx = 0
544 547 self.db = db
545 548 self.disabled = False
546 549 self.shell = shell
547 550
548 551 def inc_idx(self):
549 552 idx = self.db.get('shadowhist_idx', 1)
550 553 self.db['shadowhist_idx'] = idx + 1
551 554 return idx
552 555
553 556 def add(self, ent):
554 557 if self.disabled:
555 558 return
556 559 try:
557 560 old = self.db.hget('shadowhist', ent, _sentinel)
558 561 if old is not _sentinel:
559 562 return
560 563 newidx = self.inc_idx()
561 564 #print("new", newidx) # dbg
562 565 self.db.hset('shadowhist',ent, newidx)
563 566 except:
564 567 self.shell.showtraceback()
565 568 print("WARNING: disabling shadow history")
566 569 self.disabled = True
567 570
568 571 def all(self):
569 572 d = self.db.hdict('shadowhist')
570 573 items = [(i,s) for (s,i) in d.iteritems()]
571 574 items.sort()
572 575 return items
573 576
574 577 def get(self, idx):
575 578 all = self.all()
576 579
577 580 for k, v in all:
578 581 if k == idx:
579 582 return v
580 583
581 584
582 585 def init_ipython(ip):
583 586 ip.define_magic("rep",rep_f)
584 587 ip.define_magic("hist",magic_hist)
585 588 ip.define_magic("history",magic_history)
586 589
587 590 # XXX - ipy_completers are in quarantine, need to be updated to new apis
588 591 #import ipy_completers
589 592 #ipy_completers.quick_completer('%hist' ,'-g -t -r -n')
@@ -1,2558 +1,2555 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Main IPython class."""
3 3
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 7 # Copyright (C) 2008-2011 The IPython Development Team
8 8 #
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16
17 17 from __future__ import with_statement
18 18 from __future__ import absolute_import
19 19
20 20 import __builtin__
21 21 import __future__
22 22 import abc
23 23 import atexit
24 24 import codeop
25 25 import os
26 26 import re
27 27 import sys
28 28 import tempfile
29 29 import types
30 30 from contextlib import nested
31 31
32 32 from IPython.config.configurable import Configurable
33 33 from IPython.core import debugger, oinspect
34 34 from IPython.core import history as ipcorehist
35 35 from IPython.core import page
36 36 from IPython.core import prefilter
37 37 from IPython.core import shadowns
38 38 from IPython.core import ultratb
39 39 from IPython.core.alias import AliasManager
40 40 from IPython.core.builtin_trap import BuiltinTrap
41 41 from IPython.core.compilerop import CachingCompiler
42 42 from IPython.core.display_trap import DisplayTrap
43 43 from IPython.core.displayhook import DisplayHook
44 44 from IPython.core.displaypub import DisplayPublisher
45 45 from IPython.core.error import TryNext, UsageError
46 46 from IPython.core.extensions import ExtensionManager
47 47 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
48 48 from IPython.core.formatters import DisplayFormatter
49 49 from IPython.core.history import HistoryManager
50 50 from IPython.core.inputsplitter import IPythonInputSplitter
51 51 from IPython.core.logger import Logger
52 52 from IPython.core.magic import Magic
53 53 from IPython.core.payload import PayloadManager
54 54 from IPython.core.plugin import PluginManager
55 55 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
56 56 from IPython.external.Itpl import ItplNS
57 57 from IPython.utils import PyColorize
58 58 from IPython.utils import io
59 59 from IPython.utils import pickleshare
60 60 from IPython.utils.doctestreload import doctest_reload
61 61 from IPython.utils.io import ask_yes_no, rprint
62 62 from IPython.utils.ipstruct import Struct
63 63 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
64 64 from IPython.utils.process import system, getoutput
65 65 from IPython.utils.strdispatch import StrDispatch
66 66 from IPython.utils.syspathcontext import prepended_to_syspath
67 67 from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList
68 68 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
69 69 List, Unicode, Instance, Type)
70 70 from IPython.utils.warn import warn, error, fatal
71 71 import IPython.core.hooks
72 72
73 73 #-----------------------------------------------------------------------------
74 74 # Globals
75 75 #-----------------------------------------------------------------------------
76 76
77 77 # compiled regexps for autoindent management
78 78 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
79 79
80 80 #-----------------------------------------------------------------------------
81 81 # Utilities
82 82 #-----------------------------------------------------------------------------
83 83
84 84 # store the builtin raw_input globally, and use this always, in case user code
85 85 # overwrites it (like wx.py.PyShell does)
86 86 raw_input_original = raw_input
87 87
88 88 def softspace(file, newvalue):
89 89 """Copied from code.py, to remove the dependency"""
90 90
91 91 oldvalue = 0
92 92 try:
93 93 oldvalue = file.softspace
94 94 except AttributeError:
95 95 pass
96 96 try:
97 97 file.softspace = newvalue
98 98 except (AttributeError, TypeError):
99 99 # "attribute-less object" or "read-only attributes"
100 100 pass
101 101 return oldvalue
102 102
103 103
104 104 def no_op(*a, **kw): pass
105 105
106 106 class SpaceInInput(Exception): pass
107 107
108 108 class Bunch: pass
109 109
110 110
111 111 def get_default_colors():
112 112 if sys.platform=='darwin':
113 113 return "LightBG"
114 114 elif os.name=='nt':
115 115 return 'Linux'
116 116 else:
117 117 return 'Linux'
118 118
119 119
120 120 class SeparateStr(Str):
121 121 """A Str subclass to validate separate_in, separate_out, etc.
122 122
123 123 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
124 124 """
125 125
126 126 def validate(self, obj, value):
127 127 if value == '0': value = ''
128 128 value = value.replace('\\n','\n')
129 129 return super(SeparateStr, self).validate(obj, value)
130 130
131 131 class MultipleInstanceError(Exception):
132 132 pass
133 133
134 134
135 135 #-----------------------------------------------------------------------------
136 136 # Main IPython class
137 137 #-----------------------------------------------------------------------------
138 138
139 139 class InteractiveShell(Configurable, Magic):
140 140 """An enhanced, interactive shell for Python."""
141 141
142 142 _instance = None
143 143 autocall = Enum((0,1,2), default_value=1, config=True)
144 144 # TODO: remove all autoindent logic and put into frontends.
145 145 # We can't do this yet because even runlines uses the autoindent.
146 146 autoindent = CBool(True, config=True)
147 147 automagic = CBool(True, config=True)
148 148 cache_size = Int(1000, config=True)
149 149 color_info = CBool(True, config=True)
150 150 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
151 151 default_value=get_default_colors(), config=True)
152 152 debug = CBool(False, config=True)
153 153 deep_reload = CBool(False, config=True)
154 154 display_formatter = Instance(DisplayFormatter)
155 155 displayhook_class = Type(DisplayHook)
156 156 display_pub_class = Type(DisplayPublisher)
157 157
158 158 exit_now = CBool(False)
159 159 # Monotonically increasing execution counter
160 160 execution_count = Int(1)
161 161 filename = Str("<ipython console>")
162 162 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
163 163
164 164 # Input splitter, to split entire cells of input into either individual
165 165 # interactive statements or whole blocks.
166 166 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
167 167 (), {})
168 168 logstart = CBool(False, config=True)
169 169 logfile = Str('', config=True)
170 170 logappend = Str('', config=True)
171 171 object_info_string_level = Enum((0,1,2), default_value=0,
172 172 config=True)
173 173 pdb = CBool(False, config=True)
174 174
175 175 profile = Str('', config=True)
176 176 prompt_in1 = Str('In [\\#]: ', config=True)
177 177 prompt_in2 = Str(' .\\D.: ', config=True)
178 178 prompt_out = Str('Out[\\#]: ', config=True)
179 179 prompts_pad_left = CBool(True, config=True)
180 180 quiet = CBool(False, config=True)
181 181
182 182 history_length = Int(10000, config=True)
183 183
184 184 # The readline stuff will eventually be moved to the terminal subclass
185 185 # but for now, we can't do that as readline is welded in everywhere.
186 186 readline_use = CBool(True, config=True)
187 187 readline_merge_completions = CBool(True, config=True)
188 188 readline_omit__names = Enum((0,1,2), default_value=2, config=True)
189 189 readline_remove_delims = Str('-/~', config=True)
190 190 readline_parse_and_bind = List([
191 191 'tab: complete',
192 192 '"\C-l": clear-screen',
193 193 'set show-all-if-ambiguous on',
194 194 '"\C-o": tab-insert',
195 195 '"\M-i": " "',
196 196 '"\M-o": "\d\d\d\d"',
197 197 '"\M-I": "\d\d\d\d"',
198 198 '"\C-r": reverse-search-history',
199 199 '"\C-s": forward-search-history',
200 200 '"\C-p": history-search-backward',
201 201 '"\C-n": history-search-forward',
202 202 '"\e[A": history-search-backward',
203 203 '"\e[B": history-search-forward',
204 204 '"\C-k": kill-line',
205 205 '"\C-u": unix-line-discard',
206 206 ], allow_none=False, config=True)
207 207
208 208 # TODO: this part of prompt management should be moved to the frontends.
209 209 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
210 210 separate_in = SeparateStr('\n', config=True)
211 211 separate_out = SeparateStr('', config=True)
212 212 separate_out2 = SeparateStr('', config=True)
213 213 wildcards_case_sensitive = CBool(True, config=True)
214 214 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
215 215 default_value='Context', config=True)
216 216
217 217 # Subcomponents of InteractiveShell
218 218 alias_manager = Instance('IPython.core.alias.AliasManager')
219 219 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
220 220 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
221 221 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
222 222 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
223 223 plugin_manager = Instance('IPython.core.plugin.PluginManager')
224 224 payload_manager = Instance('IPython.core.payload.PayloadManager')
225 225 history_manager = Instance('IPython.core.history.HistoryManager')
226 226
227 227 # Private interface
228 228 _post_execute = set()
229 229
230 230 def __init__(self, config=None, ipython_dir=None,
231 231 user_ns=None, user_global_ns=None,
232 232 custom_exceptions=((), None)):
233 233
234 234 # This is where traits with a config_key argument are updated
235 235 # from the values on config.
236 236 super(InteractiveShell, self).__init__(config=config)
237 237
238 238 # These are relatively independent and stateless
239 239 self.init_ipython_dir(ipython_dir)
240 240 self.init_instance_attrs()
241 241 self.init_environment()
242 242
243 243 # Create namespaces (user_ns, user_global_ns, etc.)
244 244 self.init_create_namespaces(user_ns, user_global_ns)
245 245 # This has to be done after init_create_namespaces because it uses
246 246 # something in self.user_ns, but before init_sys_modules, which
247 247 # is the first thing to modify sys.
248 248 # TODO: When we override sys.stdout and sys.stderr before this class
249 249 # is created, we are saving the overridden ones here. Not sure if this
250 250 # is what we want to do.
251 251 self.save_sys_module_state()
252 252 self.init_sys_modules()
253 253
254 254 self.init_history()
255 255 self.init_encoding()
256 256 self.init_prefilter()
257 257
258 258 Magic.__init__(self, self)
259 259
260 260 self.init_syntax_highlighting()
261 261 self.init_hooks()
262 262 self.init_pushd_popd_magic()
263 263 # self.init_traceback_handlers use to be here, but we moved it below
264 264 # because it and init_io have to come after init_readline.
265 265 self.init_user_ns()
266 266 self.init_logger()
267 267 self.init_alias()
268 268 self.init_builtins()
269 269
270 270 # pre_config_initialization
271 271
272 272 # The next section should contain everything that was in ipmaker.
273 273 self.init_logstart()
274 274
275 275 # The following was in post_config_initialization
276 276 self.init_inspector()
277 277 # init_readline() must come before init_io(), because init_io uses
278 278 # readline related things.
279 279 self.init_readline()
280 280 # init_completer must come after init_readline, because it needs to
281 281 # know whether readline is present or not system-wide to configure the
282 282 # completers, since the completion machinery can now operate
283 283 # independently of readline (e.g. over the network)
284 284 self.init_completer()
285 285 # TODO: init_io() needs to happen before init_traceback handlers
286 286 # because the traceback handlers hardcode the stdout/stderr streams.
287 287 # This logic in in debugger.Pdb and should eventually be changed.
288 288 self.init_io()
289 289 self.init_traceback_handlers(custom_exceptions)
290 290 self.init_prompts()
291 291 self.init_display_formatter()
292 292 self.init_display_pub()
293 293 self.init_displayhook()
294 294 self.init_reload_doctest()
295 295 self.init_magics()
296 296 self.init_pdb()
297 297 self.init_extension_manager()
298 298 self.init_plugin_manager()
299 299 self.init_payload()
300 300 self.hooks.late_startup_hook()
301 301 atexit.register(self.atexit_operations)
302 302
303 303 # While we're trying to have each part of the code directly access what it
304 304 # needs without keeping redundant references to objects, we have too much
305 305 # legacy code that expects ip.db to exist, so let's make it a property that
306 306 # retrieves the underlying object from our new history manager.
307 307 @property
308 308 def db(self):
309 309 return self.history_manager.shadow_db
310 310
311 311 @classmethod
312 312 def instance(cls, *args, **kwargs):
313 313 """Returns a global InteractiveShell instance."""
314 314 if cls._instance is None:
315 315 inst = cls(*args, **kwargs)
316 316 # Now make sure that the instance will also be returned by
317 317 # the subclasses instance attribute.
318 318 for subclass in cls.mro():
319 319 if issubclass(cls, subclass) and \
320 320 issubclass(subclass, InteractiveShell):
321 321 subclass._instance = inst
322 322 else:
323 323 break
324 324 if isinstance(cls._instance, cls):
325 325 return cls._instance
326 326 else:
327 327 raise MultipleInstanceError(
328 328 'Multiple incompatible subclass instances of '
329 329 'InteractiveShell are being created.'
330 330 )
331 331
332 332 @classmethod
333 333 def initialized(cls):
334 334 return hasattr(cls, "_instance")
335 335
336 336 def get_ipython(self):
337 337 """Return the currently running IPython instance."""
338 338 return self
339 339
340 340 #-------------------------------------------------------------------------
341 341 # Trait changed handlers
342 342 #-------------------------------------------------------------------------
343 343
344 344 def _ipython_dir_changed(self, name, new):
345 345 if not os.path.isdir(new):
346 346 os.makedirs(new, mode = 0777)
347 347
348 348 def set_autoindent(self,value=None):
349 349 """Set the autoindent flag, checking for readline support.
350 350
351 351 If called with no arguments, it acts as a toggle."""
352 352
353 353 if not self.has_readline:
354 354 if os.name == 'posix':
355 355 warn("The auto-indent feature requires the readline library")
356 356 self.autoindent = 0
357 357 return
358 358 if value is None:
359 359 self.autoindent = not self.autoindent
360 360 else:
361 361 self.autoindent = value
362 362
363 363 #-------------------------------------------------------------------------
364 364 # init_* methods called by __init__
365 365 #-------------------------------------------------------------------------
366 366
367 367 def init_ipython_dir(self, ipython_dir):
368 368 if ipython_dir is not None:
369 369 self.ipython_dir = ipython_dir
370 370 self.config.Global.ipython_dir = self.ipython_dir
371 371 return
372 372
373 373 if hasattr(self.config.Global, 'ipython_dir'):
374 374 self.ipython_dir = self.config.Global.ipython_dir
375 375 else:
376 376 self.ipython_dir = get_ipython_dir()
377 377
378 378 # All children can just read this
379 379 self.config.Global.ipython_dir = self.ipython_dir
380 380
381 381 def init_instance_attrs(self):
382 382 self.more = False
383 383
384 384 # command compiler
385 385 self.compile = CachingCompiler()
386 386
387 387 # User input buffers
388 388 # NOTE: these variables are slated for full removal, once we are 100%
389 389 # sure that the new execution logic is solid. We will delte runlines,
390 390 # push_line and these buffers, as all input will be managed by the
391 391 # frontends via an inputsplitter instance.
392 392 self.buffer = []
393 393 self.buffer_raw = []
394 394
395 395 # Make an empty namespace, which extension writers can rely on both
396 396 # existing and NEVER being used by ipython itself. This gives them a
397 397 # convenient location for storing additional information and state
398 398 # their extensions may require, without fear of collisions with other
399 399 # ipython names that may develop later.
400 400 self.meta = Struct()
401 401
402 402 # Object variable to store code object waiting execution. This is
403 403 # used mainly by the multithreaded shells, but it can come in handy in
404 404 # other situations. No need to use a Queue here, since it's a single
405 405 # item which gets cleared once run.
406 406 self.code_to_run = None
407 407
408 408 # Temporary files used for various purposes. Deleted at exit.
409 409 self.tempfiles = []
410 410
411 411 # Keep track of readline usage (later set by init_readline)
412 412 self.has_readline = False
413 413
414 414 # keep track of where we started running (mainly for crash post-mortem)
415 415 # This is not being used anywhere currently.
416 416 self.starting_dir = os.getcwd()
417 417
418 418 # Indentation management
419 419 self.indent_current_nsp = 0
420 420
421 421 def init_environment(self):
422 422 """Any changes we need to make to the user's environment."""
423 423 pass
424 424
425 425 def init_encoding(self):
426 426 # Get system encoding at startup time. Certain terminals (like Emacs
427 427 # under Win32 have it set to None, and we need to have a known valid
428 428 # encoding to use in the raw_input() method
429 429 try:
430 430 self.stdin_encoding = sys.stdin.encoding or 'ascii'
431 431 except AttributeError:
432 432 self.stdin_encoding = 'ascii'
433 433
434 434 def init_syntax_highlighting(self):
435 435 # Python source parser/formatter for syntax highlighting
436 436 pyformat = PyColorize.Parser().format
437 437 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
438 438
439 439 def init_pushd_popd_magic(self):
440 440 # for pushd/popd management
441 441 try:
442 442 self.home_dir = get_home_dir()
443 443 except HomeDirError, msg:
444 444 fatal(msg)
445 445
446 446 self.dir_stack = []
447 447
448 448 def init_logger(self):
449 449 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
450 450 logmode='rotate')
451 451
452 452 def init_logstart(self):
453 453 """Initialize logging in case it was requested at the command line.
454 454 """
455 455 if self.logappend:
456 456 self.magic_logstart(self.logappend + ' append')
457 457 elif self.logfile:
458 458 self.magic_logstart(self.logfile)
459 459 elif self.logstart:
460 460 self.magic_logstart()
461 461
462 462 def init_builtins(self):
463 463 self.builtin_trap = BuiltinTrap(shell=self)
464 464
465 465 def init_inspector(self):
466 466 # Object inspector
467 467 self.inspector = oinspect.Inspector(oinspect.InspectColors,
468 468 PyColorize.ANSICodeColors,
469 469 'NoColor',
470 470 self.object_info_string_level)
471 471
472 472 def init_io(self):
473 473 # This will just use sys.stdout and sys.stderr. If you want to
474 474 # override sys.stdout and sys.stderr themselves, you need to do that
475 475 # *before* instantiating this class, because Term holds onto
476 476 # references to the underlying streams.
477 477 if sys.platform == 'win32' and self.has_readline:
478 478 Term = io.IOTerm(cout=self.readline._outputfile,
479 479 cerr=self.readline._outputfile)
480 480 else:
481 481 Term = io.IOTerm()
482 482 io.Term = Term
483 483
484 484 def init_prompts(self):
485 485 # TODO: This is a pass for now because the prompts are managed inside
486 486 # the DisplayHook. Once there is a separate prompt manager, this
487 487 # will initialize that object and all prompt related information.
488 488 pass
489 489
490 490 def init_display_formatter(self):
491 491 self.display_formatter = DisplayFormatter(config=self.config)
492 492
493 493 def init_display_pub(self):
494 494 self.display_pub = self.display_pub_class(config=self.config)
495 495
496 496 def init_displayhook(self):
497 497 # Initialize displayhook, set in/out prompts and printing system
498 498 self.displayhook = self.displayhook_class(
499 499 config=self.config,
500 500 shell=self,
501 501 cache_size=self.cache_size,
502 502 input_sep = self.separate_in,
503 503 output_sep = self.separate_out,
504 504 output_sep2 = self.separate_out2,
505 505 ps1 = self.prompt_in1,
506 506 ps2 = self.prompt_in2,
507 507 ps_out = self.prompt_out,
508 508 pad_left = self.prompts_pad_left
509 509 )
510 510 # This is a context manager that installs/revmoes the displayhook at
511 511 # the appropriate time.
512 512 self.display_trap = DisplayTrap(hook=self.displayhook)
513 513
514 514 def init_reload_doctest(self):
515 515 # Do a proper resetting of doctest, including the necessary displayhook
516 516 # monkeypatching
517 517 try:
518 518 doctest_reload()
519 519 except ImportError:
520 520 warn("doctest module does not exist.")
521 521
522 522 #-------------------------------------------------------------------------
523 523 # Things related to injections into the sys module
524 524 #-------------------------------------------------------------------------
525 525
526 526 def save_sys_module_state(self):
527 527 """Save the state of hooks in the sys module.
528 528
529 529 This has to be called after self.user_ns is created.
530 530 """
531 531 self._orig_sys_module_state = {}
532 532 self._orig_sys_module_state['stdin'] = sys.stdin
533 533 self._orig_sys_module_state['stdout'] = sys.stdout
534 534 self._orig_sys_module_state['stderr'] = sys.stderr
535 535 self._orig_sys_module_state['excepthook'] = sys.excepthook
536 536 try:
537 537 self._orig_sys_modules_main_name = self.user_ns['__name__']
538 538 except KeyError:
539 539 pass
540 540
541 541 def restore_sys_module_state(self):
542 542 """Restore the state of the sys module."""
543 543 try:
544 544 for k, v in self._orig_sys_module_state.iteritems():
545 545 setattr(sys, k, v)
546 546 except AttributeError:
547 547 pass
548 548 # Reset what what done in self.init_sys_modules
549 549 try:
550 550 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
551 551 except (AttributeError, KeyError):
552 552 pass
553 553
554 554 #-------------------------------------------------------------------------
555 555 # Things related to hooks
556 556 #-------------------------------------------------------------------------
557 557
558 558 def init_hooks(self):
559 559 # hooks holds pointers used for user-side customizations
560 560 self.hooks = Struct()
561 561
562 562 self.strdispatchers = {}
563 563
564 564 # Set all default hooks, defined in the IPython.hooks module.
565 565 hooks = IPython.core.hooks
566 566 for hook_name in hooks.__all__:
567 567 # default hooks have priority 100, i.e. low; user hooks should have
568 568 # 0-100 priority
569 569 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
570 570
571 571 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
572 572 """set_hook(name,hook) -> sets an internal IPython hook.
573 573
574 574 IPython exposes some of its internal API as user-modifiable hooks. By
575 575 adding your function to one of these hooks, you can modify IPython's
576 576 behavior to call at runtime your own routines."""
577 577
578 578 # At some point in the future, this should validate the hook before it
579 579 # accepts it. Probably at least check that the hook takes the number
580 580 # of args it's supposed to.
581 581
582 582 f = types.MethodType(hook,self)
583 583
584 584 # check if the hook is for strdispatcher first
585 585 if str_key is not None:
586 586 sdp = self.strdispatchers.get(name, StrDispatch())
587 587 sdp.add_s(str_key, f, priority )
588 588 self.strdispatchers[name] = sdp
589 589 return
590 590 if re_key is not None:
591 591 sdp = self.strdispatchers.get(name, StrDispatch())
592 592 sdp.add_re(re.compile(re_key), f, priority )
593 593 self.strdispatchers[name] = sdp
594 594 return
595 595
596 596 dp = getattr(self.hooks, name, None)
597 597 if name not in IPython.core.hooks.__all__:
598 598 print "Warning! Hook '%s' is not one of %s" % \
599 599 (name, IPython.core.hooks.__all__ )
600 600 if not dp:
601 601 dp = IPython.core.hooks.CommandChainDispatcher()
602 602
603 603 try:
604 604 dp.add(f,priority)
605 605 except AttributeError:
606 606 # it was not commandchain, plain old func - replace
607 607 dp = f
608 608
609 609 setattr(self.hooks,name, dp)
610 610
611 611 def register_post_execute(self, func):
612 612 """Register a function for calling after code execution.
613 613 """
614 614 if not callable(func):
615 615 raise ValueError('argument %s must be callable' % func)
616 616 self._post_execute.add(func)
617 617
618 618 #-------------------------------------------------------------------------
619 619 # Things related to the "main" module
620 620 #-------------------------------------------------------------------------
621 621
622 622 def new_main_mod(self,ns=None):
623 623 """Return a new 'main' module object for user code execution.
624 624 """
625 625 main_mod = self._user_main_module
626 626 init_fakemod_dict(main_mod,ns)
627 627 return main_mod
628 628
629 629 def cache_main_mod(self,ns,fname):
630 630 """Cache a main module's namespace.
631 631
632 632 When scripts are executed via %run, we must keep a reference to the
633 633 namespace of their __main__ module (a FakeModule instance) around so
634 634 that Python doesn't clear it, rendering objects defined therein
635 635 useless.
636 636
637 637 This method keeps said reference in a private dict, keyed by the
638 638 absolute path of the module object (which corresponds to the script
639 639 path). This way, for multiple executions of the same script we only
640 640 keep one copy of the namespace (the last one), thus preventing memory
641 641 leaks from old references while allowing the objects from the last
642 642 execution to be accessible.
643 643
644 644 Note: we can not allow the actual FakeModule instances to be deleted,
645 645 because of how Python tears down modules (it hard-sets all their
646 646 references to None without regard for reference counts). This method
647 647 must therefore make a *copy* of the given namespace, to allow the
648 648 original module's __dict__ to be cleared and reused.
649 649
650 650
651 651 Parameters
652 652 ----------
653 653 ns : a namespace (a dict, typically)
654 654
655 655 fname : str
656 656 Filename associated with the namespace.
657 657
658 658 Examples
659 659 --------
660 660
661 661 In [10]: import IPython
662 662
663 663 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
664 664
665 665 In [12]: IPython.__file__ in _ip._main_ns_cache
666 666 Out[12]: True
667 667 """
668 668 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
669 669
670 670 def clear_main_mod_cache(self):
671 671 """Clear the cache of main modules.
672 672
673 673 Mainly for use by utilities like %reset.
674 674
675 675 Examples
676 676 --------
677 677
678 678 In [15]: import IPython
679 679
680 680 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
681 681
682 682 In [17]: len(_ip._main_ns_cache) > 0
683 683 Out[17]: True
684 684
685 685 In [18]: _ip.clear_main_mod_cache()
686 686
687 687 In [19]: len(_ip._main_ns_cache) == 0
688 688 Out[19]: True
689 689 """
690 690 self._main_ns_cache.clear()
691 691
692 692 #-------------------------------------------------------------------------
693 693 # Things related to debugging
694 694 #-------------------------------------------------------------------------
695 695
696 696 def init_pdb(self):
697 697 # Set calling of pdb on exceptions
698 698 # self.call_pdb is a property
699 699 self.call_pdb = self.pdb
700 700
701 701 def _get_call_pdb(self):
702 702 return self._call_pdb
703 703
704 704 def _set_call_pdb(self,val):
705 705
706 706 if val not in (0,1,False,True):
707 707 raise ValueError,'new call_pdb value must be boolean'
708 708
709 709 # store value in instance
710 710 self._call_pdb = val
711 711
712 712 # notify the actual exception handlers
713 713 self.InteractiveTB.call_pdb = val
714 714
715 715 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
716 716 'Control auto-activation of pdb at exceptions')
717 717
718 718 def debugger(self,force=False):
719 719 """Call the pydb/pdb debugger.
720 720
721 721 Keywords:
722 722
723 723 - force(False): by default, this routine checks the instance call_pdb
724 724 flag and does not actually invoke the debugger if the flag is false.
725 725 The 'force' option forces the debugger to activate even if the flag
726 726 is false.
727 727 """
728 728
729 729 if not (force or self.call_pdb):
730 730 return
731 731
732 732 if not hasattr(sys,'last_traceback'):
733 733 error('No traceback has been produced, nothing to debug.')
734 734 return
735 735
736 736 # use pydb if available
737 737 if debugger.has_pydb:
738 738 from pydb import pm
739 739 else:
740 740 # fallback to our internal debugger
741 741 pm = lambda : self.InteractiveTB.debugger(force=True)
742 742 self.history_saving_wrapper(pm)()
743 743
744 744 #-------------------------------------------------------------------------
745 745 # Things related to IPython's various namespaces
746 746 #-------------------------------------------------------------------------
747 747
748 748 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
749 749 # Create the namespace where the user will operate. user_ns is
750 750 # normally the only one used, and it is passed to the exec calls as
751 751 # the locals argument. But we do carry a user_global_ns namespace
752 752 # given as the exec 'globals' argument, This is useful in embedding
753 753 # situations where the ipython shell opens in a context where the
754 754 # distinction between locals and globals is meaningful. For
755 755 # non-embedded contexts, it is just the same object as the user_ns dict.
756 756
757 757 # FIXME. For some strange reason, __builtins__ is showing up at user
758 758 # level as a dict instead of a module. This is a manual fix, but I
759 759 # should really track down where the problem is coming from. Alex
760 760 # Schmolck reported this problem first.
761 761
762 762 # A useful post by Alex Martelli on this topic:
763 763 # Re: inconsistent value from __builtins__
764 764 # Von: Alex Martelli <aleaxit@yahoo.com>
765 765 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
766 766 # Gruppen: comp.lang.python
767 767
768 768 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
769 769 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
770 770 # > <type 'dict'>
771 771 # > >>> print type(__builtins__)
772 772 # > <type 'module'>
773 773 # > Is this difference in return value intentional?
774 774
775 775 # Well, it's documented that '__builtins__' can be either a dictionary
776 776 # or a module, and it's been that way for a long time. Whether it's
777 777 # intentional (or sensible), I don't know. In any case, the idea is
778 778 # that if you need to access the built-in namespace directly, you
779 779 # should start with "import __builtin__" (note, no 's') which will
780 780 # definitely give you a module. Yeah, it's somewhat confusing:-(.
781 781
782 782 # These routines return properly built dicts as needed by the rest of
783 783 # the code, and can also be used by extension writers to generate
784 784 # properly initialized namespaces.
785 785 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
786 786 user_global_ns)
787 787
788 788 # Assign namespaces
789 789 # This is the namespace where all normal user variables live
790 790 self.user_ns = user_ns
791 791 self.user_global_ns = user_global_ns
792 792
793 793 # An auxiliary namespace that checks what parts of the user_ns were
794 794 # loaded at startup, so we can list later only variables defined in
795 795 # actual interactive use. Since it is always a subset of user_ns, it
796 796 # doesn't need to be separately tracked in the ns_table.
797 797 self.user_ns_hidden = {}
798 798
799 799 # A namespace to keep track of internal data structures to prevent
800 800 # them from cluttering user-visible stuff. Will be updated later
801 801 self.internal_ns = {}
802 802
803 803 # Now that FakeModule produces a real module, we've run into a nasty
804 804 # problem: after script execution (via %run), the module where the user
805 805 # code ran is deleted. Now that this object is a true module (needed
806 806 # so docetst and other tools work correctly), the Python module
807 807 # teardown mechanism runs over it, and sets to None every variable
808 808 # present in that module. Top-level references to objects from the
809 809 # script survive, because the user_ns is updated with them. However,
810 810 # calling functions defined in the script that use other things from
811 811 # the script will fail, because the function's closure had references
812 812 # to the original objects, which are now all None. So we must protect
813 813 # these modules from deletion by keeping a cache.
814 814 #
815 815 # To avoid keeping stale modules around (we only need the one from the
816 816 # last run), we use a dict keyed with the full path to the script, so
817 817 # only the last version of the module is held in the cache. Note,
818 818 # however, that we must cache the module *namespace contents* (their
819 819 # __dict__). Because if we try to cache the actual modules, old ones
820 820 # (uncached) could be destroyed while still holding references (such as
821 821 # those held by GUI objects that tend to be long-lived)>
822 822 #
823 823 # The %reset command will flush this cache. See the cache_main_mod()
824 824 # and clear_main_mod_cache() methods for details on use.
825 825
826 826 # This is the cache used for 'main' namespaces
827 827 self._main_ns_cache = {}
828 828 # And this is the single instance of FakeModule whose __dict__ we keep
829 829 # copying and clearing for reuse on each %run
830 830 self._user_main_module = FakeModule()
831 831
832 832 # A table holding all the namespaces IPython deals with, so that
833 833 # introspection facilities can search easily.
834 834 self.ns_table = {'user':user_ns,
835 835 'user_global':user_global_ns,
836 836 'internal':self.internal_ns,
837 837 'builtin':__builtin__.__dict__
838 838 }
839 839
840 840 # Similarly, track all namespaces where references can be held and that
841 841 # we can safely clear (so it can NOT include builtin). This one can be
842 842 # a simple list. Note that the main execution namespaces, user_ns and
843 843 # user_global_ns, can NOT be listed here, as clearing them blindly
844 844 # causes errors in object __del__ methods. Instead, the reset() method
845 845 # clears them manually and carefully.
846 846 self.ns_refs_table = [ self.user_ns_hidden,
847 847 self.internal_ns, self._main_ns_cache ]
848 848
849 849 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
850 850 """Return a valid local and global user interactive namespaces.
851 851
852 852 This builds a dict with the minimal information needed to operate as a
853 853 valid IPython user namespace, which you can pass to the various
854 854 embedding classes in ipython. The default implementation returns the
855 855 same dict for both the locals and the globals to allow functions to
856 856 refer to variables in the namespace. Customized implementations can
857 857 return different dicts. The locals dictionary can actually be anything
858 858 following the basic mapping protocol of a dict, but the globals dict
859 859 must be a true dict, not even a subclass. It is recommended that any
860 860 custom object for the locals namespace synchronize with the globals
861 861 dict somehow.
862 862
863 863 Raises TypeError if the provided globals namespace is not a true dict.
864 864
865 865 Parameters
866 866 ----------
867 867 user_ns : dict-like, optional
868 868 The current user namespace. The items in this namespace should
869 869 be included in the output. If None, an appropriate blank
870 870 namespace should be created.
871 871 user_global_ns : dict, optional
872 872 The current user global namespace. The items in this namespace
873 873 should be included in the output. If None, an appropriate
874 874 blank namespace should be created.
875 875
876 876 Returns
877 877 -------
878 878 A pair of dictionary-like object to be used as the local namespace
879 879 of the interpreter and a dict to be used as the global namespace.
880 880 """
881 881
882 882
883 883 # We must ensure that __builtin__ (without the final 's') is always
884 884 # available and pointing to the __builtin__ *module*. For more details:
885 885 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
886 886
887 887 if user_ns is None:
888 888 # Set __name__ to __main__ to better match the behavior of the
889 889 # normal interpreter.
890 890 user_ns = {'__name__' :'__main__',
891 891 '__builtin__' : __builtin__,
892 892 '__builtins__' : __builtin__,
893 893 }
894 894 else:
895 895 user_ns.setdefault('__name__','__main__')
896 896 user_ns.setdefault('__builtin__',__builtin__)
897 897 user_ns.setdefault('__builtins__',__builtin__)
898 898
899 899 if user_global_ns is None:
900 900 user_global_ns = user_ns
901 901 if type(user_global_ns) is not dict:
902 902 raise TypeError("user_global_ns must be a true dict; got %r"
903 903 % type(user_global_ns))
904 904
905 905 return user_ns, user_global_ns
906 906
907 907 def init_sys_modules(self):
908 908 # We need to insert into sys.modules something that looks like a
909 909 # module but which accesses the IPython namespace, for shelve and
910 910 # pickle to work interactively. Normally they rely on getting
911 911 # everything out of __main__, but for embedding purposes each IPython
912 912 # instance has its own private namespace, so we can't go shoving
913 913 # everything into __main__.
914 914
915 915 # note, however, that we should only do this for non-embedded
916 916 # ipythons, which really mimic the __main__.__dict__ with their own
917 917 # namespace. Embedded instances, on the other hand, should not do
918 918 # this because they need to manage the user local/global namespaces
919 919 # only, but they live within a 'normal' __main__ (meaning, they
920 920 # shouldn't overtake the execution environment of the script they're
921 921 # embedded in).
922 922
923 923 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
924 924
925 925 try:
926 926 main_name = self.user_ns['__name__']
927 927 except KeyError:
928 928 raise KeyError('user_ns dictionary MUST have a "__name__" key')
929 929 else:
930 930 sys.modules[main_name] = FakeModule(self.user_ns)
931 931
932 932 def init_user_ns(self):
933 933 """Initialize all user-visible namespaces to their minimum defaults.
934 934
935 935 Certain history lists are also initialized here, as they effectively
936 936 act as user namespaces.
937 937
938 938 Notes
939 939 -----
940 940 All data structures here are only filled in, they are NOT reset by this
941 941 method. If they were not empty before, data will simply be added to
942 942 therm.
943 943 """
944 944 # This function works in two parts: first we put a few things in
945 945 # user_ns, and we sync that contents into user_ns_hidden so that these
946 946 # initial variables aren't shown by %who. After the sync, we add the
947 947 # rest of what we *do* want the user to see with %who even on a new
948 948 # session (probably nothing, so theye really only see their own stuff)
949 949
950 950 # The user dict must *always* have a __builtin__ reference to the
951 951 # Python standard __builtin__ namespace, which must be imported.
952 952 # This is so that certain operations in prompt evaluation can be
953 953 # reliably executed with builtins. Note that we can NOT use
954 954 # __builtins__ (note the 's'), because that can either be a dict or a
955 955 # module, and can even mutate at runtime, depending on the context
956 956 # (Python makes no guarantees on it). In contrast, __builtin__ is
957 957 # always a module object, though it must be explicitly imported.
958 958
959 959 # For more details:
960 960 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
961 961 ns = dict(__builtin__ = __builtin__)
962 962
963 963 # Put 'help' in the user namespace
964 964 try:
965 965 from site import _Helper
966 966 ns['help'] = _Helper()
967 967 except ImportError:
968 968 warn('help() not available - check site.py')
969 969
970 970 # make global variables for user access to the histories
971 971 ns['_ih'] = self.history_manager.input_hist_parsed
972 972 ns['_oh'] = self.history_manager.output_hist
973 973 ns['_dh'] = self.history_manager.dir_hist
974 974
975 975 ns['_sh'] = shadowns
976 976
977 977 # user aliases to input and output histories. These shouldn't show up
978 978 # in %who, as they can have very large reprs.
979 979 ns['In'] = self.history_manager.input_hist_parsed
980 980 ns['Out'] = self.history_manager.output_hist
981 981
982 982 # Store myself as the public api!!!
983 983 ns['get_ipython'] = self.get_ipython
984 984
985 985 # Sync what we've added so far to user_ns_hidden so these aren't seen
986 986 # by %who
987 987 self.user_ns_hidden.update(ns)
988 988
989 989 # Anything put into ns now would show up in %who. Think twice before
990 990 # putting anything here, as we really want %who to show the user their
991 991 # stuff, not our variables.
992 992
993 993 # Finally, update the real user's namespace
994 994 self.user_ns.update(ns)
995 995
996 996 def reset(self):
997 997 """Clear all internal namespaces.
998 998
999 999 Note that this is much more aggressive than %reset, since it clears
1000 1000 fully all namespaces, as well as all input/output lists.
1001 1001 """
1002 1002 # Clear histories
1003 1003 self.history_manager.reset()
1004 1004
1005 1005 # Reset counter used to index all histories
1006 1006 self.execution_count = 0
1007 1007
1008 1008 # Restore the user namespaces to minimal usability
1009 1009 for ns in self.ns_refs_table:
1010 1010 ns.clear()
1011 1011
1012 1012 # The main execution namespaces must be cleared very carefully,
1013 1013 # skipping the deletion of the builtin-related keys, because doing so
1014 1014 # would cause errors in many object's __del__ methods.
1015 1015 for ns in [self.user_ns, self.user_global_ns]:
1016 1016 drop_keys = set(ns.keys())
1017 1017 drop_keys.discard('__builtin__')
1018 1018 drop_keys.discard('__builtins__')
1019 1019 for k in drop_keys:
1020 1020 del ns[k]
1021 1021
1022 1022 # Restore the user namespaces to minimal usability
1023 1023 self.init_user_ns()
1024 1024
1025 1025 # Restore the default and user aliases
1026 1026 self.alias_manager.clear_aliases()
1027 1027 self.alias_manager.init_aliases()
1028 1028
1029 1029 def reset_selective(self, regex=None):
1030 1030 """Clear selective variables from internal namespaces based on a
1031 1031 specified regular expression.
1032 1032
1033 1033 Parameters
1034 1034 ----------
1035 1035 regex : string or compiled pattern, optional
1036 1036 A regular expression pattern that will be used in searching
1037 1037 variable names in the users namespaces.
1038 1038 """
1039 1039 if regex is not None:
1040 1040 try:
1041 1041 m = re.compile(regex)
1042 1042 except TypeError:
1043 1043 raise TypeError('regex must be a string or compiled pattern')
1044 1044 # Search for keys in each namespace that match the given regex
1045 1045 # If a match is found, delete the key/value pair.
1046 1046 for ns in self.ns_refs_table:
1047 1047 for var in ns:
1048 1048 if m.search(var):
1049 1049 del ns[var]
1050 1050
1051 1051 def push(self, variables, interactive=True):
1052 1052 """Inject a group of variables into the IPython user namespace.
1053 1053
1054 1054 Parameters
1055 1055 ----------
1056 1056 variables : dict, str or list/tuple of str
1057 1057 The variables to inject into the user's namespace. If a dict, a
1058 1058 simple update is done. If a str, the string is assumed to have
1059 1059 variable names separated by spaces. A list/tuple of str can also
1060 1060 be used to give the variable names. If just the variable names are
1061 1061 give (list/tuple/str) then the variable values looked up in the
1062 1062 callers frame.
1063 1063 interactive : bool
1064 1064 If True (default), the variables will be listed with the ``who``
1065 1065 magic.
1066 1066 """
1067 1067 vdict = None
1068 1068
1069 1069 # We need a dict of name/value pairs to do namespace updates.
1070 1070 if isinstance(variables, dict):
1071 1071 vdict = variables
1072 1072 elif isinstance(variables, (basestring, list, tuple)):
1073 1073 if isinstance(variables, basestring):
1074 1074 vlist = variables.split()
1075 1075 else:
1076 1076 vlist = variables
1077 1077 vdict = {}
1078 1078 cf = sys._getframe(1)
1079 1079 for name in vlist:
1080 1080 try:
1081 1081 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1082 1082 except:
1083 1083 print ('Could not get variable %s from %s' %
1084 1084 (name,cf.f_code.co_name))
1085 1085 else:
1086 1086 raise ValueError('variables must be a dict/str/list/tuple')
1087 1087
1088 1088 # Propagate variables to user namespace
1089 1089 self.user_ns.update(vdict)
1090 1090
1091 1091 # And configure interactive visibility
1092 1092 config_ns = self.user_ns_hidden
1093 1093 if interactive:
1094 1094 for name, val in vdict.iteritems():
1095 1095 config_ns.pop(name, None)
1096 1096 else:
1097 1097 for name,val in vdict.iteritems():
1098 1098 config_ns[name] = val
1099 1099
1100 1100 #-------------------------------------------------------------------------
1101 1101 # Things related to object introspection
1102 1102 #-------------------------------------------------------------------------
1103 1103
1104 1104 def _ofind(self, oname, namespaces=None):
1105 1105 """Find an object in the available namespaces.
1106 1106
1107 1107 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1108 1108
1109 1109 Has special code to detect magic functions.
1110 1110 """
1111 1111 #oname = oname.strip()
1112 1112 #print '1- oname: <%r>' % oname # dbg
1113 1113 try:
1114 1114 oname = oname.strip().encode('ascii')
1115 1115 #print '2- oname: <%r>' % oname # dbg
1116 1116 except UnicodeEncodeError:
1117 1117 print 'Python identifiers can only contain ascii characters.'
1118 1118 return dict(found=False)
1119 1119
1120 1120 alias_ns = None
1121 1121 if namespaces is None:
1122 1122 # Namespaces to search in:
1123 1123 # Put them in a list. The order is important so that we
1124 1124 # find things in the same order that Python finds them.
1125 1125 namespaces = [ ('Interactive', self.user_ns),
1126 1126 ('IPython internal', self.internal_ns),
1127 1127 ('Python builtin', __builtin__.__dict__),
1128 1128 ('Alias', self.alias_manager.alias_table),
1129 1129 ]
1130 1130 alias_ns = self.alias_manager.alias_table
1131 1131
1132 1132 # initialize results to 'null'
1133 1133 found = False; obj = None; ospace = None; ds = None;
1134 1134 ismagic = False; isalias = False; parent = None
1135 1135
1136 1136 # We need to special-case 'print', which as of python2.6 registers as a
1137 1137 # function but should only be treated as one if print_function was
1138 1138 # loaded with a future import. In this case, just bail.
1139 1139 if (oname == 'print' and not (self.compile.compiler_flags &
1140 1140 __future__.CO_FUTURE_PRINT_FUNCTION)):
1141 1141 return {'found':found, 'obj':obj, 'namespace':ospace,
1142 1142 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1143 1143
1144 1144 # Look for the given name by splitting it in parts. If the head is
1145 1145 # found, then we look for all the remaining parts as members, and only
1146 1146 # declare success if we can find them all.
1147 1147 oname_parts = oname.split('.')
1148 1148 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1149 1149 for nsname,ns in namespaces:
1150 1150 try:
1151 1151 obj = ns[oname_head]
1152 1152 except KeyError:
1153 1153 continue
1154 1154 else:
1155 1155 #print 'oname_rest:', oname_rest # dbg
1156 1156 for part in oname_rest:
1157 1157 try:
1158 1158 parent = obj
1159 1159 obj = getattr(obj,part)
1160 1160 except:
1161 1161 # Blanket except b/c some badly implemented objects
1162 1162 # allow __getattr__ to raise exceptions other than
1163 1163 # AttributeError, which then crashes IPython.
1164 1164 break
1165 1165 else:
1166 1166 # If we finish the for loop (no break), we got all members
1167 1167 found = True
1168 1168 ospace = nsname
1169 1169 if ns == alias_ns:
1170 1170 isalias = True
1171 1171 break # namespace loop
1172 1172
1173 1173 # Try to see if it's magic
1174 1174 if not found:
1175 1175 if oname.startswith(ESC_MAGIC):
1176 1176 oname = oname[1:]
1177 1177 obj = getattr(self,'magic_'+oname,None)
1178 1178 if obj is not None:
1179 1179 found = True
1180 1180 ospace = 'IPython internal'
1181 1181 ismagic = True
1182 1182
1183 1183 # Last try: special-case some literals like '', [], {}, etc:
1184 1184 if not found and oname_head in ["''",'""','[]','{}','()']:
1185 1185 obj = eval(oname_head)
1186 1186 found = True
1187 1187 ospace = 'Interactive'
1188 1188
1189 1189 return {'found':found, 'obj':obj, 'namespace':ospace,
1190 1190 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1191 1191
1192 1192 def _ofind_property(self, oname, info):
1193 1193 """Second part of object finding, to look for property details."""
1194 1194 if info.found:
1195 1195 # Get the docstring of the class property if it exists.
1196 1196 path = oname.split('.')
1197 1197 root = '.'.join(path[:-1])
1198 1198 if info.parent is not None:
1199 1199 try:
1200 1200 target = getattr(info.parent, '__class__')
1201 1201 # The object belongs to a class instance.
1202 1202 try:
1203 1203 target = getattr(target, path[-1])
1204 1204 # The class defines the object.
1205 1205 if isinstance(target, property):
1206 1206 oname = root + '.__class__.' + path[-1]
1207 1207 info = Struct(self._ofind(oname))
1208 1208 except AttributeError: pass
1209 1209 except AttributeError: pass
1210 1210
1211 1211 # We return either the new info or the unmodified input if the object
1212 1212 # hadn't been found
1213 1213 return info
1214 1214
1215 1215 def _object_find(self, oname, namespaces=None):
1216 1216 """Find an object and return a struct with info about it."""
1217 1217 inf = Struct(self._ofind(oname, namespaces))
1218 1218 return Struct(self._ofind_property(oname, inf))
1219 1219
1220 1220 def _inspect(self, meth, oname, namespaces=None, **kw):
1221 1221 """Generic interface to the inspector system.
1222 1222
1223 1223 This function is meant to be called by pdef, pdoc & friends."""
1224 1224 info = self._object_find(oname)
1225 1225 if info.found:
1226 1226 pmethod = getattr(self.inspector, meth)
1227 1227 formatter = format_screen if info.ismagic else None
1228 1228 if meth == 'pdoc':
1229 1229 pmethod(info.obj, oname, formatter)
1230 1230 elif meth == 'pinfo':
1231 1231 pmethod(info.obj, oname, formatter, info, **kw)
1232 1232 else:
1233 1233 pmethod(info.obj, oname)
1234 1234 else:
1235 1235 print 'Object `%s` not found.' % oname
1236 1236 return 'not found' # so callers can take other action
1237 1237
1238 1238 def object_inspect(self, oname):
1239 1239 info = self._object_find(oname)
1240 1240 if info.found:
1241 1241 return self.inspector.info(info.obj, oname, info=info)
1242 1242 else:
1243 1243 return oinspect.object_info(name=oname, found=False)
1244 1244
1245 1245 #-------------------------------------------------------------------------
1246 1246 # Things related to history management
1247 1247 #-------------------------------------------------------------------------
1248 1248
1249 1249 def init_history(self):
1250 1250 """Sets up the command history, and starts regular autosaves."""
1251 self.history_manager = HistoryManager(shell=self)
1251 self.history_manager = HistoryManager(shell=self, load_history=True)
1252 1252
1253 1253 def save_history(self):
1254 1254 """Save input history to a file (via readline library)."""
1255 1255 self.history_manager.save_history()
1256 1256
1257 1257 def reload_history(self):
1258 1258 """Reload the input history from disk file."""
1259 1259 self.history_manager.reload_history()
1260 1260
1261 1261 def history_saving_wrapper(self, func):
1262 1262 """ Wrap func for readline history saving
1263 1263
1264 1264 Convert func into callable that saves & restores
1265 1265 history around the call """
1266 1266
1267 1267 if self.has_readline:
1268 1268 from IPython.utils import rlineimpl as readline
1269 1269 else:
1270 1270 return func
1271 1271
1272 1272 def wrapper():
1273 1273 self.save_history()
1274 1274 try:
1275 1275 func()
1276 1276 finally:
1277 1277 self.reload_history()
1278 1278 return wrapper
1279 1279
1280 1280 def get_history(self, index=None, raw=False, output=True):
1281 1281 return self.history_manager.get_history(index, raw, output)
1282 1282
1283 1283
1284 1284 #-------------------------------------------------------------------------
1285 1285 # Things related to exception handling and tracebacks (not debugging)
1286 1286 #-------------------------------------------------------------------------
1287 1287
1288 1288 def init_traceback_handlers(self, custom_exceptions):
1289 1289 # Syntax error handler.
1290 1290 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1291 1291
1292 1292 # The interactive one is initialized with an offset, meaning we always
1293 1293 # want to remove the topmost item in the traceback, which is our own
1294 1294 # internal code. Valid modes: ['Plain','Context','Verbose']
1295 1295 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1296 1296 color_scheme='NoColor',
1297 1297 tb_offset = 1,
1298 1298 check_cache=self.compile.check_cache)
1299 1299
1300 1300 # The instance will store a pointer to the system-wide exception hook,
1301 1301 # so that runtime code (such as magics) can access it. This is because
1302 1302 # during the read-eval loop, it may get temporarily overwritten.
1303 1303 self.sys_excepthook = sys.excepthook
1304 1304
1305 1305 # and add any custom exception handlers the user may have specified
1306 1306 self.set_custom_exc(*custom_exceptions)
1307 1307
1308 1308 # Set the exception mode
1309 1309 self.InteractiveTB.set_mode(mode=self.xmode)
1310 1310
1311 1311 def set_custom_exc(self, exc_tuple, handler):
1312 1312 """set_custom_exc(exc_tuple,handler)
1313 1313
1314 1314 Set a custom exception handler, which will be called if any of the
1315 1315 exceptions in exc_tuple occur in the mainloop (specifically, in the
1316 1316 run_code() method.
1317 1317
1318 1318 Inputs:
1319 1319
1320 1320 - exc_tuple: a *tuple* of valid exceptions to call the defined
1321 1321 handler for. It is very important that you use a tuple, and NOT A
1322 1322 LIST here, because of the way Python's except statement works. If
1323 1323 you only want to trap a single exception, use a singleton tuple:
1324 1324
1325 1325 exc_tuple == (MyCustomException,)
1326 1326
1327 1327 - handler: this must be defined as a function with the following
1328 1328 basic interface::
1329 1329
1330 1330 def my_handler(self, etype, value, tb, tb_offset=None)
1331 1331 ...
1332 1332 # The return value must be
1333 1333 return structured_traceback
1334 1334
1335 1335 This will be made into an instance method (via types.MethodType)
1336 1336 of IPython itself, and it will be called if any of the exceptions
1337 1337 listed in the exc_tuple are caught. If the handler is None, an
1338 1338 internal basic one is used, which just prints basic info.
1339 1339
1340 1340 WARNING: by putting in your own exception handler into IPython's main
1341 1341 execution loop, you run a very good chance of nasty crashes. This
1342 1342 facility should only be used if you really know what you are doing."""
1343 1343
1344 1344 assert type(exc_tuple)==type(()) , \
1345 1345 "The custom exceptions must be given AS A TUPLE."
1346 1346
1347 1347 def dummy_handler(self,etype,value,tb):
1348 1348 print '*** Simple custom exception handler ***'
1349 1349 print 'Exception type :',etype
1350 1350 print 'Exception value:',value
1351 1351 print 'Traceback :',tb
1352 1352 print 'Source code :','\n'.join(self.buffer)
1353 1353
1354 1354 if handler is None: handler = dummy_handler
1355 1355
1356 1356 self.CustomTB = types.MethodType(handler,self)
1357 1357 self.custom_exceptions = exc_tuple
1358 1358
1359 1359 def excepthook(self, etype, value, tb):
1360 1360 """One more defense for GUI apps that call sys.excepthook.
1361 1361
1362 1362 GUI frameworks like wxPython trap exceptions and call
1363 1363 sys.excepthook themselves. I guess this is a feature that
1364 1364 enables them to keep running after exceptions that would
1365 1365 otherwise kill their mainloop. This is a bother for IPython
1366 1366 which excepts to catch all of the program exceptions with a try:
1367 1367 except: statement.
1368 1368
1369 1369 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1370 1370 any app directly invokes sys.excepthook, it will look to the user like
1371 1371 IPython crashed. In order to work around this, we can disable the
1372 1372 CrashHandler and replace it with this excepthook instead, which prints a
1373 1373 regular traceback using our InteractiveTB. In this fashion, apps which
1374 1374 call sys.excepthook will generate a regular-looking exception from
1375 1375 IPython, and the CrashHandler will only be triggered by real IPython
1376 1376 crashes.
1377 1377
1378 1378 This hook should be used sparingly, only in places which are not likely
1379 1379 to be true IPython errors.
1380 1380 """
1381 1381 self.showtraceback((etype,value,tb),tb_offset=0)
1382 1382
1383 1383 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1384 1384 exception_only=False):
1385 1385 """Display the exception that just occurred.
1386 1386
1387 1387 If nothing is known about the exception, this is the method which
1388 1388 should be used throughout the code for presenting user tracebacks,
1389 1389 rather than directly invoking the InteractiveTB object.
1390 1390
1391 1391 A specific showsyntaxerror() also exists, but this method can take
1392 1392 care of calling it if needed, so unless you are explicitly catching a
1393 1393 SyntaxError exception, don't try to analyze the stack manually and
1394 1394 simply call this method."""
1395 1395
1396 1396 try:
1397 1397 if exc_tuple is None:
1398 1398 etype, value, tb = sys.exc_info()
1399 1399 else:
1400 1400 etype, value, tb = exc_tuple
1401 1401
1402 1402 if etype is None:
1403 1403 if hasattr(sys, 'last_type'):
1404 1404 etype, value, tb = sys.last_type, sys.last_value, \
1405 1405 sys.last_traceback
1406 1406 else:
1407 1407 self.write_err('No traceback available to show.\n')
1408 1408 return
1409 1409
1410 1410 if etype is SyntaxError:
1411 1411 # Though this won't be called by syntax errors in the input
1412 1412 # line, there may be SyntaxError cases whith imported code.
1413 1413 self.showsyntaxerror(filename)
1414 1414 elif etype is UsageError:
1415 1415 print "UsageError:", value
1416 1416 else:
1417 1417 # WARNING: these variables are somewhat deprecated and not
1418 1418 # necessarily safe to use in a threaded environment, but tools
1419 1419 # like pdb depend on their existence, so let's set them. If we
1420 1420 # find problems in the field, we'll need to revisit their use.
1421 1421 sys.last_type = etype
1422 1422 sys.last_value = value
1423 1423 sys.last_traceback = tb
1424 1424
1425 1425 if etype in self.custom_exceptions:
1426 1426 # FIXME: Old custom traceback objects may just return a
1427 1427 # string, in that case we just put it into a list
1428 1428 stb = self.CustomTB(etype, value, tb, tb_offset)
1429 1429 if isinstance(ctb, basestring):
1430 1430 stb = [stb]
1431 1431 else:
1432 1432 if exception_only:
1433 1433 stb = ['An exception has occurred, use %tb to see '
1434 1434 'the full traceback.\n']
1435 1435 stb.extend(self.InteractiveTB.get_exception_only(etype,
1436 1436 value))
1437 1437 else:
1438 1438 stb = self.InteractiveTB.structured_traceback(etype,
1439 1439 value, tb, tb_offset=tb_offset)
1440 1440 # FIXME: the pdb calling should be done by us, not by
1441 1441 # the code computing the traceback.
1442 1442 if self.InteractiveTB.call_pdb:
1443 1443 # pdb mucks up readline, fix it back
1444 1444 self.set_readline_completer()
1445 1445
1446 1446 # Actually show the traceback
1447 1447 self._showtraceback(etype, value, stb)
1448 1448
1449 1449 except KeyboardInterrupt:
1450 1450 self.write_err("\nKeyboardInterrupt\n")
1451 1451
1452 1452 def _showtraceback(self, etype, evalue, stb):
1453 1453 """Actually show a traceback.
1454 1454
1455 1455 Subclasses may override this method to put the traceback on a different
1456 1456 place, like a side channel.
1457 1457 """
1458 1458 print >> io.Term.cout, self.InteractiveTB.stb2text(stb)
1459 1459
1460 1460 def showsyntaxerror(self, filename=None):
1461 1461 """Display the syntax error that just occurred.
1462 1462
1463 1463 This doesn't display a stack trace because there isn't one.
1464 1464
1465 1465 If a filename is given, it is stuffed in the exception instead
1466 1466 of what was there before (because Python's parser always uses
1467 1467 "<string>" when reading from a string).
1468 1468 """
1469 1469 etype, value, last_traceback = sys.exc_info()
1470 1470
1471 1471 # See note about these variables in showtraceback() above
1472 1472 sys.last_type = etype
1473 1473 sys.last_value = value
1474 1474 sys.last_traceback = last_traceback
1475 1475
1476 1476 if filename and etype is SyntaxError:
1477 1477 # Work hard to stuff the correct filename in the exception
1478 1478 try:
1479 1479 msg, (dummy_filename, lineno, offset, line) = value
1480 1480 except:
1481 1481 # Not the format we expect; leave it alone
1482 1482 pass
1483 1483 else:
1484 1484 # Stuff in the right filename
1485 1485 try:
1486 1486 # Assume SyntaxError is a class exception
1487 1487 value = SyntaxError(msg, (filename, lineno, offset, line))
1488 1488 except:
1489 1489 # If that failed, assume SyntaxError is a string
1490 1490 value = msg, (filename, lineno, offset, line)
1491 1491 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1492 1492 self._showtraceback(etype, value, stb)
1493 1493
1494 1494 #-------------------------------------------------------------------------
1495 1495 # Things related to readline
1496 1496 #-------------------------------------------------------------------------
1497 1497
1498 1498 def init_readline(self):
1499 1499 """Command history completion/saving/reloading."""
1500 1500
1501 1501 if self.readline_use:
1502 1502 import IPython.utils.rlineimpl as readline
1503 1503
1504 1504 self.rl_next_input = None
1505 1505 self.rl_do_indent = False
1506 1506
1507 1507 if not self.readline_use or not readline.have_readline:
1508 1508 self.has_readline = False
1509 1509 self.readline = None
1510 1510 # Set a number of methods that depend on readline to be no-op
1511 1511 self.set_readline_completer = no_op
1512 1512 self.set_custom_completer = no_op
1513 1513 self.set_completer_frame = no_op
1514 1514 warn('Readline services not available or not loaded.')
1515 1515 else:
1516 1516 self.has_readline = True
1517 1517 self.readline = readline
1518 1518 sys.modules['readline'] = readline
1519 1519
1520 1520 # Platform-specific configuration
1521 1521 if os.name == 'nt':
1522 1522 # FIXME - check with Frederick to see if we can harmonize
1523 1523 # naming conventions with pyreadline to avoid this
1524 1524 # platform-dependent check
1525 1525 self.readline_startup_hook = readline.set_pre_input_hook
1526 1526 else:
1527 1527 self.readline_startup_hook = readline.set_startup_hook
1528 1528
1529 1529 # Load user's initrc file (readline config)
1530 1530 # Or if libedit is used, load editrc.
1531 1531 inputrc_name = os.environ.get('INPUTRC')
1532 1532 if inputrc_name is None:
1533 1533 home_dir = get_home_dir()
1534 1534 if home_dir is not None:
1535 1535 inputrc_name = '.inputrc'
1536 1536 if readline.uses_libedit:
1537 1537 inputrc_name = '.editrc'
1538 1538 inputrc_name = os.path.join(home_dir, inputrc_name)
1539 1539 if os.path.isfile(inputrc_name):
1540 1540 try:
1541 1541 readline.read_init_file(inputrc_name)
1542 1542 except:
1543 1543 warn('Problems reading readline initialization file <%s>'
1544 1544 % inputrc_name)
1545 1545
1546 1546 # Configure readline according to user's prefs
1547 1547 # This is only done if GNU readline is being used. If libedit
1548 1548 # is being used (as on Leopard) the readline config is
1549 1549 # not run as the syntax for libedit is different.
1550 1550 if not readline.uses_libedit:
1551 1551 for rlcommand in self.readline_parse_and_bind:
1552 1552 #print "loading rl:",rlcommand # dbg
1553 1553 readline.parse_and_bind(rlcommand)
1554 1554
1555 1555 # Remove some chars from the delimiters list. If we encounter
1556 1556 # unicode chars, discard them.
1557 1557 delims = readline.get_completer_delims().encode("ascii", "ignore")
1558 1558 delims = delims.translate(None, self.readline_remove_delims)
1559 1559 delims = delims.replace(ESC_MAGIC, '')
1560 1560 readline.set_completer_delims(delims)
1561 1561 # otherwise we end up with a monster history after a while:
1562 1562 readline.set_history_length(self.history_length)
1563 try:
1564 #print '*** Reading readline history' # dbg
1565 self.reload_history()
1566 except IOError:
1567 pass # It doesn't exist yet.
1563
1564 self.history_manager.populate_readline_history()
1568 1565
1569 1566 # Configure auto-indent for all platforms
1570 1567 self.set_autoindent(self.autoindent)
1571 1568
1572 1569 def set_next_input(self, s):
1573 1570 """ Sets the 'default' input string for the next command line.
1574 1571
1575 1572 Requires readline.
1576 1573
1577 1574 Example:
1578 1575
1579 1576 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1580 1577 [D:\ipython]|2> Hello Word_ # cursor is here
1581 1578 """
1582 1579
1583 1580 self.rl_next_input = s
1584 1581
1585 1582 # Maybe move this to the terminal subclass?
1586 1583 def pre_readline(self):
1587 1584 """readline hook to be used at the start of each line.
1588 1585
1589 1586 Currently it handles auto-indent only."""
1590 1587
1591 1588 if self.rl_do_indent:
1592 1589 self.readline.insert_text(self._indent_current_str())
1593 1590 if self.rl_next_input is not None:
1594 1591 self.readline.insert_text(self.rl_next_input)
1595 1592 self.rl_next_input = None
1596 1593
1597 1594 def _indent_current_str(self):
1598 1595 """return the current level of indentation as a string"""
1599 1596 return self.input_splitter.indent_spaces * ' '
1600 1597
1601 1598 #-------------------------------------------------------------------------
1602 1599 # Things related to text completion
1603 1600 #-------------------------------------------------------------------------
1604 1601
1605 1602 def init_completer(self):
1606 1603 """Initialize the completion machinery.
1607 1604
1608 1605 This creates completion machinery that can be used by client code,
1609 1606 either interactively in-process (typically triggered by the readline
1610 1607 library), programatically (such as in test suites) or out-of-prcess
1611 1608 (typically over the network by remote frontends).
1612 1609 """
1613 1610 from IPython.core.completer import IPCompleter
1614 1611 from IPython.core.completerlib import (module_completer,
1615 1612 magic_run_completer, cd_completer)
1616 1613
1617 1614 self.Completer = IPCompleter(self,
1618 1615 self.user_ns,
1619 1616 self.user_global_ns,
1620 1617 self.readline_omit__names,
1621 1618 self.alias_manager.alias_table,
1622 1619 self.has_readline)
1623 1620
1624 1621 # Add custom completers to the basic ones built into IPCompleter
1625 1622 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1626 1623 self.strdispatchers['complete_command'] = sdisp
1627 1624 self.Completer.custom_completers = sdisp
1628 1625
1629 1626 self.set_hook('complete_command', module_completer, str_key = 'import')
1630 1627 self.set_hook('complete_command', module_completer, str_key = 'from')
1631 1628 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1632 1629 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1633 1630
1634 1631 # Only configure readline if we truly are using readline. IPython can
1635 1632 # do tab-completion over the network, in GUIs, etc, where readline
1636 1633 # itself may be absent
1637 1634 if self.has_readline:
1638 1635 self.set_readline_completer()
1639 1636
1640 1637 def complete(self, text, line=None, cursor_pos=None):
1641 1638 """Return the completed text and a list of completions.
1642 1639
1643 1640 Parameters
1644 1641 ----------
1645 1642
1646 1643 text : string
1647 1644 A string of text to be completed on. It can be given as empty and
1648 1645 instead a line/position pair are given. In this case, the
1649 1646 completer itself will split the line like readline does.
1650 1647
1651 1648 line : string, optional
1652 1649 The complete line that text is part of.
1653 1650
1654 1651 cursor_pos : int, optional
1655 1652 The position of the cursor on the input line.
1656 1653
1657 1654 Returns
1658 1655 -------
1659 1656 text : string
1660 1657 The actual text that was completed.
1661 1658
1662 1659 matches : list
1663 1660 A sorted list with all possible completions.
1664 1661
1665 1662 The optional arguments allow the completion to take more context into
1666 1663 account, and are part of the low-level completion API.
1667 1664
1668 1665 This is a wrapper around the completion mechanism, similar to what
1669 1666 readline does at the command line when the TAB key is hit. By
1670 1667 exposing it as a method, it can be used by other non-readline
1671 1668 environments (such as GUIs) for text completion.
1672 1669
1673 1670 Simple usage example:
1674 1671
1675 1672 In [1]: x = 'hello'
1676 1673
1677 1674 In [2]: _ip.complete('x.l')
1678 1675 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1679 1676 """
1680 1677
1681 1678 # Inject names into __builtin__ so we can complete on the added names.
1682 1679 with self.builtin_trap:
1683 1680 return self.Completer.complete(text, line, cursor_pos)
1684 1681
1685 1682 def set_custom_completer(self, completer, pos=0):
1686 1683 """Adds a new custom completer function.
1687 1684
1688 1685 The position argument (defaults to 0) is the index in the completers
1689 1686 list where you want the completer to be inserted."""
1690 1687
1691 1688 newcomp = types.MethodType(completer,self.Completer)
1692 1689 self.Completer.matchers.insert(pos,newcomp)
1693 1690
1694 1691 def set_readline_completer(self):
1695 1692 """Reset readline's completer to be our own."""
1696 1693 self.readline.set_completer(self.Completer.rlcomplete)
1697 1694
1698 1695 def set_completer_frame(self, frame=None):
1699 1696 """Set the frame of the completer."""
1700 1697 if frame:
1701 1698 self.Completer.namespace = frame.f_locals
1702 1699 self.Completer.global_namespace = frame.f_globals
1703 1700 else:
1704 1701 self.Completer.namespace = self.user_ns
1705 1702 self.Completer.global_namespace = self.user_global_ns
1706 1703
1707 1704 #-------------------------------------------------------------------------
1708 1705 # Things related to magics
1709 1706 #-------------------------------------------------------------------------
1710 1707
1711 1708 def init_magics(self):
1712 1709 # FIXME: Move the color initialization to the DisplayHook, which
1713 1710 # should be split into a prompt manager and displayhook. We probably
1714 1711 # even need a centralize colors management object.
1715 1712 self.magic_colors(self.colors)
1716 1713 # History was moved to a separate module
1717 1714 from . import history
1718 1715 history.init_ipython(self)
1719 1716
1720 1717 def magic(self,arg_s):
1721 1718 """Call a magic function by name.
1722 1719
1723 1720 Input: a string containing the name of the magic function to call and
1724 1721 any additional arguments to be passed to the magic.
1725 1722
1726 1723 magic('name -opt foo bar') is equivalent to typing at the ipython
1727 1724 prompt:
1728 1725
1729 1726 In[1]: %name -opt foo bar
1730 1727
1731 1728 To call a magic without arguments, simply use magic('name').
1732 1729
1733 1730 This provides a proper Python function to call IPython's magics in any
1734 1731 valid Python code you can type at the interpreter, including loops and
1735 1732 compound statements.
1736 1733 """
1737 1734 args = arg_s.split(' ',1)
1738 1735 magic_name = args[0]
1739 1736 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1740 1737
1741 1738 try:
1742 1739 magic_args = args[1]
1743 1740 except IndexError:
1744 1741 magic_args = ''
1745 1742 fn = getattr(self,'magic_'+magic_name,None)
1746 1743 if fn is None:
1747 1744 error("Magic function `%s` not found." % magic_name)
1748 1745 else:
1749 1746 magic_args = self.var_expand(magic_args,1)
1750 1747 with nested(self.builtin_trap,):
1751 1748 result = fn(magic_args)
1752 1749 return result
1753 1750
1754 1751 def define_magic(self, magicname, func):
1755 1752 """Expose own function as magic function for ipython
1756 1753
1757 1754 def foo_impl(self,parameter_s=''):
1758 1755 'My very own magic!. (Use docstrings, IPython reads them).'
1759 1756 print 'Magic function. Passed parameter is between < >:'
1760 1757 print '<%s>' % parameter_s
1761 1758 print 'The self object is:',self
1762 1759
1763 1760 self.define_magic('foo',foo_impl)
1764 1761 """
1765 1762
1766 1763 import new
1767 1764 im = types.MethodType(func,self)
1768 1765 old = getattr(self, "magic_" + magicname, None)
1769 1766 setattr(self, "magic_" + magicname, im)
1770 1767 return old
1771 1768
1772 1769 #-------------------------------------------------------------------------
1773 1770 # Things related to macros
1774 1771 #-------------------------------------------------------------------------
1775 1772
1776 1773 def define_macro(self, name, themacro):
1777 1774 """Define a new macro
1778 1775
1779 1776 Parameters
1780 1777 ----------
1781 1778 name : str
1782 1779 The name of the macro.
1783 1780 themacro : str or Macro
1784 1781 The action to do upon invoking the macro. If a string, a new
1785 1782 Macro object is created by passing the string to it.
1786 1783 """
1787 1784
1788 1785 from IPython.core import macro
1789 1786
1790 1787 if isinstance(themacro, basestring):
1791 1788 themacro = macro.Macro(themacro)
1792 1789 if not isinstance(themacro, macro.Macro):
1793 1790 raise ValueError('A macro must be a string or a Macro instance.')
1794 1791 self.user_ns[name] = themacro
1795 1792
1796 1793 #-------------------------------------------------------------------------
1797 1794 # Things related to the running of system commands
1798 1795 #-------------------------------------------------------------------------
1799 1796
1800 1797 def system(self, cmd):
1801 1798 """Call the given cmd in a subprocess.
1802 1799
1803 1800 Parameters
1804 1801 ----------
1805 1802 cmd : str
1806 1803 Command to execute (can not end in '&', as bacground processes are
1807 1804 not supported.
1808 1805 """
1809 1806 # We do not support backgrounding processes because we either use
1810 1807 # pexpect or pipes to read from. Users can always just call
1811 1808 # os.system() if they really want a background process.
1812 1809 if cmd.endswith('&'):
1813 1810 raise OSError("Background processes not supported.")
1814 1811
1815 1812 return system(self.var_expand(cmd, depth=2))
1816 1813
1817 1814 def getoutput(self, cmd, split=True):
1818 1815 """Get output (possibly including stderr) from a subprocess.
1819 1816
1820 1817 Parameters
1821 1818 ----------
1822 1819 cmd : str
1823 1820 Command to execute (can not end in '&', as background processes are
1824 1821 not supported.
1825 1822 split : bool, optional
1826 1823
1827 1824 If True, split the output into an IPython SList. Otherwise, an
1828 1825 IPython LSString is returned. These are objects similar to normal
1829 1826 lists and strings, with a few convenience attributes for easier
1830 1827 manipulation of line-based output. You can use '?' on them for
1831 1828 details.
1832 1829 """
1833 1830 if cmd.endswith('&'):
1834 1831 raise OSError("Background processes not supported.")
1835 1832 out = getoutput(self.var_expand(cmd, depth=2))
1836 1833 if split:
1837 1834 out = SList(out.splitlines())
1838 1835 else:
1839 1836 out = LSString(out)
1840 1837 return out
1841 1838
1842 1839 #-------------------------------------------------------------------------
1843 1840 # Things related to aliases
1844 1841 #-------------------------------------------------------------------------
1845 1842
1846 1843 def init_alias(self):
1847 1844 self.alias_manager = AliasManager(shell=self, config=self.config)
1848 1845 self.ns_table['alias'] = self.alias_manager.alias_table,
1849 1846
1850 1847 #-------------------------------------------------------------------------
1851 1848 # Things related to extensions and plugins
1852 1849 #-------------------------------------------------------------------------
1853 1850
1854 1851 def init_extension_manager(self):
1855 1852 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1856 1853
1857 1854 def init_plugin_manager(self):
1858 1855 self.plugin_manager = PluginManager(config=self.config)
1859 1856
1860 1857 #-------------------------------------------------------------------------
1861 1858 # Things related to payloads
1862 1859 #-------------------------------------------------------------------------
1863 1860
1864 1861 def init_payload(self):
1865 1862 self.payload_manager = PayloadManager(config=self.config)
1866 1863
1867 1864 #-------------------------------------------------------------------------
1868 1865 # Things related to the prefilter
1869 1866 #-------------------------------------------------------------------------
1870 1867
1871 1868 def init_prefilter(self):
1872 1869 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1873 1870 # Ultimately this will be refactored in the new interpreter code, but
1874 1871 # for now, we should expose the main prefilter method (there's legacy
1875 1872 # code out there that may rely on this).
1876 1873 self.prefilter = self.prefilter_manager.prefilter_lines
1877 1874
1878 1875 def auto_rewrite_input(self, cmd):
1879 1876 """Print to the screen the rewritten form of the user's command.
1880 1877
1881 1878 This shows visual feedback by rewriting input lines that cause
1882 1879 automatic calling to kick in, like::
1883 1880
1884 1881 /f x
1885 1882
1886 1883 into::
1887 1884
1888 1885 ------> f(x)
1889 1886
1890 1887 after the user's input prompt. This helps the user understand that the
1891 1888 input line was transformed automatically by IPython.
1892 1889 """
1893 1890 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1894 1891
1895 1892 try:
1896 1893 # plain ascii works better w/ pyreadline, on some machines, so
1897 1894 # we use it and only print uncolored rewrite if we have unicode
1898 1895 rw = str(rw)
1899 1896 print >> IPython.utils.io.Term.cout, rw
1900 1897 except UnicodeEncodeError:
1901 1898 print "------> " + cmd
1902 1899
1903 1900 #-------------------------------------------------------------------------
1904 1901 # Things related to extracting values/expressions from kernel and user_ns
1905 1902 #-------------------------------------------------------------------------
1906 1903
1907 1904 def _simple_error(self):
1908 1905 etype, value = sys.exc_info()[:2]
1909 1906 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
1910 1907
1911 1908 def user_variables(self, names):
1912 1909 """Get a list of variable names from the user's namespace.
1913 1910
1914 1911 Parameters
1915 1912 ----------
1916 1913 names : list of strings
1917 1914 A list of names of variables to be read from the user namespace.
1918 1915
1919 1916 Returns
1920 1917 -------
1921 1918 A dict, keyed by the input names and with the repr() of each value.
1922 1919 """
1923 1920 out = {}
1924 1921 user_ns = self.user_ns
1925 1922 for varname in names:
1926 1923 try:
1927 1924 value = repr(user_ns[varname])
1928 1925 except:
1929 1926 value = self._simple_error()
1930 1927 out[varname] = value
1931 1928 return out
1932 1929
1933 1930 def user_expressions(self, expressions):
1934 1931 """Evaluate a dict of expressions in the user's namespace.
1935 1932
1936 1933 Parameters
1937 1934 ----------
1938 1935 expressions : dict
1939 1936 A dict with string keys and string values. The expression values
1940 1937 should be valid Python expressions, each of which will be evaluated
1941 1938 in the user namespace.
1942 1939
1943 1940 Returns
1944 1941 -------
1945 1942 A dict, keyed like the input expressions dict, with the repr() of each
1946 1943 value.
1947 1944 """
1948 1945 out = {}
1949 1946 user_ns = self.user_ns
1950 1947 global_ns = self.user_global_ns
1951 1948 for key, expr in expressions.iteritems():
1952 1949 try:
1953 1950 value = repr(eval(expr, global_ns, user_ns))
1954 1951 except:
1955 1952 value = self._simple_error()
1956 1953 out[key] = value
1957 1954 return out
1958 1955
1959 1956 #-------------------------------------------------------------------------
1960 1957 # Things related to the running of code
1961 1958 #-------------------------------------------------------------------------
1962 1959
1963 1960 def ex(self, cmd):
1964 1961 """Execute a normal python statement in user namespace."""
1965 1962 with nested(self.builtin_trap,):
1966 1963 exec cmd in self.user_global_ns, self.user_ns
1967 1964
1968 1965 def ev(self, expr):
1969 1966 """Evaluate python expression expr in user namespace.
1970 1967
1971 1968 Returns the result of evaluation
1972 1969 """
1973 1970 with nested(self.builtin_trap,):
1974 1971 return eval(expr, self.user_global_ns, self.user_ns)
1975 1972
1976 1973 def safe_execfile(self, fname, *where, **kw):
1977 1974 """A safe version of the builtin execfile().
1978 1975
1979 1976 This version will never throw an exception, but instead print
1980 1977 helpful error messages to the screen. This only works on pure
1981 1978 Python files with the .py extension.
1982 1979
1983 1980 Parameters
1984 1981 ----------
1985 1982 fname : string
1986 1983 The name of the file to be executed.
1987 1984 where : tuple
1988 1985 One or two namespaces, passed to execfile() as (globals,locals).
1989 1986 If only one is given, it is passed as both.
1990 1987 exit_ignore : bool (False)
1991 1988 If True, then silence SystemExit for non-zero status (it is always
1992 1989 silenced for zero status, as it is so common).
1993 1990 """
1994 1991 kw.setdefault('exit_ignore', False)
1995 1992
1996 1993 fname = os.path.abspath(os.path.expanduser(fname))
1997 1994
1998 1995 # Make sure we have a .py file
1999 1996 if not fname.endswith('.py'):
2000 1997 warn('File must end with .py to be run using execfile: <%s>' % fname)
2001 1998
2002 1999 # Make sure we can open the file
2003 2000 try:
2004 2001 with open(fname) as thefile:
2005 2002 pass
2006 2003 except:
2007 2004 warn('Could not open file <%s> for safe execution.' % fname)
2008 2005 return
2009 2006
2010 2007 # Find things also in current directory. This is needed to mimic the
2011 2008 # behavior of running a script from the system command line, where
2012 2009 # Python inserts the script's directory into sys.path
2013 2010 dname = os.path.dirname(fname)
2014 2011
2015 2012 with prepended_to_syspath(dname):
2016 2013 try:
2017 2014 execfile(fname,*where)
2018 2015 except SystemExit, status:
2019 2016 # If the call was made with 0 or None exit status (sys.exit(0)
2020 2017 # or sys.exit() ), don't bother showing a traceback, as both of
2021 2018 # these are considered normal by the OS:
2022 2019 # > python -c'import sys;sys.exit(0)'; echo $?
2023 2020 # 0
2024 2021 # > python -c'import sys;sys.exit()'; echo $?
2025 2022 # 0
2026 2023 # For other exit status, we show the exception unless
2027 2024 # explicitly silenced, but only in short form.
2028 2025 if status.code not in (0, None) and not kw['exit_ignore']:
2029 2026 self.showtraceback(exception_only=True)
2030 2027 except:
2031 2028 self.showtraceback()
2032 2029
2033 2030 def safe_execfile_ipy(self, fname):
2034 2031 """Like safe_execfile, but for .ipy files with IPython syntax.
2035 2032
2036 2033 Parameters
2037 2034 ----------
2038 2035 fname : str
2039 2036 The name of the file to execute. The filename must have a
2040 2037 .ipy extension.
2041 2038 """
2042 2039 fname = os.path.abspath(os.path.expanduser(fname))
2043 2040
2044 2041 # Make sure we have a .py file
2045 2042 if not fname.endswith('.ipy'):
2046 2043 warn('File must end with .py to be run using execfile: <%s>' % fname)
2047 2044
2048 2045 # Make sure we can open the file
2049 2046 try:
2050 2047 with open(fname) as thefile:
2051 2048 pass
2052 2049 except:
2053 2050 warn('Could not open file <%s> for safe execution.' % fname)
2054 2051 return
2055 2052
2056 2053 # Find things also in current directory. This is needed to mimic the
2057 2054 # behavior of running a script from the system command line, where
2058 2055 # Python inserts the script's directory into sys.path
2059 2056 dname = os.path.dirname(fname)
2060 2057
2061 2058 with prepended_to_syspath(dname):
2062 2059 try:
2063 2060 with open(fname) as thefile:
2064 2061 # self.run_cell currently captures all exceptions
2065 2062 # raised in user code. It would be nice if there were
2066 2063 # versions of runlines, execfile that did raise, so
2067 2064 # we could catch the errors.
2068 2065 self.run_cell(thefile.read())
2069 2066 except:
2070 2067 self.showtraceback()
2071 2068 warn('Unknown failure executing file: <%s>' % fname)
2072 2069
2073 2070 def run_cell(self, cell):
2074 2071 """Run the contents of an entire multiline 'cell' of code.
2075 2072
2076 2073 The cell is split into separate blocks which can be executed
2077 2074 individually. Then, based on how many blocks there are, they are
2078 2075 executed as follows:
2079 2076
2080 2077 - A single block: 'single' mode.
2081 2078
2082 2079 If there's more than one block, it depends:
2083 2080
2084 2081 - if the last one is no more than two lines long, run all but the last
2085 2082 in 'exec' mode and the very last one in 'single' mode. This makes it
2086 2083 easy to type simple expressions at the end to see computed values. -
2087 2084 otherwise (last one is also multiline), run all in 'exec' mode
2088 2085
2089 2086 When code is executed in 'single' mode, :func:`sys.displayhook` fires,
2090 2087 results are displayed and output prompts are computed. In 'exec' mode,
2091 2088 no results are displayed unless :func:`print` is called explicitly;
2092 2089 this mode is more akin to running a script.
2093 2090
2094 2091 Parameters
2095 2092 ----------
2096 2093 cell : str
2097 2094 A single or multiline string.
2098 2095 """
2099 2096
2100 2097 # We need to break up the input into executable blocks that can be run
2101 2098 # in 'single' mode, to provide comfortable user behavior.
2102 2099 blocks = self.input_splitter.split_blocks(cell)
2103 2100
2104 2101 if not blocks:
2105 2102 return
2106 2103
2107 2104 # Store the 'ipython' version of the cell as well, since that's what
2108 2105 # needs to go into the translated history and get executed (the
2109 2106 # original cell may contain non-python syntax).
2110 2107 ipy_cell = ''.join(blocks)
2111 2108
2112 2109 # Store raw and processed history
2113 2110 self.history_manager.store_inputs(ipy_cell, cell)
2114 2111
2115 2112 self.logger.log(ipy_cell, cell)
2116 2113
2117 2114 # All user code execution must happen with our context managers active
2118 2115 with nested(self.builtin_trap, self.display_trap):
2119 2116
2120 2117 # Single-block input should behave like an interactive prompt
2121 2118 if len(blocks) == 1:
2122 2119 # since we return here, we need to update the execution count
2123 2120 out = self.run_one_block(blocks[0])
2124 2121 self.execution_count += 1
2125 2122 return out
2126 2123
2127 2124 # In multi-block input, if the last block is a simple (one-two
2128 2125 # lines) expression, run it in single mode so it produces output.
2129 2126 # Otherwise just feed the whole thing to run_code. This seems like
2130 2127 # a reasonable usability design.
2131 2128 last = blocks[-1]
2132 2129 last_nlines = len(last.splitlines())
2133 2130
2134 2131 # Note: below, whenever we call run_code, we must sync history
2135 2132 # ourselves, because run_code is NOT meant to manage history at all.
2136 2133 if last_nlines < 2:
2137 2134 # Here we consider the cell split between 'body' and 'last',
2138 2135 # store all history and execute 'body', and if successful, then
2139 2136 # proceed to execute 'last'.
2140 2137
2141 2138 # Get the main body to run as a cell
2142 2139 ipy_body = ''.join(blocks[:-1])
2143 2140 retcode = self.run_source(ipy_body, symbol='exec',
2144 2141 post_execute=False)
2145 2142 if retcode==0:
2146 2143 # And the last expression via runlines so it produces output
2147 2144 self.run_one_block(last)
2148 2145 else:
2149 2146 # Run the whole cell as one entity, storing both raw and
2150 2147 # processed input in history
2151 2148 self.run_source(ipy_cell, symbol='exec')
2152 2149
2153 2150 # Each cell is a *single* input, regardless of how many lines it has
2154 2151 self.execution_count += 1
2155 2152
2156 2153 def run_one_block(self, block):
2157 2154 """Run a single interactive block of source code.
2158 2155
2159 2156 If the block is single-line, dynamic transformations are applied to it
2160 2157 (like automagics, autocall and alias recognition).
2161 2158
2162 2159 If the block is multi-line, it must consist of valid Python code only.
2163 2160
2164 2161 Parameters
2165 2162 ----------
2166 2163 block : string
2167 2164 A (possibly multiline) string of code to be executed.
2168 2165
2169 2166 Returns
2170 2167 -------
2171 2168 The output of the underlying execution method used, be it
2172 2169 :meth:`run_source` or :meth:`run_single_line`.
2173 2170 """
2174 2171 if len(block.splitlines()) <= 1:
2175 2172 out = self.run_single_line(block)
2176 2173 else:
2177 2174 # Call run_source, which correctly compiles the input cell.
2178 2175 # run_code must only be called when we know we have a code object,
2179 2176 # as it does a naked exec and the compilation mode may not be what
2180 2177 # we wanted.
2181 2178 out = self.run_source(block)
2182 2179 return out
2183 2180
2184 2181 def run_single_line(self, line):
2185 2182 """Run a single-line interactive statement.
2186 2183
2187 2184 This assumes the input has been transformed to IPython syntax by
2188 2185 applying all static transformations (those with an explicit prefix like
2189 2186 % or !), but it will further try to apply the dynamic ones.
2190 2187
2191 2188 It does not update history.
2192 2189 """
2193 2190 tline = self.prefilter_manager.prefilter_line(line)
2194 2191 return self.run_source(tline)
2195 2192
2196 2193 # PENDING REMOVAL: this method is slated for deletion, once our new
2197 2194 # input logic has been 100% moved to frontends and is stable.
2198 2195 def runlines(self, lines, clean=False):
2199 2196 """Run a string of one or more lines of source.
2200 2197
2201 2198 This method is capable of running a string containing multiple source
2202 2199 lines, as if they had been entered at the IPython prompt. Since it
2203 2200 exposes IPython's processing machinery, the given strings can contain
2204 2201 magic calls (%magic), special shell access (!cmd), etc.
2205 2202 """
2206 2203
2207 2204 if isinstance(lines, (list, tuple)):
2208 2205 lines = '\n'.join(lines)
2209 2206
2210 2207 if clean:
2211 2208 lines = self._cleanup_ipy_script(lines)
2212 2209
2213 2210 # We must start with a clean buffer, in case this is run from an
2214 2211 # interactive IPython session (via a magic, for example).
2215 2212 self.reset_buffer()
2216 2213 lines = lines.splitlines()
2217 2214
2218 2215 # Since we will prefilter all lines, store the user's raw input too
2219 2216 # before we apply any transformations
2220 2217 self.buffer_raw[:] = [ l+'\n' for l in lines]
2221 2218
2222 2219 more = False
2223 2220 prefilter_lines = self.prefilter_manager.prefilter_lines
2224 2221 with nested(self.builtin_trap, self.display_trap):
2225 2222 for line in lines:
2226 2223 # skip blank lines so we don't mess up the prompt counter, but
2227 2224 # do NOT skip even a blank line if we are in a code block (more
2228 2225 # is true)
2229 2226
2230 2227 if line or more:
2231 2228 more = self.push_line(prefilter_lines(line, more))
2232 2229 # IPython's run_source returns None if there was an error
2233 2230 # compiling the code. This allows us to stop processing
2234 2231 # right away, so the user gets the error message at the
2235 2232 # right place.
2236 2233 if more is None:
2237 2234 break
2238 2235 # final newline in case the input didn't have it, so that the code
2239 2236 # actually does get executed
2240 2237 if more:
2241 2238 self.push_line('\n')
2242 2239
2243 2240 def run_source(self, source, filename=None,
2244 2241 symbol='single', post_execute=True):
2245 2242 """Compile and run some source in the interpreter.
2246 2243
2247 2244 Arguments are as for compile_command().
2248 2245
2249 2246 One several things can happen:
2250 2247
2251 2248 1) The input is incorrect; compile_command() raised an
2252 2249 exception (SyntaxError or OverflowError). A syntax traceback
2253 2250 will be printed by calling the showsyntaxerror() method.
2254 2251
2255 2252 2) The input is incomplete, and more input is required;
2256 2253 compile_command() returned None. Nothing happens.
2257 2254
2258 2255 3) The input is complete; compile_command() returned a code
2259 2256 object. The code is executed by calling self.run_code() (which
2260 2257 also handles run-time exceptions, except for SystemExit).
2261 2258
2262 2259 The return value is:
2263 2260
2264 2261 - True in case 2
2265 2262
2266 2263 - False in the other cases, unless an exception is raised, where
2267 2264 None is returned instead. This can be used by external callers to
2268 2265 know whether to continue feeding input or not.
2269 2266
2270 2267 The return value can be used to decide whether to use sys.ps1 or
2271 2268 sys.ps2 to prompt the next line."""
2272 2269
2273 2270 # We need to ensure that the source is unicode from here on.
2274 2271 if type(source)==str:
2275 2272 usource = source.decode(self.stdin_encoding)
2276 2273 else:
2277 2274 usource = source
2278 2275
2279 2276 if 0: # dbg
2280 2277 print 'Source:', repr(source) # dbg
2281 2278 print 'USource:', repr(usource) # dbg
2282 2279 print 'type:', type(source) # dbg
2283 2280 print 'encoding', self.stdin_encoding # dbg
2284 2281
2285 2282 try:
2286 2283 code = self.compile(usource, symbol, self.execution_count)
2287 2284 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2288 2285 # Case 1
2289 2286 self.showsyntaxerror(filename)
2290 2287 return None
2291 2288
2292 2289 if code is None:
2293 2290 # Case 2
2294 2291 return True
2295 2292
2296 2293 # Case 3
2297 2294 # We store the code object so that threaded shells and
2298 2295 # custom exception handlers can access all this info if needed.
2299 2296 # The source corresponding to this can be obtained from the
2300 2297 # buffer attribute as '\n'.join(self.buffer).
2301 2298 self.code_to_run = code
2302 2299 # now actually execute the code object
2303 2300 if self.run_code(code, post_execute) == 0:
2304 2301 return False
2305 2302 else:
2306 2303 return None
2307 2304
2308 2305 # For backwards compatibility
2309 2306 runsource = run_source
2310 2307
2311 2308 def run_code(self, code_obj, post_execute=True):
2312 2309 """Execute a code object.
2313 2310
2314 2311 When an exception occurs, self.showtraceback() is called to display a
2315 2312 traceback.
2316 2313
2317 2314 Return value: a flag indicating whether the code to be run completed
2318 2315 successfully:
2319 2316
2320 2317 - 0: successful execution.
2321 2318 - 1: an error occurred.
2322 2319 """
2323 2320
2324 2321 # Set our own excepthook in case the user code tries to call it
2325 2322 # directly, so that the IPython crash handler doesn't get triggered
2326 2323 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2327 2324
2328 2325 # we save the original sys.excepthook in the instance, in case config
2329 2326 # code (such as magics) needs access to it.
2330 2327 self.sys_excepthook = old_excepthook
2331 2328 outflag = 1 # happens in more places, so it's easier as default
2332 2329 try:
2333 2330 try:
2334 2331 self.hooks.pre_run_code_hook()
2335 2332 #rprint('Running code', repr(code_obj)) # dbg
2336 2333 exec code_obj in self.user_global_ns, self.user_ns
2337 2334 finally:
2338 2335 # Reset our crash handler in place
2339 2336 sys.excepthook = old_excepthook
2340 2337 except SystemExit:
2341 2338 self.reset_buffer()
2342 2339 self.showtraceback(exception_only=True)
2343 2340 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2344 2341 except self.custom_exceptions:
2345 2342 etype,value,tb = sys.exc_info()
2346 2343 self.CustomTB(etype,value,tb)
2347 2344 except:
2348 2345 self.showtraceback()
2349 2346 else:
2350 2347 outflag = 0
2351 2348 if softspace(sys.stdout, 0):
2352 2349 print
2353 2350
2354 2351 # Execute any registered post-execution functions. Here, any errors
2355 2352 # are reported only minimally and just on the terminal, because the
2356 2353 # main exception channel may be occupied with a user traceback.
2357 2354 # FIXME: we need to think this mechanism a little more carefully.
2358 2355 if post_execute:
2359 2356 for func in self._post_execute:
2360 2357 try:
2361 2358 func()
2362 2359 except:
2363 2360 head = '[ ERROR ] Evaluating post_execute function: %s' % \
2364 2361 func
2365 2362 print >> io.Term.cout, head
2366 2363 print >> io.Term.cout, self._simple_error()
2367 2364 print >> io.Term.cout, 'Removing from post_execute'
2368 2365 self._post_execute.remove(func)
2369 2366
2370 2367 # Flush out code object which has been run (and source)
2371 2368 self.code_to_run = None
2372 2369 return outflag
2373 2370
2374 2371 # For backwards compatibility
2375 2372 runcode = run_code
2376 2373
2377 2374 # PENDING REMOVAL: this method is slated for deletion, once our new
2378 2375 # input logic has been 100% moved to frontends and is stable.
2379 2376 def push_line(self, line):
2380 2377 """Push a line to the interpreter.
2381 2378
2382 2379 The line should not have a trailing newline; it may have
2383 2380 internal newlines. The line is appended to a buffer and the
2384 2381 interpreter's run_source() method is called with the
2385 2382 concatenated contents of the buffer as source. If this
2386 2383 indicates that the command was executed or invalid, the buffer
2387 2384 is reset; otherwise, the command is incomplete, and the buffer
2388 2385 is left as it was after the line was appended. The return
2389 2386 value is 1 if more input is required, 0 if the line was dealt
2390 2387 with in some way (this is the same as run_source()).
2391 2388 """
2392 2389
2393 2390 # autoindent management should be done here, and not in the
2394 2391 # interactive loop, since that one is only seen by keyboard input. We
2395 2392 # need this done correctly even for code run via runlines (which uses
2396 2393 # push).
2397 2394
2398 2395 #print 'push line: <%s>' % line # dbg
2399 2396 self.buffer.append(line)
2400 2397 full_source = '\n'.join(self.buffer)
2401 2398 more = self.run_source(full_source, self.filename)
2402 2399 if not more:
2403 2400 self.history_manager.store_inputs('\n'.join(self.buffer_raw),
2404 2401 full_source)
2405 2402 self.reset_buffer()
2406 2403 self.execution_count += 1
2407 2404 return more
2408 2405
2409 2406 def reset_buffer(self):
2410 2407 """Reset the input buffer."""
2411 2408 self.buffer[:] = []
2412 2409 self.buffer_raw[:] = []
2413 2410 self.input_splitter.reset()
2414 2411
2415 2412 # For backwards compatibility
2416 2413 resetbuffer = reset_buffer
2417 2414
2418 2415 def _is_secondary_block_start(self, s):
2419 2416 if not s.endswith(':'):
2420 2417 return False
2421 2418 if (s.startswith('elif') or
2422 2419 s.startswith('else') or
2423 2420 s.startswith('except') or
2424 2421 s.startswith('finally')):
2425 2422 return True
2426 2423
2427 2424 def _cleanup_ipy_script(self, script):
2428 2425 """Make a script safe for self.runlines()
2429 2426
2430 2427 Currently, IPython is lines based, with blocks being detected by
2431 2428 empty lines. This is a problem for block based scripts that may
2432 2429 not have empty lines after blocks. This script adds those empty
2433 2430 lines to make scripts safe for running in the current line based
2434 2431 IPython.
2435 2432 """
2436 2433 res = []
2437 2434 lines = script.splitlines()
2438 2435 level = 0
2439 2436
2440 2437 for l in lines:
2441 2438 lstripped = l.lstrip()
2442 2439 stripped = l.strip()
2443 2440 if not stripped:
2444 2441 continue
2445 2442 newlevel = len(l) - len(lstripped)
2446 2443 if level > 0 and newlevel == 0 and \
2447 2444 not self._is_secondary_block_start(stripped):
2448 2445 # add empty line
2449 2446 res.append('')
2450 2447 res.append(l)
2451 2448 level = newlevel
2452 2449
2453 2450 return '\n'.join(res) + '\n'
2454 2451
2455 2452 #-------------------------------------------------------------------------
2456 2453 # Things related to GUI support and pylab
2457 2454 #-------------------------------------------------------------------------
2458 2455
2459 2456 def enable_pylab(self, gui=None):
2460 2457 raise NotImplementedError('Implement enable_pylab in a subclass')
2461 2458
2462 2459 #-------------------------------------------------------------------------
2463 2460 # Utilities
2464 2461 #-------------------------------------------------------------------------
2465 2462
2466 2463 def var_expand(self,cmd,depth=0):
2467 2464 """Expand python variables in a string.
2468 2465
2469 2466 The depth argument indicates how many frames above the caller should
2470 2467 be walked to look for the local namespace where to expand variables.
2471 2468
2472 2469 The global namespace for expansion is always the user's interactive
2473 2470 namespace.
2474 2471 """
2475 2472
2476 2473 return str(ItplNS(cmd,
2477 2474 self.user_ns, # globals
2478 2475 # Skip our own frame in searching for locals:
2479 2476 sys._getframe(depth+1).f_locals # locals
2480 2477 ))
2481 2478
2482 2479 def mktempfile(self, data=None, prefix='ipython_edit_'):
2483 2480 """Make a new tempfile and return its filename.
2484 2481
2485 2482 This makes a call to tempfile.mktemp, but it registers the created
2486 2483 filename internally so ipython cleans it up at exit time.
2487 2484
2488 2485 Optional inputs:
2489 2486
2490 2487 - data(None): if data is given, it gets written out to the temp file
2491 2488 immediately, and the file is closed again."""
2492 2489
2493 2490 filename = tempfile.mktemp('.py', prefix)
2494 2491 self.tempfiles.append(filename)
2495 2492
2496 2493 if data:
2497 2494 tmp_file = open(filename,'w')
2498 2495 tmp_file.write(data)
2499 2496 tmp_file.close()
2500 2497 return filename
2501 2498
2502 2499 # TODO: This should be removed when Term is refactored.
2503 2500 def write(self,data):
2504 2501 """Write a string to the default output"""
2505 2502 io.Term.cout.write(data)
2506 2503
2507 2504 # TODO: This should be removed when Term is refactored.
2508 2505 def write_err(self,data):
2509 2506 """Write a string to the default error output"""
2510 2507 io.Term.cerr.write(data)
2511 2508
2512 2509 def ask_yes_no(self,prompt,default=True):
2513 2510 if self.quiet:
2514 2511 return True
2515 2512 return ask_yes_no(prompt,default)
2516 2513
2517 2514 def show_usage(self):
2518 2515 """Show a usage message"""
2519 2516 page.page(IPython.core.usage.interactive_usage)
2520 2517
2521 2518 #-------------------------------------------------------------------------
2522 2519 # Things related to IPython exiting
2523 2520 #-------------------------------------------------------------------------
2524 2521 def atexit_operations(self):
2525 2522 """This will be executed at the time of exit.
2526 2523
2527 2524 Cleanup operations and saving of persistent data that is done
2528 2525 unconditionally by IPython should be performed here.
2529 2526
2530 2527 For things that may depend on startup flags or platform specifics (such
2531 2528 as having readline or not), register a separate atexit function in the
2532 2529 code that has the appropriate information, rather than trying to
2533 2530 clutter
2534 2531 """
2535 2532 # Cleanup all tempfiles left around
2536 2533 for tfile in self.tempfiles:
2537 2534 try:
2538 2535 os.unlink(tfile)
2539 2536 except OSError:
2540 2537 pass
2541 2538
2542 2539 self.save_history()
2543 2540
2544 2541 # Clear all user namespaces to release all references cleanly.
2545 2542 self.reset()
2546 2543
2547 2544 # Run user hooks
2548 2545 self.hooks.shutdown_hook()
2549 2546
2550 2547 def cleanup(self):
2551 2548 self.restore_sys_module_state()
2552 2549
2553 2550
2554 2551 class InteractiveShellABC(object):
2555 2552 """An abstract base class for InteractiveShell."""
2556 2553 __metaclass__ = abc.ABCMeta
2557 2554
2558 2555 InteractiveShellABC.register(InteractiveShell)
@@ -1,39 +1,39 b''
1 1 """Support for interactive macros in IPython"""
2 2
3 3 #*****************************************************************************
4 4 # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu>
5 5 #
6 6 # Distributed under the terms of the BSD License. The full license is in
7 7 # the file COPYING, distributed as part of this software.
8 8 #*****************************************************************************
9 9
10 10 import IPython.utils.io
11 11 from IPython.core.autocall import IPyAutocall
12 12
13 13 class Macro(IPyAutocall):
14 14 """Simple class to store the value of macros as strings.
15 15
16 16 Macro is just a callable that executes a string of IPython
17 17 input when called.
18 18
19 19 Args to macro are available in _margv list if you need them.
20 20 """
21 21
22 def __init__(self,data):
22 def __init__(self,code):
23 23 """store the macro value, as a single string which can be executed"""
24 self.value = '\n'.join(data).rstrip()+'\n'
24 self.value = code.rstrip()+'\n'
25 25
26 26 def __str__(self):
27 27 return self.value
28 28
29 29 def __repr__(self):
30 30 return 'IPython.macro.Macro(%s)' % repr(self.value)
31 31
32 32 def __call__(self,*args):
33 33 IPython.utils.io.Term.cout.flush()
34 34 self._ip.user_ns['_margv'] = args
35 35 self._ip.run_cell(self.value)
36 36
37 37 def __getstate__(self):
38 38 """ needed for safe pickling via %store """
39 39 return {'value': self.value}
@@ -1,3509 +1,3506 b''
1 1 # encoding: utf-8
2 2 """Magic functions for InteractiveShell.
3 3 """
4 4
5 5 #-----------------------------------------------------------------------------
6 6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 7 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
8 8 # Copyright (C) 2008-2009 The IPython Development Team
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 # Imports
16 16 #-----------------------------------------------------------------------------
17 17
18 18 import __builtin__
19 19 import __future__
20 20 import bdb
21 21 import inspect
22 22 import os
23 23 import sys
24 24 import shutil
25 25 import re
26 26 import time
27 27 import textwrap
28 28 import types
29 29 from cStringIO import StringIO
30 30 from getopt import getopt,GetoptError
31 31 from pprint import pformat
32 32
33 33 # cProfile was added in Python2.5
34 34 try:
35 35 import cProfile as profile
36 36 import pstats
37 37 except ImportError:
38 38 # profile isn't bundled by default in Debian for license reasons
39 39 try:
40 40 import profile,pstats
41 41 except ImportError:
42 42 profile = pstats = None
43 43
44 44 import IPython
45 45 from IPython.core import debugger, oinspect
46 46 from IPython.core.error import TryNext
47 47 from IPython.core.error import UsageError
48 48 from IPython.core.fakemodule import FakeModule
49 49 from IPython.core.macro import Macro
50 50 from IPython.core import page
51 51 from IPython.core.prefilter import ESC_MAGIC
52 52 from IPython.lib.pylabtools import mpl_runner
53 53 from IPython.external.Itpl import itpl, printpl
54 54 from IPython.testing import decorators as testdec
55 55 from IPython.utils.io import file_read, nlprint
56 56 import IPython.utils.io
57 57 from IPython.utils.path import get_py_filename
58 58 from IPython.utils.process import arg_split, abbrev_cwd
59 59 from IPython.utils.terminal import set_term_title
60 60 from IPython.utils.text import LSString, SList, StringTypes, format_screen
61 61 from IPython.utils.timing import clock, clock2
62 62 from IPython.utils.warn import warn, error
63 63 from IPython.utils.ipstruct import Struct
64 64 import IPython.utils.generics
65 65
66 66 #-----------------------------------------------------------------------------
67 67 # Utility functions
68 68 #-----------------------------------------------------------------------------
69 69
70 70 def on_off(tag):
71 71 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
72 72 return ['OFF','ON'][tag]
73 73
74 74 class Bunch: pass
75 75
76 76 def compress_dhist(dh):
77 77 head, tail = dh[:-10], dh[-10:]
78 78
79 79 newhead = []
80 80 done = set()
81 81 for h in head:
82 82 if h in done:
83 83 continue
84 84 newhead.append(h)
85 85 done.add(h)
86 86
87 87 return newhead + tail
88 88
89 89
90 90 #***************************************************************************
91 91 # Main class implementing Magic functionality
92 92
93 93 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
94 94 # on construction of the main InteractiveShell object. Something odd is going
95 95 # on with super() calls, Configurable and the MRO... For now leave it as-is, but
96 96 # eventually this needs to be clarified.
97 97 # BG: This is because InteractiveShell inherits from this, but is itself a
98 98 # Configurable. This messes up the MRO in some way. The fix is that we need to
99 99 # make Magic a configurable that InteractiveShell does not subclass.
100 100
101 101 class Magic:
102 102 """Magic functions for InteractiveShell.
103 103
104 104 Shell functions which can be reached as %function_name. All magic
105 105 functions should accept a string, which they can parse for their own
106 106 needs. This can make some functions easier to type, eg `%cd ../`
107 107 vs. `%cd("../")`
108 108
109 109 ALL definitions MUST begin with the prefix magic_. The user won't need it
110 110 at the command line, but it is is needed in the definition. """
111 111
112 112 # class globals
113 113 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
114 114 'Automagic is ON, % prefix NOT needed for magic functions.']
115 115
116 116 #......................................................................
117 117 # some utility functions
118 118
119 119 def __init__(self,shell):
120 120
121 121 self.options_table = {}
122 122 if profile is None:
123 123 self.magic_prun = self.profile_missing_notice
124 124 self.shell = shell
125 125
126 126 # namespace for holding state we may need
127 127 self._magic_state = Bunch()
128 128
129 129 def profile_missing_notice(self, *args, **kwargs):
130 130 error("""\
131 131 The profile module could not be found. It has been removed from the standard
132 132 python packages because of its non-free license. To use profiling, install the
133 133 python-profiler package from non-free.""")
134 134
135 135 def default_option(self,fn,optstr):
136 136 """Make an entry in the options_table for fn, with value optstr"""
137 137
138 138 if fn not in self.lsmagic():
139 139 error("%s is not a magic function" % fn)
140 140 self.options_table[fn] = optstr
141 141
142 142 def lsmagic(self):
143 143 """Return a list of currently available magic functions.
144 144
145 145 Gives a list of the bare names after mangling (['ls','cd', ...], not
146 146 ['magic_ls','magic_cd',...]"""
147 147
148 148 # FIXME. This needs a cleanup, in the way the magics list is built.
149 149
150 150 # magics in class definition
151 151 class_magic = lambda fn: fn.startswith('magic_') and \
152 152 callable(Magic.__dict__[fn])
153 153 # in instance namespace (run-time user additions)
154 154 inst_magic = lambda fn: fn.startswith('magic_') and \
155 155 callable(self.__dict__[fn])
156 156 # and bound magics by user (so they can access self):
157 157 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
158 158 callable(self.__class__.__dict__[fn])
159 159 magics = filter(class_magic,Magic.__dict__.keys()) + \
160 160 filter(inst_magic,self.__dict__.keys()) + \
161 161 filter(inst_bound_magic,self.__class__.__dict__.keys())
162 162 out = []
163 163 for fn in set(magics):
164 164 out.append(fn.replace('magic_','',1))
165 165 out.sort()
166 166 return out
167 167
168 168 def extract_input_slices(self,slices,raw=False):
169 169 """Return as a string a set of input history slices.
170 170
171 171 Inputs:
172 172
173 173 - slices: the set of slices is given as a list of strings (like
174 174 ['1','4:8','9'], since this function is for use by magic functions
175 175 which get their arguments as strings.
176 176
177 177 Optional inputs:
178 178
179 179 - raw(False): by default, the processed input is used. If this is
180 180 true, the raw input history is used instead.
181 181
182 182 Note that slices can be called with two notations:
183 183
184 184 N:M -> standard python form, means including items N...(M-1).
185 185
186 186 N-M -> include items N..M (closed endpoint)."""
187
188 if raw:
189 hist = self.shell.history_manager.input_hist_raw
190 else:
191 hist = self.shell.history_manager.input_hist_parsed
187 history_manager = self.shell.history_manager
192 188
193 189 cmds = []
194 190 for chunk in slices:
195 191 if ':' in chunk:
196 192 ini,fin = map(int,chunk.split(':'))
197 193 elif '-' in chunk:
198 194 ini,fin = map(int,chunk.split('-'))
199 195 fin += 1
200 196 else:
201 197 ini = int(chunk)
202 198 fin = ini+1
203 cmds.append('\n'.join(hist[ini:fin]))
199 hist = history_manager.get_history((ini,fin), raw=raw, output=False)
200 cmds.append('\n'.join(hist[i] for i in sorted(hist.iterkeys())))
204 201 return cmds
205 202
206 203 def arg_err(self,func):
207 204 """Print docstring if incorrect arguments were passed"""
208 205 print 'Error in arguments:'
209 206 print oinspect.getdoc(func)
210 207
211 208 def format_latex(self,strng):
212 209 """Format a string for latex inclusion."""
213 210
214 211 # Characters that need to be escaped for latex:
215 212 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
216 213 # Magic command names as headers:
217 214 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
218 215 re.MULTILINE)
219 216 # Magic commands
220 217 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
221 218 re.MULTILINE)
222 219 # Paragraph continue
223 220 par_re = re.compile(r'\\$',re.MULTILINE)
224 221
225 222 # The "\n" symbol
226 223 newline_re = re.compile(r'\\n')
227 224
228 225 # Now build the string for output:
229 226 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
230 227 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
231 228 strng)
232 229 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
233 230 strng = par_re.sub(r'\\\\',strng)
234 231 strng = escape_re.sub(r'\\\1',strng)
235 232 strng = newline_re.sub(r'\\textbackslash{}n',strng)
236 233 return strng
237 234
238 235 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
239 236 """Parse options passed to an argument string.
240 237
241 238 The interface is similar to that of getopt(), but it returns back a
242 239 Struct with the options as keys and the stripped argument string still
243 240 as a string.
244 241
245 242 arg_str is quoted as a true sys.argv vector by using shlex.split.
246 243 This allows us to easily expand variables, glob files, quote
247 244 arguments, etc.
248 245
249 246 Options:
250 247 -mode: default 'string'. If given as 'list', the argument string is
251 248 returned as a list (split on whitespace) instead of a string.
252 249
253 250 -list_all: put all option values in lists. Normally only options
254 251 appearing more than once are put in a list.
255 252
256 253 -posix (True): whether to split the input line in POSIX mode or not,
257 254 as per the conventions outlined in the shlex module from the
258 255 standard library."""
259 256
260 257 # inject default options at the beginning of the input line
261 258 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
262 259 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
263 260
264 261 mode = kw.get('mode','string')
265 262 if mode not in ['string','list']:
266 263 raise ValueError,'incorrect mode given: %s' % mode
267 264 # Get options
268 265 list_all = kw.get('list_all',0)
269 266 posix = kw.get('posix', os.name == 'posix')
270 267
271 268 # Check if we have more than one argument to warrant extra processing:
272 269 odict = {} # Dictionary with options
273 270 args = arg_str.split()
274 271 if len(args) >= 1:
275 272 # If the list of inputs only has 0 or 1 thing in it, there's no
276 273 # need to look for options
277 274 argv = arg_split(arg_str,posix)
278 275 # Do regular option processing
279 276 try:
280 277 opts,args = getopt(argv,opt_str,*long_opts)
281 278 except GetoptError,e:
282 279 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
283 280 " ".join(long_opts)))
284 281 for o,a in opts:
285 282 if o.startswith('--'):
286 283 o = o[2:]
287 284 else:
288 285 o = o[1:]
289 286 try:
290 287 odict[o].append(a)
291 288 except AttributeError:
292 289 odict[o] = [odict[o],a]
293 290 except KeyError:
294 291 if list_all:
295 292 odict[o] = [a]
296 293 else:
297 294 odict[o] = a
298 295
299 296 # Prepare opts,args for return
300 297 opts = Struct(odict)
301 298 if mode == 'string':
302 299 args = ' '.join(args)
303 300
304 301 return opts,args
305 302
306 303 #......................................................................
307 304 # And now the actual magic functions
308 305
309 306 # Functions for IPython shell work (vars,funcs, config, etc)
310 307 def magic_lsmagic(self, parameter_s = ''):
311 308 """List currently available magic functions."""
312 309 mesc = ESC_MAGIC
313 310 print 'Available magic functions:\n'+mesc+\
314 311 (' '+mesc).join(self.lsmagic())
315 312 print '\n' + Magic.auto_status[self.shell.automagic]
316 313 return None
317 314
318 315 def magic_magic(self, parameter_s = ''):
319 316 """Print information about the magic function system.
320 317
321 318 Supported formats: -latex, -brief, -rest
322 319 """
323 320
324 321 mode = ''
325 322 try:
326 323 if parameter_s.split()[0] == '-latex':
327 324 mode = 'latex'
328 325 if parameter_s.split()[0] == '-brief':
329 326 mode = 'brief'
330 327 if parameter_s.split()[0] == '-rest':
331 328 mode = 'rest'
332 329 rest_docs = []
333 330 except:
334 331 pass
335 332
336 333 magic_docs = []
337 334 for fname in self.lsmagic():
338 335 mname = 'magic_' + fname
339 336 for space in (Magic,self,self.__class__):
340 337 try:
341 338 fn = space.__dict__[mname]
342 339 except KeyError:
343 340 pass
344 341 else:
345 342 break
346 343 if mode == 'brief':
347 344 # only first line
348 345 if fn.__doc__:
349 346 fndoc = fn.__doc__.split('\n',1)[0]
350 347 else:
351 348 fndoc = 'No documentation'
352 349 else:
353 350 if fn.__doc__:
354 351 fndoc = fn.__doc__.rstrip()
355 352 else:
356 353 fndoc = 'No documentation'
357 354
358 355
359 356 if mode == 'rest':
360 357 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
361 358 fname,fndoc))
362 359
363 360 else:
364 361 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
365 362 fname,fndoc))
366 363
367 364 magic_docs = ''.join(magic_docs)
368 365
369 366 if mode == 'rest':
370 367 return "".join(rest_docs)
371 368
372 369 if mode == 'latex':
373 370 print self.format_latex(magic_docs)
374 371 return
375 372 else:
376 373 magic_docs = format_screen(magic_docs)
377 374 if mode == 'brief':
378 375 return magic_docs
379 376
380 377 outmsg = """
381 378 IPython's 'magic' functions
382 379 ===========================
383 380
384 381 The magic function system provides a series of functions which allow you to
385 382 control the behavior of IPython itself, plus a lot of system-type
386 383 features. All these functions are prefixed with a % character, but parameters
387 384 are given without parentheses or quotes.
388 385
389 386 NOTE: If you have 'automagic' enabled (via the command line option or with the
390 387 %automagic function), you don't need to type in the % explicitly. By default,
391 388 IPython ships with automagic on, so you should only rarely need the % escape.
392 389
393 390 Example: typing '%cd mydir' (without the quotes) changes you working directory
394 391 to 'mydir', if it exists.
395 392
396 393 You can define your own magic functions to extend the system. See the supplied
397 394 ipythonrc and example-magic.py files for details (in your ipython
398 395 configuration directory, typically $HOME/.config/ipython on Linux or $HOME/.ipython elsewhere).
399 396
400 397 You can also define your own aliased names for magic functions. In your
401 398 ipythonrc file, placing a line like:
402 399
403 400 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
404 401
405 402 will define %pf as a new name for %profile.
406 403
407 404 You can also call magics in code using the magic() function, which IPython
408 405 automatically adds to the builtin namespace. Type 'magic?' for details.
409 406
410 407 For a list of the available magic functions, use %lsmagic. For a description
411 408 of any of them, type %magic_name?, e.g. '%cd?'.
412 409
413 410 Currently the magic system has the following functions:\n"""
414 411
415 412 mesc = ESC_MAGIC
416 413 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
417 414 "\n\n%s%s\n\n%s" % (outmsg,
418 415 magic_docs,mesc,mesc,
419 416 (' '+mesc).join(self.lsmagic()),
420 417 Magic.auto_status[self.shell.automagic] ) )
421 418 page.page(outmsg)
422 419
423 420 def magic_automagic(self, parameter_s = ''):
424 421 """Make magic functions callable without having to type the initial %.
425 422
426 423 Without argumentsl toggles on/off (when off, you must call it as
427 424 %automagic, of course). With arguments it sets the value, and you can
428 425 use any of (case insensitive):
429 426
430 427 - on,1,True: to activate
431 428
432 429 - off,0,False: to deactivate.
433 430
434 431 Note that magic functions have lowest priority, so if there's a
435 432 variable whose name collides with that of a magic fn, automagic won't
436 433 work for that function (you get the variable instead). However, if you
437 434 delete the variable (del var), the previously shadowed magic function
438 435 becomes visible to automagic again."""
439 436
440 437 arg = parameter_s.lower()
441 438 if parameter_s in ('on','1','true'):
442 439 self.shell.automagic = True
443 440 elif parameter_s in ('off','0','false'):
444 441 self.shell.automagic = False
445 442 else:
446 443 self.shell.automagic = not self.shell.automagic
447 444 print '\n' + Magic.auto_status[self.shell.automagic]
448 445
449 446 @testdec.skip_doctest
450 447 def magic_autocall(self, parameter_s = ''):
451 448 """Make functions callable without having to type parentheses.
452 449
453 450 Usage:
454 451
455 452 %autocall [mode]
456 453
457 454 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
458 455 value is toggled on and off (remembering the previous state).
459 456
460 457 In more detail, these values mean:
461 458
462 459 0 -> fully disabled
463 460
464 461 1 -> active, but do not apply if there are no arguments on the line.
465 462
466 463 In this mode, you get:
467 464
468 465 In [1]: callable
469 466 Out[1]: <built-in function callable>
470 467
471 468 In [2]: callable 'hello'
472 469 ------> callable('hello')
473 470 Out[2]: False
474 471
475 472 2 -> Active always. Even if no arguments are present, the callable
476 473 object is called:
477 474
478 475 In [2]: float
479 476 ------> float()
480 477 Out[2]: 0.0
481 478
482 479 Note that even with autocall off, you can still use '/' at the start of
483 480 a line to treat the first argument on the command line as a function
484 481 and add parentheses to it:
485 482
486 483 In [8]: /str 43
487 484 ------> str(43)
488 485 Out[8]: '43'
489 486
490 487 # all-random (note for auto-testing)
491 488 """
492 489
493 490 if parameter_s:
494 491 arg = int(parameter_s)
495 492 else:
496 493 arg = 'toggle'
497 494
498 495 if not arg in (0,1,2,'toggle'):
499 496 error('Valid modes: (0->Off, 1->Smart, 2->Full')
500 497 return
501 498
502 499 if arg in (0,1,2):
503 500 self.shell.autocall = arg
504 501 else: # toggle
505 502 if self.shell.autocall:
506 503 self._magic_state.autocall_save = self.shell.autocall
507 504 self.shell.autocall = 0
508 505 else:
509 506 try:
510 507 self.shell.autocall = self._magic_state.autocall_save
511 508 except AttributeError:
512 509 self.shell.autocall = self._magic_state.autocall_save = 1
513 510
514 511 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
515 512
516 513
517 514 def magic_page(self, parameter_s=''):
518 515 """Pretty print the object and display it through a pager.
519 516
520 517 %page [options] OBJECT
521 518
522 519 If no object is given, use _ (last output).
523 520
524 521 Options:
525 522
526 523 -r: page str(object), don't pretty-print it."""
527 524
528 525 # After a function contributed by Olivier Aubert, slightly modified.
529 526
530 527 # Process options/args
531 528 opts,args = self.parse_options(parameter_s,'r')
532 529 raw = 'r' in opts
533 530
534 531 oname = args and args or '_'
535 532 info = self._ofind(oname)
536 533 if info['found']:
537 534 txt = (raw and str or pformat)( info['obj'] )
538 535 page.page(txt)
539 536 else:
540 537 print 'Object `%s` not found' % oname
541 538
542 539 def magic_profile(self, parameter_s=''):
543 540 """Print your currently active IPython profile."""
544 541 if self.shell.profile:
545 542 printpl('Current IPython profile: $self.shell.profile.')
546 543 else:
547 544 print 'No profile active.'
548 545
549 546 def magic_pinfo(self, parameter_s='', namespaces=None):
550 547 """Provide detailed information about an object.
551 548
552 549 '%pinfo object' is just a synonym for object? or ?object."""
553 550
554 551 #print 'pinfo par: <%s>' % parameter_s # dbg
555 552
556 553
557 554 # detail_level: 0 -> obj? , 1 -> obj??
558 555 detail_level = 0
559 556 # We need to detect if we got called as 'pinfo pinfo foo', which can
560 557 # happen if the user types 'pinfo foo?' at the cmd line.
561 558 pinfo,qmark1,oname,qmark2 = \
562 559 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
563 560 if pinfo or qmark1 or qmark2:
564 561 detail_level = 1
565 562 if "*" in oname:
566 563 self.magic_psearch(oname)
567 564 else:
568 565 self.shell._inspect('pinfo', oname, detail_level=detail_level,
569 566 namespaces=namespaces)
570 567
571 568 def magic_pinfo2(self, parameter_s='', namespaces=None):
572 569 """Provide extra detailed information about an object.
573 570
574 571 '%pinfo2 object' is just a synonym for object?? or ??object."""
575 572 self.shell._inspect('pinfo', parameter_s, detail_level=1,
576 573 namespaces=namespaces)
577 574
578 575 @testdec.skip_doctest
579 576 def magic_pdef(self, parameter_s='', namespaces=None):
580 577 """Print the definition header for any callable object.
581 578
582 579 If the object is a class, print the constructor information.
583 580
584 581 Examples
585 582 --------
586 583 ::
587 584
588 585 In [3]: %pdef urllib.urlopen
589 586 urllib.urlopen(url, data=None, proxies=None)
590 587 """
591 588 self._inspect('pdef',parameter_s, namespaces)
592 589
593 590 def magic_pdoc(self, parameter_s='', namespaces=None):
594 591 """Print the docstring for an object.
595 592
596 593 If the given object is a class, it will print both the class and the
597 594 constructor docstrings."""
598 595 self._inspect('pdoc',parameter_s, namespaces)
599 596
600 597 def magic_psource(self, parameter_s='', namespaces=None):
601 598 """Print (or run through pager) the source code for an object."""
602 599 self._inspect('psource',parameter_s, namespaces)
603 600
604 601 def magic_pfile(self, parameter_s=''):
605 602 """Print (or run through pager) the file where an object is defined.
606 603
607 604 The file opens at the line where the object definition begins. IPython
608 605 will honor the environment variable PAGER if set, and otherwise will
609 606 do its best to print the file in a convenient form.
610 607
611 608 If the given argument is not an object currently defined, IPython will
612 609 try to interpret it as a filename (automatically adding a .py extension
613 610 if needed). You can thus use %pfile as a syntax highlighting code
614 611 viewer."""
615 612
616 613 # first interpret argument as an object name
617 614 out = self._inspect('pfile',parameter_s)
618 615 # if not, try the input as a filename
619 616 if out == 'not found':
620 617 try:
621 618 filename = get_py_filename(parameter_s)
622 619 except IOError,msg:
623 620 print msg
624 621 return
625 622 page.page(self.shell.inspector.format(file(filename).read()))
626 623
627 624 def magic_psearch(self, parameter_s=''):
628 625 """Search for object in namespaces by wildcard.
629 626
630 627 %psearch [options] PATTERN [OBJECT TYPE]
631 628
632 629 Note: ? can be used as a synonym for %psearch, at the beginning or at
633 630 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
634 631 rest of the command line must be unchanged (options come first), so
635 632 for example the following forms are equivalent
636 633
637 634 %psearch -i a* function
638 635 -i a* function?
639 636 ?-i a* function
640 637
641 638 Arguments:
642 639
643 640 PATTERN
644 641
645 642 where PATTERN is a string containing * as a wildcard similar to its
646 643 use in a shell. The pattern is matched in all namespaces on the
647 644 search path. By default objects starting with a single _ are not
648 645 matched, many IPython generated objects have a single
649 646 underscore. The default is case insensitive matching. Matching is
650 647 also done on the attributes of objects and not only on the objects
651 648 in a module.
652 649
653 650 [OBJECT TYPE]
654 651
655 652 Is the name of a python type from the types module. The name is
656 653 given in lowercase without the ending type, ex. StringType is
657 654 written string. By adding a type here only objects matching the
658 655 given type are matched. Using all here makes the pattern match all
659 656 types (this is the default).
660 657
661 658 Options:
662 659
663 660 -a: makes the pattern match even objects whose names start with a
664 661 single underscore. These names are normally ommitted from the
665 662 search.
666 663
667 664 -i/-c: make the pattern case insensitive/sensitive. If neither of
668 665 these options is given, the default is read from your ipythonrc
669 666 file. The option name which sets this value is
670 667 'wildcards_case_sensitive'. If this option is not specified in your
671 668 ipythonrc file, IPython's internal default is to do a case sensitive
672 669 search.
673 670
674 671 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
675 672 specifiy can be searched in any of the following namespaces:
676 673 'builtin', 'user', 'user_global','internal', 'alias', where
677 674 'builtin' and 'user' are the search defaults. Note that you should
678 675 not use quotes when specifying namespaces.
679 676
680 677 'Builtin' contains the python module builtin, 'user' contains all
681 678 user data, 'alias' only contain the shell aliases and no python
682 679 objects, 'internal' contains objects used by IPython. The
683 680 'user_global' namespace is only used by embedded IPython instances,
684 681 and it contains module-level globals. You can add namespaces to the
685 682 search with -s or exclude them with -e (these options can be given
686 683 more than once).
687 684
688 685 Examples:
689 686
690 687 %psearch a* -> objects beginning with an a
691 688 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
692 689 %psearch a* function -> all functions beginning with an a
693 690 %psearch re.e* -> objects beginning with an e in module re
694 691 %psearch r*.e* -> objects that start with e in modules starting in r
695 692 %psearch r*.* string -> all strings in modules beginning with r
696 693
697 694 Case sensitve search:
698 695
699 696 %psearch -c a* list all object beginning with lower case a
700 697
701 698 Show objects beginning with a single _:
702 699
703 700 %psearch -a _* list objects beginning with a single underscore"""
704 701 try:
705 702 parameter_s = parameter_s.encode('ascii')
706 703 except UnicodeEncodeError:
707 704 print 'Python identifiers can only contain ascii characters.'
708 705 return
709 706
710 707 # default namespaces to be searched
711 708 def_search = ['user','builtin']
712 709
713 710 # Process options/args
714 711 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
715 712 opt = opts.get
716 713 shell = self.shell
717 714 psearch = shell.inspector.psearch
718 715
719 716 # select case options
720 717 if opts.has_key('i'):
721 718 ignore_case = True
722 719 elif opts.has_key('c'):
723 720 ignore_case = False
724 721 else:
725 722 ignore_case = not shell.wildcards_case_sensitive
726 723
727 724 # Build list of namespaces to search from user options
728 725 def_search.extend(opt('s',[]))
729 726 ns_exclude = ns_exclude=opt('e',[])
730 727 ns_search = [nm for nm in def_search if nm not in ns_exclude]
731 728
732 729 # Call the actual search
733 730 try:
734 731 psearch(args,shell.ns_table,ns_search,
735 732 show_all=opt('a'),ignore_case=ignore_case)
736 733 except:
737 734 shell.showtraceback()
738 735
739 736 @testdec.skip_doctest
740 737 def magic_who_ls(self, parameter_s=''):
741 738 """Return a sorted list of all interactive variables.
742 739
743 740 If arguments are given, only variables of types matching these
744 741 arguments are returned.
745 742
746 743 Examples
747 744 --------
748 745
749 746 Define two variables and list them with who_ls::
750 747
751 748 In [1]: alpha = 123
752 749
753 750 In [2]: beta = 'test'
754 751
755 752 In [3]: %who_ls
756 753 Out[3]: ['alpha', 'beta']
757 754
758 755 In [4]: %who_ls int
759 756 Out[4]: ['alpha']
760 757
761 758 In [5]: %who_ls str
762 759 Out[5]: ['beta']
763 760 """
764 761
765 762 user_ns = self.shell.user_ns
766 763 internal_ns = self.shell.internal_ns
767 764 user_ns_hidden = self.shell.user_ns_hidden
768 765 out = [ i for i in user_ns
769 766 if not i.startswith('_') \
770 767 and not (i in internal_ns or i in user_ns_hidden) ]
771 768
772 769 typelist = parameter_s.split()
773 770 if typelist:
774 771 typeset = set(typelist)
775 772 out = [i for i in out if type(user_ns[i]).__name__ in typeset]
776 773
777 774 out.sort()
778 775 return out
779 776
780 777 @testdec.skip_doctest
781 778 def magic_who(self, parameter_s=''):
782 779 """Print all interactive variables, with some minimal formatting.
783 780
784 781 If any arguments are given, only variables whose type matches one of
785 782 these are printed. For example:
786 783
787 784 %who function str
788 785
789 786 will only list functions and strings, excluding all other types of
790 787 variables. To find the proper type names, simply use type(var) at a
791 788 command line to see how python prints type names. For example:
792 789
793 790 In [1]: type('hello')\\
794 791 Out[1]: <type 'str'>
795 792
796 793 indicates that the type name for strings is 'str'.
797 794
798 795 %who always excludes executed names loaded through your configuration
799 796 file and things which are internal to IPython.
800 797
801 798 This is deliberate, as typically you may load many modules and the
802 799 purpose of %who is to show you only what you've manually defined.
803 800
804 801 Examples
805 802 --------
806 803
807 804 Define two variables and list them with who::
808 805
809 806 In [1]: alpha = 123
810 807
811 808 In [2]: beta = 'test'
812 809
813 810 In [3]: %who
814 811 alpha beta
815 812
816 813 In [4]: %who int
817 814 alpha
818 815
819 816 In [5]: %who str
820 817 beta
821 818 """
822 819
823 820 varlist = self.magic_who_ls(parameter_s)
824 821 if not varlist:
825 822 if parameter_s:
826 823 print 'No variables match your requested type.'
827 824 else:
828 825 print 'Interactive namespace is empty.'
829 826 return
830 827
831 828 # if we have variables, move on...
832 829 count = 0
833 830 for i in varlist:
834 831 print i+'\t',
835 832 count += 1
836 833 if count > 8:
837 834 count = 0
838 835 print
839 836 print
840 837
841 838 @testdec.skip_doctest
842 839 def magic_whos(self, parameter_s=''):
843 840 """Like %who, but gives some extra information about each variable.
844 841
845 842 The same type filtering of %who can be applied here.
846 843
847 844 For all variables, the type is printed. Additionally it prints:
848 845
849 846 - For {},[],(): their length.
850 847
851 848 - For numpy and Numeric arrays, a summary with shape, number of
852 849 elements, typecode and size in memory.
853 850
854 851 - Everything else: a string representation, snipping their middle if
855 852 too long.
856 853
857 854 Examples
858 855 --------
859 856
860 857 Define two variables and list them with whos::
861 858
862 859 In [1]: alpha = 123
863 860
864 861 In [2]: beta = 'test'
865 862
866 863 In [3]: %whos
867 864 Variable Type Data/Info
868 865 --------------------------------
869 866 alpha int 123
870 867 beta str test
871 868 """
872 869
873 870 varnames = self.magic_who_ls(parameter_s)
874 871 if not varnames:
875 872 if parameter_s:
876 873 print 'No variables match your requested type.'
877 874 else:
878 875 print 'Interactive namespace is empty.'
879 876 return
880 877
881 878 # if we have variables, move on...
882 879
883 880 # for these types, show len() instead of data:
884 881 seq_types = [types.DictType,types.ListType,types.TupleType]
885 882
886 883 # for numpy/Numeric arrays, display summary info
887 884 try:
888 885 import numpy
889 886 except ImportError:
890 887 ndarray_type = None
891 888 else:
892 889 ndarray_type = numpy.ndarray.__name__
893 890 try:
894 891 import Numeric
895 892 except ImportError:
896 893 array_type = None
897 894 else:
898 895 array_type = Numeric.ArrayType.__name__
899 896
900 897 # Find all variable names and types so we can figure out column sizes
901 898 def get_vars(i):
902 899 return self.shell.user_ns[i]
903 900
904 901 # some types are well known and can be shorter
905 902 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
906 903 def type_name(v):
907 904 tn = type(v).__name__
908 905 return abbrevs.get(tn,tn)
909 906
910 907 varlist = map(get_vars,varnames)
911 908
912 909 typelist = []
913 910 for vv in varlist:
914 911 tt = type_name(vv)
915 912
916 913 if tt=='instance':
917 914 typelist.append( abbrevs.get(str(vv.__class__),
918 915 str(vv.__class__)))
919 916 else:
920 917 typelist.append(tt)
921 918
922 919 # column labels and # of spaces as separator
923 920 varlabel = 'Variable'
924 921 typelabel = 'Type'
925 922 datalabel = 'Data/Info'
926 923 colsep = 3
927 924 # variable format strings
928 925 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
929 926 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
930 927 aformat = "%s: %s elems, type `%s`, %s bytes"
931 928 # find the size of the columns to format the output nicely
932 929 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
933 930 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
934 931 # table header
935 932 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
936 933 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
937 934 # and the table itself
938 935 kb = 1024
939 936 Mb = 1048576 # kb**2
940 937 for vname,var,vtype in zip(varnames,varlist,typelist):
941 938 print itpl(vformat),
942 939 if vtype in seq_types:
943 940 print len(var)
944 941 elif vtype in [array_type,ndarray_type]:
945 942 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
946 943 if vtype==ndarray_type:
947 944 # numpy
948 945 vsize = var.size
949 946 vbytes = vsize*var.itemsize
950 947 vdtype = var.dtype
951 948 else:
952 949 # Numeric
953 950 vsize = Numeric.size(var)
954 951 vbytes = vsize*var.itemsize()
955 952 vdtype = var.typecode()
956 953
957 954 if vbytes < 100000:
958 955 print aformat % (vshape,vsize,vdtype,vbytes)
959 956 else:
960 957 print aformat % (vshape,vsize,vdtype,vbytes),
961 958 if vbytes < Mb:
962 959 print '(%s kb)' % (vbytes/kb,)
963 960 else:
964 961 print '(%s Mb)' % (vbytes/Mb,)
965 962 else:
966 963 try:
967 964 vstr = str(var)
968 965 except UnicodeEncodeError:
969 966 vstr = unicode(var).encode(sys.getdefaultencoding(),
970 967 'backslashreplace')
971 968 vstr = vstr.replace('\n','\\n')
972 969 if len(vstr) < 50:
973 970 print vstr
974 971 else:
975 972 printpl(vfmt_short)
976 973
977 974 def magic_reset(self, parameter_s=''):
978 975 """Resets the namespace by removing all names defined by the user.
979 976
980 977 Input/Output history are left around in case you need them.
981 978
982 979 Parameters
983 980 ----------
984 981 -y : force reset without asking for confirmation.
985 982
986 983 Examples
987 984 --------
988 985 In [6]: a = 1
989 986
990 987 In [7]: a
991 988 Out[7]: 1
992 989
993 990 In [8]: 'a' in _ip.user_ns
994 991 Out[8]: True
995 992
996 993 In [9]: %reset -f
997 994
998 995 In [10]: 'a' in _ip.user_ns
999 996 Out[10]: False
1000 997 """
1001 998
1002 999 if parameter_s == '-f':
1003 1000 ans = True
1004 1001 else:
1005 1002 ans = self.shell.ask_yes_no(
1006 1003 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1007 1004 if not ans:
1008 1005 print 'Nothing done.'
1009 1006 return
1010 1007 user_ns = self.shell.user_ns
1011 1008 for i in self.magic_who_ls():
1012 1009 del(user_ns[i])
1013 1010
1014 1011 # Also flush the private list of module references kept for script
1015 1012 # execution protection
1016 1013 self.shell.clear_main_mod_cache()
1017 1014
1018 1015 def magic_reset_selective(self, parameter_s=''):
1019 1016 """Resets the namespace by removing names defined by the user.
1020 1017
1021 1018 Input/Output history are left around in case you need them.
1022 1019
1023 1020 %reset_selective [-f] regex
1024 1021
1025 1022 No action is taken if regex is not included
1026 1023
1027 1024 Options
1028 1025 -f : force reset without asking for confirmation.
1029 1026
1030 1027 Examples
1031 1028 --------
1032 1029
1033 1030 We first fully reset the namespace so your output looks identical to
1034 1031 this example for pedagogical reasons; in practice you do not need a
1035 1032 full reset.
1036 1033
1037 1034 In [1]: %reset -f
1038 1035
1039 1036 Now, with a clean namespace we can make a few variables and use
1040 1037 %reset_selective to only delete names that match our regexp:
1041 1038
1042 1039 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1043 1040
1044 1041 In [3]: who_ls
1045 1042 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1046 1043
1047 1044 In [4]: %reset_selective -f b[2-3]m
1048 1045
1049 1046 In [5]: who_ls
1050 1047 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1051 1048
1052 1049 In [6]: %reset_selective -f d
1053 1050
1054 1051 In [7]: who_ls
1055 1052 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1056 1053
1057 1054 In [8]: %reset_selective -f c
1058 1055
1059 1056 In [9]: who_ls
1060 1057 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1061 1058
1062 1059 In [10]: %reset_selective -f b
1063 1060
1064 1061 In [11]: who_ls
1065 1062 Out[11]: ['a']
1066 1063 """
1067 1064
1068 1065 opts, regex = self.parse_options(parameter_s,'f')
1069 1066
1070 1067 if opts.has_key('f'):
1071 1068 ans = True
1072 1069 else:
1073 1070 ans = self.shell.ask_yes_no(
1074 1071 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1075 1072 if not ans:
1076 1073 print 'Nothing done.'
1077 1074 return
1078 1075 user_ns = self.shell.user_ns
1079 1076 if not regex:
1080 1077 print 'No regex pattern specified. Nothing done.'
1081 1078 return
1082 1079 else:
1083 1080 try:
1084 1081 m = re.compile(regex)
1085 1082 except TypeError:
1086 1083 raise TypeError('regex must be a string or compiled pattern')
1087 1084 for i in self.magic_who_ls():
1088 1085 if m.search(i):
1089 1086 del(user_ns[i])
1090 1087
1091 1088 def magic_logstart(self,parameter_s=''):
1092 1089 """Start logging anywhere in a session.
1093 1090
1094 1091 %logstart [-o|-r|-t] [log_name [log_mode]]
1095 1092
1096 1093 If no name is given, it defaults to a file named 'ipython_log.py' in your
1097 1094 current directory, in 'rotate' mode (see below).
1098 1095
1099 1096 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1100 1097 history up to that point and then continues logging.
1101 1098
1102 1099 %logstart takes a second optional parameter: logging mode. This can be one
1103 1100 of (note that the modes are given unquoted):\\
1104 1101 append: well, that says it.\\
1105 1102 backup: rename (if exists) to name~ and start name.\\
1106 1103 global: single logfile in your home dir, appended to.\\
1107 1104 over : overwrite existing log.\\
1108 1105 rotate: create rotating logs name.1~, name.2~, etc.
1109 1106
1110 1107 Options:
1111 1108
1112 1109 -o: log also IPython's output. In this mode, all commands which
1113 1110 generate an Out[NN] prompt are recorded to the logfile, right after
1114 1111 their corresponding input line. The output lines are always
1115 1112 prepended with a '#[Out]# ' marker, so that the log remains valid
1116 1113 Python code.
1117 1114
1118 1115 Since this marker is always the same, filtering only the output from
1119 1116 a log is very easy, using for example a simple awk call:
1120 1117
1121 1118 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1122 1119
1123 1120 -r: log 'raw' input. Normally, IPython's logs contain the processed
1124 1121 input, so that user lines are logged in their final form, converted
1125 1122 into valid Python. For example, %Exit is logged as
1126 1123 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1127 1124 exactly as typed, with no transformations applied.
1128 1125
1129 1126 -t: put timestamps before each input line logged (these are put in
1130 1127 comments)."""
1131 1128
1132 1129 opts,par = self.parse_options(parameter_s,'ort')
1133 1130 log_output = 'o' in opts
1134 1131 log_raw_input = 'r' in opts
1135 1132 timestamp = 't' in opts
1136 1133
1137 1134 logger = self.shell.logger
1138 1135
1139 1136 # if no args are given, the defaults set in the logger constructor by
1140 1137 # ipytohn remain valid
1141 1138 if par:
1142 1139 try:
1143 1140 logfname,logmode = par.split()
1144 1141 except:
1145 1142 logfname = par
1146 1143 logmode = 'backup'
1147 1144 else:
1148 1145 logfname = logger.logfname
1149 1146 logmode = logger.logmode
1150 1147 # put logfname into rc struct as if it had been called on the command
1151 1148 # line, so it ends up saved in the log header Save it in case we need
1152 1149 # to restore it...
1153 1150 old_logfile = self.shell.logfile
1154 1151 if logfname:
1155 1152 logfname = os.path.expanduser(logfname)
1156 1153 self.shell.logfile = logfname
1157 1154
1158 1155 loghead = '# IPython log file\n\n'
1159 1156 try:
1160 1157 started = logger.logstart(logfname,loghead,logmode,
1161 1158 log_output,timestamp,log_raw_input)
1162 1159 except:
1163 1160 self.shell.logfile = old_logfile
1164 1161 warn("Couldn't start log: %s" % sys.exc_info()[1])
1165 1162 else:
1166 1163 # log input history up to this point, optionally interleaving
1167 1164 # output if requested
1168 1165
1169 1166 if timestamp:
1170 1167 # disable timestamping for the previous history, since we've
1171 1168 # lost those already (no time machine here).
1172 1169 logger.timestamp = False
1173 1170
1174 1171 if log_raw_input:
1175 1172 input_hist = self.shell.history_manager.input_hist_raw
1176 1173 else:
1177 1174 input_hist = self.shell.history_manager.input_hist_parsed
1178 1175
1179 1176 if log_output:
1180 1177 log_write = logger.log_write
1181 1178 output_hist = self.shell.history_manager.output_hist
1182 1179 for n in range(1,len(input_hist)-1):
1183 1180 log_write(input_hist[n].rstrip())
1184 1181 if n in output_hist:
1185 1182 log_write(repr(output_hist[n]),'output')
1186 1183 else:
1187 1184 logger.log_write(''.join(input_hist[1:]))
1188 1185 if timestamp:
1189 1186 # re-enable timestamping
1190 1187 logger.timestamp = True
1191 1188
1192 1189 print ('Activating auto-logging. '
1193 1190 'Current session state plus future input saved.')
1194 1191 logger.logstate()
1195 1192
1196 1193 def magic_logstop(self,parameter_s=''):
1197 1194 """Fully stop logging and close log file.
1198 1195
1199 1196 In order to start logging again, a new %logstart call needs to be made,
1200 1197 possibly (though not necessarily) with a new filename, mode and other
1201 1198 options."""
1202 1199 self.logger.logstop()
1203 1200
1204 1201 def magic_logoff(self,parameter_s=''):
1205 1202 """Temporarily stop logging.
1206 1203
1207 1204 You must have previously started logging."""
1208 1205 self.shell.logger.switch_log(0)
1209 1206
1210 1207 def magic_logon(self,parameter_s=''):
1211 1208 """Restart logging.
1212 1209
1213 1210 This function is for restarting logging which you've temporarily
1214 1211 stopped with %logoff. For starting logging for the first time, you
1215 1212 must use the %logstart function, which allows you to specify an
1216 1213 optional log filename."""
1217 1214
1218 1215 self.shell.logger.switch_log(1)
1219 1216
1220 1217 def magic_logstate(self,parameter_s=''):
1221 1218 """Print the status of the logging system."""
1222 1219
1223 1220 self.shell.logger.logstate()
1224 1221
1225 1222 def magic_pdb(self, parameter_s=''):
1226 1223 """Control the automatic calling of the pdb interactive debugger.
1227 1224
1228 1225 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1229 1226 argument it works as a toggle.
1230 1227
1231 1228 When an exception is triggered, IPython can optionally call the
1232 1229 interactive pdb debugger after the traceback printout. %pdb toggles
1233 1230 this feature on and off.
1234 1231
1235 1232 The initial state of this feature is set in your ipythonrc
1236 1233 configuration file (the variable is called 'pdb').
1237 1234
1238 1235 If you want to just activate the debugger AFTER an exception has fired,
1239 1236 without having to type '%pdb on' and rerunning your code, you can use
1240 1237 the %debug magic."""
1241 1238
1242 1239 par = parameter_s.strip().lower()
1243 1240
1244 1241 if par:
1245 1242 try:
1246 1243 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1247 1244 except KeyError:
1248 1245 print ('Incorrect argument. Use on/1, off/0, '
1249 1246 'or nothing for a toggle.')
1250 1247 return
1251 1248 else:
1252 1249 # toggle
1253 1250 new_pdb = not self.shell.call_pdb
1254 1251
1255 1252 # set on the shell
1256 1253 self.shell.call_pdb = new_pdb
1257 1254 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1258 1255
1259 1256 def magic_debug(self, parameter_s=''):
1260 1257 """Activate the interactive debugger in post-mortem mode.
1261 1258
1262 1259 If an exception has just occurred, this lets you inspect its stack
1263 1260 frames interactively. Note that this will always work only on the last
1264 1261 traceback that occurred, so you must call this quickly after an
1265 1262 exception that you wish to inspect has fired, because if another one
1266 1263 occurs, it clobbers the previous one.
1267 1264
1268 1265 If you want IPython to automatically do this on every exception, see
1269 1266 the %pdb magic for more details.
1270 1267 """
1271 1268 self.shell.debugger(force=True)
1272 1269
1273 1270 @testdec.skip_doctest
1274 1271 def magic_prun(self, parameter_s ='',user_mode=1,
1275 1272 opts=None,arg_lst=None,prog_ns=None):
1276 1273
1277 1274 """Run a statement through the python code profiler.
1278 1275
1279 1276 Usage:
1280 1277 %prun [options] statement
1281 1278
1282 1279 The given statement (which doesn't require quote marks) is run via the
1283 1280 python profiler in a manner similar to the profile.run() function.
1284 1281 Namespaces are internally managed to work correctly; profile.run
1285 1282 cannot be used in IPython because it makes certain assumptions about
1286 1283 namespaces which do not hold under IPython.
1287 1284
1288 1285 Options:
1289 1286
1290 1287 -l <limit>: you can place restrictions on what or how much of the
1291 1288 profile gets printed. The limit value can be:
1292 1289
1293 1290 * A string: only information for function names containing this string
1294 1291 is printed.
1295 1292
1296 1293 * An integer: only these many lines are printed.
1297 1294
1298 1295 * A float (between 0 and 1): this fraction of the report is printed
1299 1296 (for example, use a limit of 0.4 to see the topmost 40% only).
1300 1297
1301 1298 You can combine several limits with repeated use of the option. For
1302 1299 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1303 1300 information about class constructors.
1304 1301
1305 1302 -r: return the pstats.Stats object generated by the profiling. This
1306 1303 object has all the information about the profile in it, and you can
1307 1304 later use it for further analysis or in other functions.
1308 1305
1309 1306 -s <key>: sort profile by given key. You can provide more than one key
1310 1307 by using the option several times: '-s key1 -s key2 -s key3...'. The
1311 1308 default sorting key is 'time'.
1312 1309
1313 1310 The following is copied verbatim from the profile documentation
1314 1311 referenced below:
1315 1312
1316 1313 When more than one key is provided, additional keys are used as
1317 1314 secondary criteria when the there is equality in all keys selected
1318 1315 before them.
1319 1316
1320 1317 Abbreviations can be used for any key names, as long as the
1321 1318 abbreviation is unambiguous. The following are the keys currently
1322 1319 defined:
1323 1320
1324 1321 Valid Arg Meaning
1325 1322 "calls" call count
1326 1323 "cumulative" cumulative time
1327 1324 "file" file name
1328 1325 "module" file name
1329 1326 "pcalls" primitive call count
1330 1327 "line" line number
1331 1328 "name" function name
1332 1329 "nfl" name/file/line
1333 1330 "stdname" standard name
1334 1331 "time" internal time
1335 1332
1336 1333 Note that all sorts on statistics are in descending order (placing
1337 1334 most time consuming items first), where as name, file, and line number
1338 1335 searches are in ascending order (i.e., alphabetical). The subtle
1339 1336 distinction between "nfl" and "stdname" is that the standard name is a
1340 1337 sort of the name as printed, which means that the embedded line
1341 1338 numbers get compared in an odd way. For example, lines 3, 20, and 40
1342 1339 would (if the file names were the same) appear in the string order
1343 1340 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1344 1341 line numbers. In fact, sort_stats("nfl") is the same as
1345 1342 sort_stats("name", "file", "line").
1346 1343
1347 1344 -T <filename>: save profile results as shown on screen to a text
1348 1345 file. The profile is still shown on screen.
1349 1346
1350 1347 -D <filename>: save (via dump_stats) profile statistics to given
1351 1348 filename. This data is in a format understod by the pstats module, and
1352 1349 is generated by a call to the dump_stats() method of profile
1353 1350 objects. The profile is still shown on screen.
1354 1351
1355 1352 If you want to run complete programs under the profiler's control, use
1356 1353 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1357 1354 contains profiler specific options as described here.
1358 1355
1359 1356 You can read the complete documentation for the profile module with::
1360 1357
1361 1358 In [1]: import profile; profile.help()
1362 1359 """
1363 1360
1364 1361 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1365 1362 # protect user quote marks
1366 1363 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1367 1364
1368 1365 if user_mode: # regular user call
1369 1366 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1370 1367 list_all=1)
1371 1368 namespace = self.shell.user_ns
1372 1369 else: # called to run a program by %run -p
1373 1370 try:
1374 1371 filename = get_py_filename(arg_lst[0])
1375 1372 except IOError,msg:
1376 1373 error(msg)
1377 1374 return
1378 1375
1379 1376 arg_str = 'execfile(filename,prog_ns)'
1380 1377 namespace = locals()
1381 1378
1382 1379 opts.merge(opts_def)
1383 1380
1384 1381 prof = profile.Profile()
1385 1382 try:
1386 1383 prof = prof.runctx(arg_str,namespace,namespace)
1387 1384 sys_exit = ''
1388 1385 except SystemExit:
1389 1386 sys_exit = """*** SystemExit exception caught in code being profiled."""
1390 1387
1391 1388 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1392 1389
1393 1390 lims = opts.l
1394 1391 if lims:
1395 1392 lims = [] # rebuild lims with ints/floats/strings
1396 1393 for lim in opts.l:
1397 1394 try:
1398 1395 lims.append(int(lim))
1399 1396 except ValueError:
1400 1397 try:
1401 1398 lims.append(float(lim))
1402 1399 except ValueError:
1403 1400 lims.append(lim)
1404 1401
1405 1402 # Trap output.
1406 1403 stdout_trap = StringIO()
1407 1404
1408 1405 if hasattr(stats,'stream'):
1409 1406 # In newer versions of python, the stats object has a 'stream'
1410 1407 # attribute to write into.
1411 1408 stats.stream = stdout_trap
1412 1409 stats.print_stats(*lims)
1413 1410 else:
1414 1411 # For older versions, we manually redirect stdout during printing
1415 1412 sys_stdout = sys.stdout
1416 1413 try:
1417 1414 sys.stdout = stdout_trap
1418 1415 stats.print_stats(*lims)
1419 1416 finally:
1420 1417 sys.stdout = sys_stdout
1421 1418
1422 1419 output = stdout_trap.getvalue()
1423 1420 output = output.rstrip()
1424 1421
1425 1422 page.page(output)
1426 1423 print sys_exit,
1427 1424
1428 1425 dump_file = opts.D[0]
1429 1426 text_file = opts.T[0]
1430 1427 if dump_file:
1431 1428 prof.dump_stats(dump_file)
1432 1429 print '\n*** Profile stats marshalled to file',\
1433 1430 `dump_file`+'.',sys_exit
1434 1431 if text_file:
1435 1432 pfile = file(text_file,'w')
1436 1433 pfile.write(output)
1437 1434 pfile.close()
1438 1435 print '\n*** Profile printout saved to text file',\
1439 1436 `text_file`+'.',sys_exit
1440 1437
1441 1438 if opts.has_key('r'):
1442 1439 return stats
1443 1440 else:
1444 1441 return None
1445 1442
1446 1443 @testdec.skip_doctest
1447 1444 def magic_run(self, parameter_s ='',runner=None,
1448 1445 file_finder=get_py_filename):
1449 1446 """Run the named file inside IPython as a program.
1450 1447
1451 1448 Usage:\\
1452 1449 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1453 1450
1454 1451 Parameters after the filename are passed as command-line arguments to
1455 1452 the program (put in sys.argv). Then, control returns to IPython's
1456 1453 prompt.
1457 1454
1458 1455 This is similar to running at a system prompt:\\
1459 1456 $ python file args\\
1460 1457 but with the advantage of giving you IPython's tracebacks, and of
1461 1458 loading all variables into your interactive namespace for further use
1462 1459 (unless -p is used, see below).
1463 1460
1464 1461 The file is executed in a namespace initially consisting only of
1465 1462 __name__=='__main__' and sys.argv constructed as indicated. It thus
1466 1463 sees its environment as if it were being run as a stand-alone program
1467 1464 (except for sharing global objects such as previously imported
1468 1465 modules). But after execution, the IPython interactive namespace gets
1469 1466 updated with all variables defined in the program (except for __name__
1470 1467 and sys.argv). This allows for very convenient loading of code for
1471 1468 interactive work, while giving each program a 'clean sheet' to run in.
1472 1469
1473 1470 Options:
1474 1471
1475 1472 -n: __name__ is NOT set to '__main__', but to the running file's name
1476 1473 without extension (as python does under import). This allows running
1477 1474 scripts and reloading the definitions in them without calling code
1478 1475 protected by an ' if __name__ == "__main__" ' clause.
1479 1476
1480 1477 -i: run the file in IPython's namespace instead of an empty one. This
1481 1478 is useful if you are experimenting with code written in a text editor
1482 1479 which depends on variables defined interactively.
1483 1480
1484 1481 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1485 1482 being run. This is particularly useful if IPython is being used to
1486 1483 run unittests, which always exit with a sys.exit() call. In such
1487 1484 cases you are interested in the output of the test results, not in
1488 1485 seeing a traceback of the unittest module.
1489 1486
1490 1487 -t: print timing information at the end of the run. IPython will give
1491 1488 you an estimated CPU time consumption for your script, which under
1492 1489 Unix uses the resource module to avoid the wraparound problems of
1493 1490 time.clock(). Under Unix, an estimate of time spent on system tasks
1494 1491 is also given (for Windows platforms this is reported as 0.0).
1495 1492
1496 1493 If -t is given, an additional -N<N> option can be given, where <N>
1497 1494 must be an integer indicating how many times you want the script to
1498 1495 run. The final timing report will include total and per run results.
1499 1496
1500 1497 For example (testing the script uniq_stable.py):
1501 1498
1502 1499 In [1]: run -t uniq_stable
1503 1500
1504 1501 IPython CPU timings (estimated):\\
1505 1502 User : 0.19597 s.\\
1506 1503 System: 0.0 s.\\
1507 1504
1508 1505 In [2]: run -t -N5 uniq_stable
1509 1506
1510 1507 IPython CPU timings (estimated):\\
1511 1508 Total runs performed: 5\\
1512 1509 Times : Total Per run\\
1513 1510 User : 0.910862 s, 0.1821724 s.\\
1514 1511 System: 0.0 s, 0.0 s.
1515 1512
1516 1513 -d: run your program under the control of pdb, the Python debugger.
1517 1514 This allows you to execute your program step by step, watch variables,
1518 1515 etc. Internally, what IPython does is similar to calling:
1519 1516
1520 1517 pdb.run('execfile("YOURFILENAME")')
1521 1518
1522 1519 with a breakpoint set on line 1 of your file. You can change the line
1523 1520 number for this automatic breakpoint to be <N> by using the -bN option
1524 1521 (where N must be an integer). For example:
1525 1522
1526 1523 %run -d -b40 myscript
1527 1524
1528 1525 will set the first breakpoint at line 40 in myscript.py. Note that
1529 1526 the first breakpoint must be set on a line which actually does
1530 1527 something (not a comment or docstring) for it to stop execution.
1531 1528
1532 1529 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1533 1530 first enter 'c' (without qoutes) to start execution up to the first
1534 1531 breakpoint.
1535 1532
1536 1533 Entering 'help' gives information about the use of the debugger. You
1537 1534 can easily see pdb's full documentation with "import pdb;pdb.help()"
1538 1535 at a prompt.
1539 1536
1540 1537 -p: run program under the control of the Python profiler module (which
1541 1538 prints a detailed report of execution times, function calls, etc).
1542 1539
1543 1540 You can pass other options after -p which affect the behavior of the
1544 1541 profiler itself. See the docs for %prun for details.
1545 1542
1546 1543 In this mode, the program's variables do NOT propagate back to the
1547 1544 IPython interactive namespace (because they remain in the namespace
1548 1545 where the profiler executes them).
1549 1546
1550 1547 Internally this triggers a call to %prun, see its documentation for
1551 1548 details on the options available specifically for profiling.
1552 1549
1553 1550 There is one special usage for which the text above doesn't apply:
1554 1551 if the filename ends with .ipy, the file is run as ipython script,
1555 1552 just as if the commands were written on IPython prompt.
1556 1553 """
1557 1554
1558 1555 # get arguments and set sys.argv for program to be run.
1559 1556 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1560 1557 mode='list',list_all=1)
1561 1558
1562 1559 try:
1563 1560 filename = file_finder(arg_lst[0])
1564 1561 except IndexError:
1565 1562 warn('you must provide at least a filename.')
1566 1563 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1567 1564 return
1568 1565 except IOError,msg:
1569 1566 error(msg)
1570 1567 return
1571 1568
1572 1569 if filename.lower().endswith('.ipy'):
1573 1570 self.shell.safe_execfile_ipy(filename)
1574 1571 return
1575 1572
1576 1573 # Control the response to exit() calls made by the script being run
1577 1574 exit_ignore = opts.has_key('e')
1578 1575
1579 1576 # Make sure that the running script gets a proper sys.argv as if it
1580 1577 # were run from a system shell.
1581 1578 save_argv = sys.argv # save it for later restoring
1582 1579 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1583 1580
1584 1581 if opts.has_key('i'):
1585 1582 # Run in user's interactive namespace
1586 1583 prog_ns = self.shell.user_ns
1587 1584 __name__save = self.shell.user_ns['__name__']
1588 1585 prog_ns['__name__'] = '__main__'
1589 1586 main_mod = self.shell.new_main_mod(prog_ns)
1590 1587 else:
1591 1588 # Run in a fresh, empty namespace
1592 1589 if opts.has_key('n'):
1593 1590 name = os.path.splitext(os.path.basename(filename))[0]
1594 1591 else:
1595 1592 name = '__main__'
1596 1593
1597 1594 main_mod = self.shell.new_main_mod()
1598 1595 prog_ns = main_mod.__dict__
1599 1596 prog_ns['__name__'] = name
1600 1597
1601 1598 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1602 1599 # set the __file__ global in the script's namespace
1603 1600 prog_ns['__file__'] = filename
1604 1601
1605 1602 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1606 1603 # that, if we overwrite __main__, we replace it at the end
1607 1604 main_mod_name = prog_ns['__name__']
1608 1605
1609 1606 if main_mod_name == '__main__':
1610 1607 restore_main = sys.modules['__main__']
1611 1608 else:
1612 1609 restore_main = False
1613 1610
1614 1611 # This needs to be undone at the end to prevent holding references to
1615 1612 # every single object ever created.
1616 1613 sys.modules[main_mod_name] = main_mod
1617 1614
1618 1615 stats = None
1619 1616 try:
1620 1617 self.shell.save_history()
1621 1618
1622 1619 if opts.has_key('p'):
1623 1620 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1624 1621 else:
1625 1622 if opts.has_key('d'):
1626 1623 deb = debugger.Pdb(self.shell.colors)
1627 1624 # reset Breakpoint state, which is moronically kept
1628 1625 # in a class
1629 1626 bdb.Breakpoint.next = 1
1630 1627 bdb.Breakpoint.bplist = {}
1631 1628 bdb.Breakpoint.bpbynumber = [None]
1632 1629 # Set an initial breakpoint to stop execution
1633 1630 maxtries = 10
1634 1631 bp = int(opts.get('b',[1])[0])
1635 1632 checkline = deb.checkline(filename,bp)
1636 1633 if not checkline:
1637 1634 for bp in range(bp+1,bp+maxtries+1):
1638 1635 if deb.checkline(filename,bp):
1639 1636 break
1640 1637 else:
1641 1638 msg = ("\nI failed to find a valid line to set "
1642 1639 "a breakpoint\n"
1643 1640 "after trying up to line: %s.\n"
1644 1641 "Please set a valid breakpoint manually "
1645 1642 "with the -b option." % bp)
1646 1643 error(msg)
1647 1644 return
1648 1645 # if we find a good linenumber, set the breakpoint
1649 1646 deb.do_break('%s:%s' % (filename,bp))
1650 1647 # Start file run
1651 1648 print "NOTE: Enter 'c' at the",
1652 1649 print "%s prompt to start your script." % deb.prompt
1653 1650 try:
1654 1651 deb.run('execfile("%s")' % filename,prog_ns)
1655 1652
1656 1653 except:
1657 1654 etype, value, tb = sys.exc_info()
1658 1655 # Skip three frames in the traceback: the %run one,
1659 1656 # one inside bdb.py, and the command-line typed by the
1660 1657 # user (run by exec in pdb itself).
1661 1658 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1662 1659 else:
1663 1660 if runner is None:
1664 1661 runner = self.shell.safe_execfile
1665 1662 if opts.has_key('t'):
1666 1663 # timed execution
1667 1664 try:
1668 1665 nruns = int(opts['N'][0])
1669 1666 if nruns < 1:
1670 1667 error('Number of runs must be >=1')
1671 1668 return
1672 1669 except (KeyError):
1673 1670 nruns = 1
1674 1671 if nruns == 1:
1675 1672 t0 = clock2()
1676 1673 runner(filename,prog_ns,prog_ns,
1677 1674 exit_ignore=exit_ignore)
1678 1675 t1 = clock2()
1679 1676 t_usr = t1[0]-t0[0]
1680 1677 t_sys = t1[1]-t0[1]
1681 1678 print "\nIPython CPU timings (estimated):"
1682 1679 print " User : %10s s." % t_usr
1683 1680 print " System: %10s s." % t_sys
1684 1681 else:
1685 1682 runs = range(nruns)
1686 1683 t0 = clock2()
1687 1684 for nr in runs:
1688 1685 runner(filename,prog_ns,prog_ns,
1689 1686 exit_ignore=exit_ignore)
1690 1687 t1 = clock2()
1691 1688 t_usr = t1[0]-t0[0]
1692 1689 t_sys = t1[1]-t0[1]
1693 1690 print "\nIPython CPU timings (estimated):"
1694 1691 print "Total runs performed:",nruns
1695 1692 print " Times : %10s %10s" % ('Total','Per run')
1696 1693 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1697 1694 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1698 1695
1699 1696 else:
1700 1697 # regular execution
1701 1698 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1702 1699
1703 1700 if opts.has_key('i'):
1704 1701 self.shell.user_ns['__name__'] = __name__save
1705 1702 else:
1706 1703 # The shell MUST hold a reference to prog_ns so after %run
1707 1704 # exits, the python deletion mechanism doesn't zero it out
1708 1705 # (leaving dangling references).
1709 1706 self.shell.cache_main_mod(prog_ns,filename)
1710 1707 # update IPython interactive namespace
1711 1708
1712 1709 # Some forms of read errors on the file may mean the
1713 1710 # __name__ key was never set; using pop we don't have to
1714 1711 # worry about a possible KeyError.
1715 1712 prog_ns.pop('__name__', None)
1716 1713
1717 1714 self.shell.user_ns.update(prog_ns)
1718 1715 finally:
1719 1716 # It's a bit of a mystery why, but __builtins__ can change from
1720 1717 # being a module to becoming a dict missing some key data after
1721 1718 # %run. As best I can see, this is NOT something IPython is doing
1722 1719 # at all, and similar problems have been reported before:
1723 1720 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1724 1721 # Since this seems to be done by the interpreter itself, the best
1725 1722 # we can do is to at least restore __builtins__ for the user on
1726 1723 # exit.
1727 1724 self.shell.user_ns['__builtins__'] = __builtin__
1728 1725
1729 1726 # Ensure key global structures are restored
1730 1727 sys.argv = save_argv
1731 1728 if restore_main:
1732 1729 sys.modules['__main__'] = restore_main
1733 1730 else:
1734 1731 # Remove from sys.modules the reference to main_mod we'd
1735 1732 # added. Otherwise it will trap references to objects
1736 1733 # contained therein.
1737 1734 del sys.modules[main_mod_name]
1738 1735
1739 1736 self.shell.reload_history()
1740 1737
1741 1738 return stats
1742 1739
1743 1740 @testdec.skip_doctest
1744 1741 def magic_timeit(self, parameter_s =''):
1745 1742 """Time execution of a Python statement or expression
1746 1743
1747 1744 Usage:\\
1748 1745 %timeit [-n<N> -r<R> [-t|-c]] statement
1749 1746
1750 1747 Time execution of a Python statement or expression using the timeit
1751 1748 module.
1752 1749
1753 1750 Options:
1754 1751 -n<N>: execute the given statement <N> times in a loop. If this value
1755 1752 is not given, a fitting value is chosen.
1756 1753
1757 1754 -r<R>: repeat the loop iteration <R> times and take the best result.
1758 1755 Default: 3
1759 1756
1760 1757 -t: use time.time to measure the time, which is the default on Unix.
1761 1758 This function measures wall time.
1762 1759
1763 1760 -c: use time.clock to measure the time, which is the default on
1764 1761 Windows and measures wall time. On Unix, resource.getrusage is used
1765 1762 instead and returns the CPU user time.
1766 1763
1767 1764 -p<P>: use a precision of <P> digits to display the timing result.
1768 1765 Default: 3
1769 1766
1770 1767
1771 1768 Examples:
1772 1769
1773 1770 In [1]: %timeit pass
1774 1771 10000000 loops, best of 3: 53.3 ns per loop
1775 1772
1776 1773 In [2]: u = None
1777 1774
1778 1775 In [3]: %timeit u is None
1779 1776 10000000 loops, best of 3: 184 ns per loop
1780 1777
1781 1778 In [4]: %timeit -r 4 u == None
1782 1779 1000000 loops, best of 4: 242 ns per loop
1783 1780
1784 1781 In [5]: import time
1785 1782
1786 1783 In [6]: %timeit -n1 time.sleep(2)
1787 1784 1 loops, best of 3: 2 s per loop
1788 1785
1789 1786
1790 1787 The times reported by %timeit will be slightly higher than those
1791 1788 reported by the timeit.py script when variables are accessed. This is
1792 1789 due to the fact that %timeit executes the statement in the namespace
1793 1790 of the shell, compared with timeit.py, which uses a single setup
1794 1791 statement to import function or create variables. Generally, the bias
1795 1792 does not matter as long as results from timeit.py are not mixed with
1796 1793 those from %timeit."""
1797 1794
1798 1795 import timeit
1799 1796 import math
1800 1797
1801 1798 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1802 1799 # certain terminals. Until we figure out a robust way of
1803 1800 # auto-detecting if the terminal can deal with it, use plain 'us' for
1804 1801 # microseconds. I am really NOT happy about disabling the proper
1805 1802 # 'micro' prefix, but crashing is worse... If anyone knows what the
1806 1803 # right solution for this is, I'm all ears...
1807 1804 #
1808 1805 # Note: using
1809 1806 #
1810 1807 # s = u'\xb5'
1811 1808 # s.encode(sys.getdefaultencoding())
1812 1809 #
1813 1810 # is not sufficient, as I've seen terminals where that fails but
1814 1811 # print s
1815 1812 #
1816 1813 # succeeds
1817 1814 #
1818 1815 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1819 1816
1820 1817 #units = [u"s", u"ms",u'\xb5',"ns"]
1821 1818 units = [u"s", u"ms",u'us',"ns"]
1822 1819
1823 1820 scaling = [1, 1e3, 1e6, 1e9]
1824 1821
1825 1822 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1826 1823 posix=False)
1827 1824 if stmt == "":
1828 1825 return
1829 1826 timefunc = timeit.default_timer
1830 1827 number = int(getattr(opts, "n", 0))
1831 1828 repeat = int(getattr(opts, "r", timeit.default_repeat))
1832 1829 precision = int(getattr(opts, "p", 3))
1833 1830 if hasattr(opts, "t"):
1834 1831 timefunc = time.time
1835 1832 if hasattr(opts, "c"):
1836 1833 timefunc = clock
1837 1834
1838 1835 timer = timeit.Timer(timer=timefunc)
1839 1836 # this code has tight coupling to the inner workings of timeit.Timer,
1840 1837 # but is there a better way to achieve that the code stmt has access
1841 1838 # to the shell namespace?
1842 1839
1843 1840 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1844 1841 'setup': "pass"}
1845 1842 # Track compilation time so it can be reported if too long
1846 1843 # Minimum time above which compilation time will be reported
1847 1844 tc_min = 0.1
1848 1845
1849 1846 t0 = clock()
1850 1847 code = compile(src, "<magic-timeit>", "exec")
1851 1848 tc = clock()-t0
1852 1849
1853 1850 ns = {}
1854 1851 exec code in self.shell.user_ns, ns
1855 1852 timer.inner = ns["inner"]
1856 1853
1857 1854 if number == 0:
1858 1855 # determine number so that 0.2 <= total time < 2.0
1859 1856 number = 1
1860 1857 for i in range(1, 10):
1861 1858 if timer.timeit(number) >= 0.2:
1862 1859 break
1863 1860 number *= 10
1864 1861
1865 1862 best = min(timer.repeat(repeat, number)) / number
1866 1863
1867 1864 if best > 0.0 and best < 1000.0:
1868 1865 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1869 1866 elif best >= 1000.0:
1870 1867 order = 0
1871 1868 else:
1872 1869 order = 3
1873 1870 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1874 1871 precision,
1875 1872 best * scaling[order],
1876 1873 units[order])
1877 1874 if tc > tc_min:
1878 1875 print "Compiler time: %.2f s" % tc
1879 1876
1880 1877 @testdec.skip_doctest
1881 1878 def magic_time(self,parameter_s = ''):
1882 1879 """Time execution of a Python statement or expression.
1883 1880
1884 1881 The CPU and wall clock times are printed, and the value of the
1885 1882 expression (if any) is returned. Note that under Win32, system time
1886 1883 is always reported as 0, since it can not be measured.
1887 1884
1888 1885 This function provides very basic timing functionality. In Python
1889 1886 2.3, the timeit module offers more control and sophistication, so this
1890 1887 could be rewritten to use it (patches welcome).
1891 1888
1892 1889 Some examples:
1893 1890
1894 1891 In [1]: time 2**128
1895 1892 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1896 1893 Wall time: 0.00
1897 1894 Out[1]: 340282366920938463463374607431768211456L
1898 1895
1899 1896 In [2]: n = 1000000
1900 1897
1901 1898 In [3]: time sum(range(n))
1902 1899 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1903 1900 Wall time: 1.37
1904 1901 Out[3]: 499999500000L
1905 1902
1906 1903 In [4]: time print 'hello world'
1907 1904 hello world
1908 1905 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1909 1906 Wall time: 0.00
1910 1907
1911 1908 Note that the time needed by Python to compile the given expression
1912 1909 will be reported if it is more than 0.1s. In this example, the
1913 1910 actual exponentiation is done by Python at compilation time, so while
1914 1911 the expression can take a noticeable amount of time to compute, that
1915 1912 time is purely due to the compilation:
1916 1913
1917 1914 In [5]: time 3**9999;
1918 1915 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1919 1916 Wall time: 0.00 s
1920 1917
1921 1918 In [6]: time 3**999999;
1922 1919 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1923 1920 Wall time: 0.00 s
1924 1921 Compiler : 0.78 s
1925 1922 """
1926 1923
1927 1924 # fail immediately if the given expression can't be compiled
1928 1925
1929 1926 expr = self.shell.prefilter(parameter_s,False)
1930 1927
1931 1928 # Minimum time above which compilation time will be reported
1932 1929 tc_min = 0.1
1933 1930
1934 1931 try:
1935 1932 mode = 'eval'
1936 1933 t0 = clock()
1937 1934 code = compile(expr,'<timed eval>',mode)
1938 1935 tc = clock()-t0
1939 1936 except SyntaxError:
1940 1937 mode = 'exec'
1941 1938 t0 = clock()
1942 1939 code = compile(expr,'<timed exec>',mode)
1943 1940 tc = clock()-t0
1944 1941 # skew measurement as little as possible
1945 1942 glob = self.shell.user_ns
1946 1943 clk = clock2
1947 1944 wtime = time.time
1948 1945 # time execution
1949 1946 wall_st = wtime()
1950 1947 if mode=='eval':
1951 1948 st = clk()
1952 1949 out = eval(code,glob)
1953 1950 end = clk()
1954 1951 else:
1955 1952 st = clk()
1956 1953 exec code in glob
1957 1954 end = clk()
1958 1955 out = None
1959 1956 wall_end = wtime()
1960 1957 # Compute actual times and report
1961 1958 wall_time = wall_end-wall_st
1962 1959 cpu_user = end[0]-st[0]
1963 1960 cpu_sys = end[1]-st[1]
1964 1961 cpu_tot = cpu_user+cpu_sys
1965 1962 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1966 1963 (cpu_user,cpu_sys,cpu_tot)
1967 1964 print "Wall time: %.2f s" % wall_time
1968 1965 if tc > tc_min:
1969 1966 print "Compiler : %.2f s" % tc
1970 1967 return out
1971 1968
1972 1969 @testdec.skip_doctest
1973 1970 def magic_macro(self,parameter_s = ''):
1974 1971 """Define a set of input lines as a macro for future re-execution.
1975 1972
1976 1973 Usage:\\
1977 1974 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1978 1975
1979 1976 Options:
1980 1977
1981 1978 -r: use 'raw' input. By default, the 'processed' history is used,
1982 1979 so that magics are loaded in their transformed version to valid
1983 1980 Python. If this option is given, the raw input as typed as the
1984 1981 command line is used instead.
1985 1982
1986 1983 This will define a global variable called `name` which is a string
1987 1984 made of joining the slices and lines you specify (n1,n2,... numbers
1988 1985 above) from your input history into a single string. This variable
1989 1986 acts like an automatic function which re-executes those lines as if
1990 1987 you had typed them. You just type 'name' at the prompt and the code
1991 1988 executes.
1992 1989
1993 1990 The notation for indicating number ranges is: n1-n2 means 'use line
1994 1991 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1995 1992 using the lines numbered 5,6 and 7.
1996 1993
1997 1994 Note: as a 'hidden' feature, you can also use traditional python slice
1998 1995 notation, where N:M means numbers N through M-1.
1999 1996
2000 1997 For example, if your history contains (%hist prints it):
2001 1998
2002 1999 44: x=1
2003 2000 45: y=3
2004 2001 46: z=x+y
2005 2002 47: print x
2006 2003 48: a=5
2007 2004 49: print 'x',x,'y',y
2008 2005
2009 2006 you can create a macro with lines 44 through 47 (included) and line 49
2010 2007 called my_macro with:
2011 2008
2012 2009 In [55]: %macro my_macro 44-47 49
2013 2010
2014 2011 Now, typing `my_macro` (without quotes) will re-execute all this code
2015 2012 in one pass.
2016 2013
2017 2014 You don't need to give the line-numbers in order, and any given line
2018 2015 number can appear multiple times. You can assemble macros with any
2019 2016 lines from your input history in any order.
2020 2017
2021 2018 The macro is a simple object which holds its value in an attribute,
2022 2019 but IPython's display system checks for macros and executes them as
2023 2020 code instead of printing them when you type their name.
2024 2021
2025 2022 You can view a macro's contents by explicitly printing it with:
2026 2023
2027 2024 'print macro_name'.
2028 2025
2029 2026 For one-off cases which DON'T contain magic function calls in them you
2030 2027 can obtain similar results by explicitly executing slices from your
2031 2028 input history with:
2032 2029
2033 2030 In [60]: exec In[44:48]+In[49]"""
2034 2031
2035 2032 opts,args = self.parse_options(parameter_s,'r',mode='list')
2036 2033 if not args:
2037 2034 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2038 2035 macs.sort()
2039 2036 return macs
2040 2037 if len(args) == 1:
2041 2038 raise UsageError(
2042 2039 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2043 2040 name,ranges = args[0], args[1:]
2044 2041
2045 2042 #print 'rng',ranges # dbg
2046 2043 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2047 macro = Macro(lines)
2044 macro = Macro("\n".join(lines))
2048 2045 self.shell.define_macro(name, macro)
2049 2046 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2050 2047 print 'Macro contents:'
2051 2048 print macro,
2052 2049
2053 2050 def magic_save(self,parameter_s = ''):
2054 2051 """Save a set of lines to a given filename.
2055 2052
2056 2053 Usage:\\
2057 2054 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2058 2055
2059 2056 Options:
2060 2057
2061 2058 -r: use 'raw' input. By default, the 'processed' history is used,
2062 2059 so that magics are loaded in their transformed version to valid
2063 2060 Python. If this option is given, the raw input as typed as the
2064 2061 command line is used instead.
2065 2062
2066 2063 This function uses the same syntax as %macro for line extraction, but
2067 2064 instead of creating a macro it saves the resulting string to the
2068 2065 filename you specify.
2069 2066
2070 2067 It adds a '.py' extension to the file if you don't do so yourself, and
2071 2068 it asks for confirmation before overwriting existing files."""
2072 2069
2073 2070 opts,args = self.parse_options(parameter_s,'r',mode='list')
2074 2071 fname,ranges = args[0], args[1:]
2075 2072 if not fname.endswith('.py'):
2076 2073 fname += '.py'
2077 2074 if os.path.isfile(fname):
2078 2075 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2079 2076 if ans.lower() not in ['y','yes']:
2080 2077 print 'Operation cancelled.'
2081 2078 return
2082 2079 cmds = '\n'.join(self.extract_input_slices(ranges,opts.has_key('r')))
2083 2080 with open(fname,'w') as f:
2084 2081 f.write(cmds)
2085 2082 print 'The following commands were written to file `%s`:' % fname
2086 2083 print cmds
2087 2084
2088 2085 def _edit_macro(self,mname,macro):
2089 2086 """open an editor with the macro data in a file"""
2090 2087 filename = self.shell.mktempfile(macro.value)
2091 2088 self.shell.hooks.editor(filename)
2092 2089
2093 2090 # and make a new macro object, to replace the old one
2094 2091 mfile = open(filename)
2095 2092 mvalue = mfile.read()
2096 2093 mfile.close()
2097 2094 self.shell.user_ns[mname] = Macro(mvalue)
2098 2095
2099 2096 def magic_ed(self,parameter_s=''):
2100 2097 """Alias to %edit."""
2101 2098 return self.magic_edit(parameter_s)
2102 2099
2103 2100 @testdec.skip_doctest
2104 2101 def magic_edit(self,parameter_s='',last_call=['','']):
2105 2102 """Bring up an editor and execute the resulting code.
2106 2103
2107 2104 Usage:
2108 2105 %edit [options] [args]
2109 2106
2110 2107 %edit runs IPython's editor hook. The default version of this hook is
2111 2108 set to call the __IPYTHON__.rc.editor command. This is read from your
2112 2109 environment variable $EDITOR. If this isn't found, it will default to
2113 2110 vi under Linux/Unix and to notepad under Windows. See the end of this
2114 2111 docstring for how to change the editor hook.
2115 2112
2116 2113 You can also set the value of this editor via the command line option
2117 2114 '-editor' or in your ipythonrc file. This is useful if you wish to use
2118 2115 specifically for IPython an editor different from your typical default
2119 2116 (and for Windows users who typically don't set environment variables).
2120 2117
2121 2118 This command allows you to conveniently edit multi-line code right in
2122 2119 your IPython session.
2123 2120
2124 2121 If called without arguments, %edit opens up an empty editor with a
2125 2122 temporary file and will execute the contents of this file when you
2126 2123 close it (don't forget to save it!).
2127 2124
2128 2125
2129 2126 Options:
2130 2127
2131 2128 -n <number>: open the editor at a specified line number. By default,
2132 2129 the IPython editor hook uses the unix syntax 'editor +N filename', but
2133 2130 you can configure this by providing your own modified hook if your
2134 2131 favorite editor supports line-number specifications with a different
2135 2132 syntax.
2136 2133
2137 2134 -p: this will call the editor with the same data as the previous time
2138 2135 it was used, regardless of how long ago (in your current session) it
2139 2136 was.
2140 2137
2141 2138 -r: use 'raw' input. This option only applies to input taken from the
2142 2139 user's history. By default, the 'processed' history is used, so that
2143 2140 magics are loaded in their transformed version to valid Python. If
2144 2141 this option is given, the raw input as typed as the command line is
2145 2142 used instead. When you exit the editor, it will be executed by
2146 2143 IPython's own processor.
2147 2144
2148 2145 -x: do not execute the edited code immediately upon exit. This is
2149 2146 mainly useful if you are editing programs which need to be called with
2150 2147 command line arguments, which you can then do using %run.
2151 2148
2152 2149
2153 2150 Arguments:
2154 2151
2155 2152 If arguments are given, the following possibilites exist:
2156 2153
2157 2154 - The arguments are numbers or pairs of colon-separated numbers (like
2158 2155 1 4:8 9). These are interpreted as lines of previous input to be
2159 2156 loaded into the editor. The syntax is the same of the %macro command.
2160 2157
2161 2158 - If the argument doesn't start with a number, it is evaluated as a
2162 2159 variable and its contents loaded into the editor. You can thus edit
2163 2160 any string which contains python code (including the result of
2164 2161 previous edits).
2165 2162
2166 2163 - If the argument is the name of an object (other than a string),
2167 2164 IPython will try to locate the file where it was defined and open the
2168 2165 editor at the point where it is defined. You can use `%edit function`
2169 2166 to load an editor exactly at the point where 'function' is defined,
2170 2167 edit it and have the file be executed automatically.
2171 2168
2172 2169 If the object is a macro (see %macro for details), this opens up your
2173 2170 specified editor with a temporary file containing the macro's data.
2174 2171 Upon exit, the macro is reloaded with the contents of the file.
2175 2172
2176 2173 Note: opening at an exact line is only supported under Unix, and some
2177 2174 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2178 2175 '+NUMBER' parameter necessary for this feature. Good editors like
2179 2176 (X)Emacs, vi, jed, pico and joe all do.
2180 2177
2181 2178 - If the argument is not found as a variable, IPython will look for a
2182 2179 file with that name (adding .py if necessary) and load it into the
2183 2180 editor. It will execute its contents with execfile() when you exit,
2184 2181 loading any code in the file into your interactive namespace.
2185 2182
2186 2183 After executing your code, %edit will return as output the code you
2187 2184 typed in the editor (except when it was an existing file). This way
2188 2185 you can reload the code in further invocations of %edit as a variable,
2189 2186 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2190 2187 the output.
2191 2188
2192 2189 Note that %edit is also available through the alias %ed.
2193 2190
2194 2191 This is an example of creating a simple function inside the editor and
2195 2192 then modifying it. First, start up the editor:
2196 2193
2197 2194 In [1]: ed
2198 2195 Editing... done. Executing edited code...
2199 2196 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2200 2197
2201 2198 We can then call the function foo():
2202 2199
2203 2200 In [2]: foo()
2204 2201 foo() was defined in an editing session
2205 2202
2206 2203 Now we edit foo. IPython automatically loads the editor with the
2207 2204 (temporary) file where foo() was previously defined:
2208 2205
2209 2206 In [3]: ed foo
2210 2207 Editing... done. Executing edited code...
2211 2208
2212 2209 And if we call foo() again we get the modified version:
2213 2210
2214 2211 In [4]: foo()
2215 2212 foo() has now been changed!
2216 2213
2217 2214 Here is an example of how to edit a code snippet successive
2218 2215 times. First we call the editor:
2219 2216
2220 2217 In [5]: ed
2221 2218 Editing... done. Executing edited code...
2222 2219 hello
2223 2220 Out[5]: "print 'hello'n"
2224 2221
2225 2222 Now we call it again with the previous output (stored in _):
2226 2223
2227 2224 In [6]: ed _
2228 2225 Editing... done. Executing edited code...
2229 2226 hello world
2230 2227 Out[6]: "print 'hello world'n"
2231 2228
2232 2229 Now we call it with the output #8 (stored in _8, also as Out[8]):
2233 2230
2234 2231 In [7]: ed _8
2235 2232 Editing... done. Executing edited code...
2236 2233 hello again
2237 2234 Out[7]: "print 'hello again'n"
2238 2235
2239 2236
2240 2237 Changing the default editor hook:
2241 2238
2242 2239 If you wish to write your own editor hook, you can put it in a
2243 2240 configuration file which you load at startup time. The default hook
2244 2241 is defined in the IPython.core.hooks module, and you can use that as a
2245 2242 starting example for further modifications. That file also has
2246 2243 general instructions on how to set a new hook for use once you've
2247 2244 defined it."""
2248 2245
2249 2246 # FIXME: This function has become a convoluted mess. It needs a
2250 2247 # ground-up rewrite with clean, simple logic.
2251 2248
2252 2249 def make_filename(arg):
2253 2250 "Make a filename from the given args"
2254 2251 try:
2255 2252 filename = get_py_filename(arg)
2256 2253 except IOError:
2257 2254 if args.endswith('.py'):
2258 2255 filename = arg
2259 2256 else:
2260 2257 filename = None
2261 2258 return filename
2262 2259
2263 2260 # custom exceptions
2264 2261 class DataIsObject(Exception): pass
2265 2262
2266 2263 opts,args = self.parse_options(parameter_s,'prxn:')
2267 2264 # Set a few locals from the options for convenience:
2268 2265 opts_p = opts.has_key('p')
2269 2266 opts_r = opts.has_key('r')
2270 2267
2271 2268 # Default line number value
2272 2269 lineno = opts.get('n',None)
2273 2270
2274 2271 if opts_p:
2275 2272 args = '_%s' % last_call[0]
2276 2273 if not self.shell.user_ns.has_key(args):
2277 2274 args = last_call[1]
2278 2275
2279 2276 # use last_call to remember the state of the previous call, but don't
2280 2277 # let it be clobbered by successive '-p' calls.
2281 2278 try:
2282 2279 last_call[0] = self.shell.displayhook.prompt_count
2283 2280 if not opts_p:
2284 2281 last_call[1] = parameter_s
2285 2282 except:
2286 2283 pass
2287 2284
2288 2285 # by default this is done with temp files, except when the given
2289 2286 # arg is a filename
2290 2287 use_temp = 1
2291 2288
2292 2289 if re.match(r'\d',args):
2293 2290 # Mode where user specifies ranges of lines, like in %macro.
2294 2291 # This means that you can't edit files whose names begin with
2295 2292 # numbers this way. Tough.
2296 2293 ranges = args.split()
2297 data = ''.join(self.extract_input_slices(ranges,opts_r))
2294 data = '\n'.join(self.extract_input_slices(ranges,opts_r))
2298 2295 elif args.endswith('.py'):
2299 2296 filename = make_filename(args)
2300 2297 data = ''
2301 2298 use_temp = 0
2302 2299 elif args:
2303 2300 try:
2304 2301 # Load the parameter given as a variable. If not a string,
2305 2302 # process it as an object instead (below)
2306 2303
2307 2304 #print '*** args',args,'type',type(args) # dbg
2308 2305 data = eval(args,self.shell.user_ns)
2309 2306 if not type(data) in StringTypes:
2310 2307 raise DataIsObject
2311 2308
2312 2309 except (NameError,SyntaxError):
2313 2310 # given argument is not a variable, try as a filename
2314 2311 filename = make_filename(args)
2315 2312 if filename is None:
2316 2313 warn("Argument given (%s) can't be found as a variable "
2317 2314 "or as a filename." % args)
2318 2315 return
2319 2316
2320 2317 data = ''
2321 2318 use_temp = 0
2322 2319 except DataIsObject:
2323 2320
2324 2321 # macros have a special edit function
2325 2322 if isinstance(data,Macro):
2326 2323 self._edit_macro(args,data)
2327 2324 return
2328 2325
2329 2326 # For objects, try to edit the file where they are defined
2330 2327 try:
2331 2328 filename = inspect.getabsfile(data)
2332 2329 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2333 2330 # class created by %edit? Try to find source
2334 2331 # by looking for method definitions instead, the
2335 2332 # __module__ in those classes is FakeModule.
2336 2333 attrs = [getattr(data, aname) for aname in dir(data)]
2337 2334 for attr in attrs:
2338 2335 if not inspect.ismethod(attr):
2339 2336 continue
2340 2337 filename = inspect.getabsfile(attr)
2341 2338 if filename and 'fakemodule' not in filename.lower():
2342 2339 # change the attribute to be the edit target instead
2343 2340 data = attr
2344 2341 break
2345 2342
2346 2343 datafile = 1
2347 2344 except TypeError:
2348 2345 filename = make_filename(args)
2349 2346 datafile = 1
2350 2347 warn('Could not find file where `%s` is defined.\n'
2351 2348 'Opening a file named `%s`' % (args,filename))
2352 2349 # Now, make sure we can actually read the source (if it was in
2353 2350 # a temp file it's gone by now).
2354 2351 if datafile:
2355 2352 try:
2356 2353 if lineno is None:
2357 2354 lineno = inspect.getsourcelines(data)[1]
2358 2355 except IOError:
2359 2356 filename = make_filename(args)
2360 2357 if filename is None:
2361 2358 warn('The file `%s` where `%s` was defined cannot '
2362 2359 'be read.' % (filename,data))
2363 2360 return
2364 2361 use_temp = 0
2365 2362 else:
2366 2363 data = ''
2367 2364
2368 2365 if use_temp:
2369 2366 filename = self.shell.mktempfile(data)
2370 2367 print 'IPython will make a temporary file named:',filename
2371 2368
2372 2369 # do actual editing here
2373 2370 print 'Editing...',
2374 2371 sys.stdout.flush()
2375 2372 try:
2376 2373 # Quote filenames that may have spaces in them
2377 2374 if ' ' in filename:
2378 2375 filename = "%s" % filename
2379 2376 self.shell.hooks.editor(filename,lineno)
2380 2377 except TryNext:
2381 2378 warn('Could not open editor')
2382 2379 return
2383 2380
2384 2381 # XXX TODO: should this be generalized for all string vars?
2385 2382 # For now, this is special-cased to blocks created by cpaste
2386 2383 if args.strip() == 'pasted_block':
2387 2384 self.shell.user_ns['pasted_block'] = file_read(filename)
2388 2385
2389 2386 if opts.has_key('x'): # -x prevents actual execution
2390 2387 print
2391 2388 else:
2392 2389 print 'done. Executing edited code...'
2393 2390 if opts_r:
2394 2391 self.shell.run_cell(file_read(filename))
2395 2392 else:
2396 2393 self.shell.safe_execfile(filename,self.shell.user_ns,
2397 2394 self.shell.user_ns)
2398 2395
2399 2396
2400 2397 if use_temp:
2401 2398 try:
2402 2399 return open(filename).read()
2403 2400 except IOError,msg:
2404 2401 if msg.filename == filename:
2405 2402 warn('File not found. Did you forget to save?')
2406 2403 return
2407 2404 else:
2408 2405 self.shell.showtraceback()
2409 2406
2410 2407 def magic_xmode(self,parameter_s = ''):
2411 2408 """Switch modes for the exception handlers.
2412 2409
2413 2410 Valid modes: Plain, Context and Verbose.
2414 2411
2415 2412 If called without arguments, acts as a toggle."""
2416 2413
2417 2414 def xmode_switch_err(name):
2418 2415 warn('Error changing %s exception modes.\n%s' %
2419 2416 (name,sys.exc_info()[1]))
2420 2417
2421 2418 shell = self.shell
2422 2419 new_mode = parameter_s.strip().capitalize()
2423 2420 try:
2424 2421 shell.InteractiveTB.set_mode(mode=new_mode)
2425 2422 print 'Exception reporting mode:',shell.InteractiveTB.mode
2426 2423 except:
2427 2424 xmode_switch_err('user')
2428 2425
2429 2426 def magic_colors(self,parameter_s = ''):
2430 2427 """Switch color scheme for prompts, info system and exception handlers.
2431 2428
2432 2429 Currently implemented schemes: NoColor, Linux, LightBG.
2433 2430
2434 2431 Color scheme names are not case-sensitive.
2435 2432
2436 2433 Examples
2437 2434 --------
2438 2435 To get a plain black and white terminal::
2439 2436
2440 2437 %colors nocolor
2441 2438 """
2442 2439
2443 2440 def color_switch_err(name):
2444 2441 warn('Error changing %s color schemes.\n%s' %
2445 2442 (name,sys.exc_info()[1]))
2446 2443
2447 2444
2448 2445 new_scheme = parameter_s.strip()
2449 2446 if not new_scheme:
2450 2447 raise UsageError(
2451 2448 "%colors: you must specify a color scheme. See '%colors?'")
2452 2449 return
2453 2450 # local shortcut
2454 2451 shell = self.shell
2455 2452
2456 2453 import IPython.utils.rlineimpl as readline
2457 2454
2458 2455 if not readline.have_readline and sys.platform == "win32":
2459 2456 msg = """\
2460 2457 Proper color support under MS Windows requires the pyreadline library.
2461 2458 You can find it at:
2462 2459 http://ipython.scipy.org/moin/PyReadline/Intro
2463 2460 Gary's readline needs the ctypes module, from:
2464 2461 http://starship.python.net/crew/theller/ctypes
2465 2462 (Note that ctypes is already part of Python versions 2.5 and newer).
2466 2463
2467 2464 Defaulting color scheme to 'NoColor'"""
2468 2465 new_scheme = 'NoColor'
2469 2466 warn(msg)
2470 2467
2471 2468 # readline option is 0
2472 2469 if not shell.has_readline:
2473 2470 new_scheme = 'NoColor'
2474 2471
2475 2472 # Set prompt colors
2476 2473 try:
2477 2474 shell.displayhook.set_colors(new_scheme)
2478 2475 except:
2479 2476 color_switch_err('prompt')
2480 2477 else:
2481 2478 shell.colors = \
2482 2479 shell.displayhook.color_table.active_scheme_name
2483 2480 # Set exception colors
2484 2481 try:
2485 2482 shell.InteractiveTB.set_colors(scheme = new_scheme)
2486 2483 shell.SyntaxTB.set_colors(scheme = new_scheme)
2487 2484 except:
2488 2485 color_switch_err('exception')
2489 2486
2490 2487 # Set info (for 'object?') colors
2491 2488 if shell.color_info:
2492 2489 try:
2493 2490 shell.inspector.set_active_scheme(new_scheme)
2494 2491 except:
2495 2492 color_switch_err('object inspector')
2496 2493 else:
2497 2494 shell.inspector.set_active_scheme('NoColor')
2498 2495
2499 2496 def magic_pprint(self, parameter_s=''):
2500 2497 """Toggle pretty printing on/off."""
2501 2498 ptformatter = self.shell.display_formatter.formatters['text/plain']
2502 2499 ptformatter.pprint = bool(1 - ptformatter.pprint)
2503 2500 print 'Pretty printing has been turned', \
2504 2501 ['OFF','ON'][ptformatter.pprint]
2505 2502
2506 2503 def magic_Exit(self, parameter_s=''):
2507 2504 """Exit IPython."""
2508 2505
2509 2506 self.shell.ask_exit()
2510 2507
2511 2508 # Add aliases as magics so all common forms work: exit, quit, Exit, Quit.
2512 2509 magic_exit = magic_quit = magic_Quit = magic_Exit
2513 2510
2514 2511 #......................................................................
2515 2512 # Functions to implement unix shell-type things
2516 2513
2517 2514 @testdec.skip_doctest
2518 2515 def magic_alias(self, parameter_s = ''):
2519 2516 """Define an alias for a system command.
2520 2517
2521 2518 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2522 2519
2523 2520 Then, typing 'alias_name params' will execute the system command 'cmd
2524 2521 params' (from your underlying operating system).
2525 2522
2526 2523 Aliases have lower precedence than magic functions and Python normal
2527 2524 variables, so if 'foo' is both a Python variable and an alias, the
2528 2525 alias can not be executed until 'del foo' removes the Python variable.
2529 2526
2530 2527 You can use the %l specifier in an alias definition to represent the
2531 2528 whole line when the alias is called. For example:
2532 2529
2533 2530 In [2]: alias bracket echo "Input in brackets: <%l>"
2534 2531 In [3]: bracket hello world
2535 2532 Input in brackets: <hello world>
2536 2533
2537 2534 You can also define aliases with parameters using %s specifiers (one
2538 2535 per parameter):
2539 2536
2540 2537 In [1]: alias parts echo first %s second %s
2541 2538 In [2]: %parts A B
2542 2539 first A second B
2543 2540 In [3]: %parts A
2544 2541 Incorrect number of arguments: 2 expected.
2545 2542 parts is an alias to: 'echo first %s second %s'
2546 2543
2547 2544 Note that %l and %s are mutually exclusive. You can only use one or
2548 2545 the other in your aliases.
2549 2546
2550 2547 Aliases expand Python variables just like system calls using ! or !!
2551 2548 do: all expressions prefixed with '$' get expanded. For details of
2552 2549 the semantic rules, see PEP-215:
2553 2550 http://www.python.org/peps/pep-0215.html. This is the library used by
2554 2551 IPython for variable expansion. If you want to access a true shell
2555 2552 variable, an extra $ is necessary to prevent its expansion by IPython:
2556 2553
2557 2554 In [6]: alias show echo
2558 2555 In [7]: PATH='A Python string'
2559 2556 In [8]: show $PATH
2560 2557 A Python string
2561 2558 In [9]: show $$PATH
2562 2559 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2563 2560
2564 2561 You can use the alias facility to acess all of $PATH. See the %rehash
2565 2562 and %rehashx functions, which automatically create aliases for the
2566 2563 contents of your $PATH.
2567 2564
2568 2565 If called with no parameters, %alias prints the current alias table."""
2569 2566
2570 2567 par = parameter_s.strip()
2571 2568 if not par:
2572 2569 stored = self.db.get('stored_aliases', {} )
2573 2570 aliases = sorted(self.shell.alias_manager.aliases)
2574 2571 # for k, v in stored:
2575 2572 # atab.append(k, v[0])
2576 2573
2577 2574 print "Total number of aliases:", len(aliases)
2578 2575 sys.stdout.flush()
2579 2576 return aliases
2580 2577
2581 2578 # Now try to define a new one
2582 2579 try:
2583 2580 alias,cmd = par.split(None, 1)
2584 2581 except:
2585 2582 print oinspect.getdoc(self.magic_alias)
2586 2583 else:
2587 2584 self.shell.alias_manager.soft_define_alias(alias, cmd)
2588 2585 # end magic_alias
2589 2586
2590 2587 def magic_unalias(self, parameter_s = ''):
2591 2588 """Remove an alias"""
2592 2589
2593 2590 aname = parameter_s.strip()
2594 2591 self.shell.alias_manager.undefine_alias(aname)
2595 2592 stored = self.db.get('stored_aliases', {} )
2596 2593 if aname in stored:
2597 2594 print "Removing %stored alias",aname
2598 2595 del stored[aname]
2599 2596 self.db['stored_aliases'] = stored
2600 2597
2601 2598 def magic_rehashx(self, parameter_s = ''):
2602 2599 """Update the alias table with all executable files in $PATH.
2603 2600
2604 2601 This version explicitly checks that every entry in $PATH is a file
2605 2602 with execute access (os.X_OK), so it is much slower than %rehash.
2606 2603
2607 2604 Under Windows, it checks executability as a match agains a
2608 2605 '|'-separated string of extensions, stored in the IPython config
2609 2606 variable win_exec_ext. This defaults to 'exe|com|bat'.
2610 2607
2611 2608 This function also resets the root module cache of module completer,
2612 2609 used on slow filesystems.
2613 2610 """
2614 2611 from IPython.core.alias import InvalidAliasError
2615 2612
2616 2613 # for the benefit of module completer in ipy_completers.py
2617 2614 del self.db['rootmodules']
2618 2615
2619 2616 path = [os.path.abspath(os.path.expanduser(p)) for p in
2620 2617 os.environ.get('PATH','').split(os.pathsep)]
2621 2618 path = filter(os.path.isdir,path)
2622 2619
2623 2620 syscmdlist = []
2624 2621 # Now define isexec in a cross platform manner.
2625 2622 if os.name == 'posix':
2626 2623 isexec = lambda fname:os.path.isfile(fname) and \
2627 2624 os.access(fname,os.X_OK)
2628 2625 else:
2629 2626 try:
2630 2627 winext = os.environ['pathext'].replace(';','|').replace('.','')
2631 2628 except KeyError:
2632 2629 winext = 'exe|com|bat|py'
2633 2630 if 'py' not in winext:
2634 2631 winext += '|py'
2635 2632 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2636 2633 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2637 2634 savedir = os.getcwd()
2638 2635
2639 2636 # Now walk the paths looking for executables to alias.
2640 2637 try:
2641 2638 # write the whole loop for posix/Windows so we don't have an if in
2642 2639 # the innermost part
2643 2640 if os.name == 'posix':
2644 2641 for pdir in path:
2645 2642 os.chdir(pdir)
2646 2643 for ff in os.listdir(pdir):
2647 2644 if isexec(ff):
2648 2645 try:
2649 2646 # Removes dots from the name since ipython
2650 2647 # will assume names with dots to be python.
2651 2648 self.shell.alias_manager.define_alias(
2652 2649 ff.replace('.',''), ff)
2653 2650 except InvalidAliasError:
2654 2651 pass
2655 2652 else:
2656 2653 syscmdlist.append(ff)
2657 2654 else:
2658 2655 no_alias = self.shell.alias_manager.no_alias
2659 2656 for pdir in path:
2660 2657 os.chdir(pdir)
2661 2658 for ff in os.listdir(pdir):
2662 2659 base, ext = os.path.splitext(ff)
2663 2660 if isexec(ff) and base.lower() not in no_alias:
2664 2661 if ext.lower() == '.exe':
2665 2662 ff = base
2666 2663 try:
2667 2664 # Removes dots from the name since ipython
2668 2665 # will assume names with dots to be python.
2669 2666 self.shell.alias_manager.define_alias(
2670 2667 base.lower().replace('.',''), ff)
2671 2668 except InvalidAliasError:
2672 2669 pass
2673 2670 syscmdlist.append(ff)
2674 2671 db = self.db
2675 2672 db['syscmdlist'] = syscmdlist
2676 2673 finally:
2677 2674 os.chdir(savedir)
2678 2675
2679 2676 @testdec.skip_doctest
2680 2677 def magic_pwd(self, parameter_s = ''):
2681 2678 """Return the current working directory path.
2682 2679
2683 2680 Examples
2684 2681 --------
2685 2682 ::
2686 2683
2687 2684 In [9]: pwd
2688 2685 Out[9]: '/home/tsuser/sprint/ipython'
2689 2686 """
2690 2687 return os.getcwd()
2691 2688
2692 2689 @testdec.skip_doctest
2693 2690 def magic_cd(self, parameter_s=''):
2694 2691 """Change the current working directory.
2695 2692
2696 2693 This command automatically maintains an internal list of directories
2697 2694 you visit during your IPython session, in the variable _dh. The
2698 2695 command %dhist shows this history nicely formatted. You can also
2699 2696 do 'cd -<tab>' to see directory history conveniently.
2700 2697
2701 2698 Usage:
2702 2699
2703 2700 cd 'dir': changes to directory 'dir'.
2704 2701
2705 2702 cd -: changes to the last visited directory.
2706 2703
2707 2704 cd -<n>: changes to the n-th directory in the directory history.
2708 2705
2709 2706 cd --foo: change to directory that matches 'foo' in history
2710 2707
2711 2708 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2712 2709 (note: cd <bookmark_name> is enough if there is no
2713 2710 directory <bookmark_name>, but a bookmark with the name exists.)
2714 2711 'cd -b <tab>' allows you to tab-complete bookmark names.
2715 2712
2716 2713 Options:
2717 2714
2718 2715 -q: quiet. Do not print the working directory after the cd command is
2719 2716 executed. By default IPython's cd command does print this directory,
2720 2717 since the default prompts do not display path information.
2721 2718
2722 2719 Note that !cd doesn't work for this purpose because the shell where
2723 2720 !command runs is immediately discarded after executing 'command'.
2724 2721
2725 2722 Examples
2726 2723 --------
2727 2724 ::
2728 2725
2729 2726 In [10]: cd parent/child
2730 2727 /home/tsuser/parent/child
2731 2728 """
2732 2729
2733 2730 parameter_s = parameter_s.strip()
2734 2731 #bkms = self.shell.persist.get("bookmarks",{})
2735 2732
2736 2733 oldcwd = os.getcwd()
2737 2734 numcd = re.match(r'(-)(\d+)$',parameter_s)
2738 2735 # jump in directory history by number
2739 2736 if numcd:
2740 2737 nn = int(numcd.group(2))
2741 2738 try:
2742 2739 ps = self.shell.user_ns['_dh'][nn]
2743 2740 except IndexError:
2744 2741 print 'The requested directory does not exist in history.'
2745 2742 return
2746 2743 else:
2747 2744 opts = {}
2748 2745 elif parameter_s.startswith('--'):
2749 2746 ps = None
2750 2747 fallback = None
2751 2748 pat = parameter_s[2:]
2752 2749 dh = self.shell.user_ns['_dh']
2753 2750 # first search only by basename (last component)
2754 2751 for ent in reversed(dh):
2755 2752 if pat in os.path.basename(ent) and os.path.isdir(ent):
2756 2753 ps = ent
2757 2754 break
2758 2755
2759 2756 if fallback is None and pat in ent and os.path.isdir(ent):
2760 2757 fallback = ent
2761 2758
2762 2759 # if we have no last part match, pick the first full path match
2763 2760 if ps is None:
2764 2761 ps = fallback
2765 2762
2766 2763 if ps is None:
2767 2764 print "No matching entry in directory history"
2768 2765 return
2769 2766 else:
2770 2767 opts = {}
2771 2768
2772 2769
2773 2770 else:
2774 2771 #turn all non-space-escaping backslashes to slashes,
2775 2772 # for c:\windows\directory\names\
2776 2773 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2777 2774 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2778 2775 # jump to previous
2779 2776 if ps == '-':
2780 2777 try:
2781 2778 ps = self.shell.user_ns['_dh'][-2]
2782 2779 except IndexError:
2783 2780 raise UsageError('%cd -: No previous directory to change to.')
2784 2781 # jump to bookmark if needed
2785 2782 else:
2786 2783 if not os.path.isdir(ps) or opts.has_key('b'):
2787 2784 bkms = self.db.get('bookmarks', {})
2788 2785
2789 2786 if bkms.has_key(ps):
2790 2787 target = bkms[ps]
2791 2788 print '(bookmark:%s) -> %s' % (ps,target)
2792 2789 ps = target
2793 2790 else:
2794 2791 if opts.has_key('b'):
2795 2792 raise UsageError("Bookmark '%s' not found. "
2796 2793 "Use '%%bookmark -l' to see your bookmarks." % ps)
2797 2794
2798 2795 # at this point ps should point to the target dir
2799 2796 if ps:
2800 2797 try:
2801 2798 os.chdir(os.path.expanduser(ps))
2802 2799 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2803 2800 set_term_title('IPython: ' + abbrev_cwd())
2804 2801 except OSError:
2805 2802 print sys.exc_info()[1]
2806 2803 else:
2807 2804 cwd = os.getcwd()
2808 2805 dhist = self.shell.user_ns['_dh']
2809 2806 if oldcwd != cwd:
2810 2807 dhist.append(cwd)
2811 2808 self.db['dhist'] = compress_dhist(dhist)[-100:]
2812 2809
2813 2810 else:
2814 2811 os.chdir(self.shell.home_dir)
2815 2812 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2816 2813 set_term_title('IPython: ' + '~')
2817 2814 cwd = os.getcwd()
2818 2815 dhist = self.shell.user_ns['_dh']
2819 2816
2820 2817 if oldcwd != cwd:
2821 2818 dhist.append(cwd)
2822 2819 self.db['dhist'] = compress_dhist(dhist)[-100:]
2823 2820 if not 'q' in opts and self.shell.user_ns['_dh']:
2824 2821 print self.shell.user_ns['_dh'][-1]
2825 2822
2826 2823
2827 2824 def magic_env(self, parameter_s=''):
2828 2825 """List environment variables."""
2829 2826
2830 2827 return os.environ.data
2831 2828
2832 2829 def magic_pushd(self, parameter_s=''):
2833 2830 """Place the current dir on stack and change directory.
2834 2831
2835 2832 Usage:\\
2836 2833 %pushd ['dirname']
2837 2834 """
2838 2835
2839 2836 dir_s = self.shell.dir_stack
2840 2837 tgt = os.path.expanduser(parameter_s)
2841 2838 cwd = os.getcwd().replace(self.home_dir,'~')
2842 2839 if tgt:
2843 2840 self.magic_cd(parameter_s)
2844 2841 dir_s.insert(0,cwd)
2845 2842 return self.magic_dirs()
2846 2843
2847 2844 def magic_popd(self, parameter_s=''):
2848 2845 """Change to directory popped off the top of the stack.
2849 2846 """
2850 2847 if not self.shell.dir_stack:
2851 2848 raise UsageError("%popd on empty stack")
2852 2849 top = self.shell.dir_stack.pop(0)
2853 2850 self.magic_cd(top)
2854 2851 print "popd ->",top
2855 2852
2856 2853 def magic_dirs(self, parameter_s=''):
2857 2854 """Return the current directory stack."""
2858 2855
2859 2856 return self.shell.dir_stack
2860 2857
2861 2858 def magic_dhist(self, parameter_s=''):
2862 2859 """Print your history of visited directories.
2863 2860
2864 2861 %dhist -> print full history\\
2865 2862 %dhist n -> print last n entries only\\
2866 2863 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2867 2864
2868 2865 This history is automatically maintained by the %cd command, and
2869 2866 always available as the global list variable _dh. You can use %cd -<n>
2870 2867 to go to directory number <n>.
2871 2868
2872 2869 Note that most of time, you should view directory history by entering
2873 2870 cd -<TAB>.
2874 2871
2875 2872 """
2876 2873
2877 2874 dh = self.shell.user_ns['_dh']
2878 2875 if parameter_s:
2879 2876 try:
2880 2877 args = map(int,parameter_s.split())
2881 2878 except:
2882 2879 self.arg_err(Magic.magic_dhist)
2883 2880 return
2884 2881 if len(args) == 1:
2885 2882 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2886 2883 elif len(args) == 2:
2887 2884 ini,fin = args
2888 2885 else:
2889 2886 self.arg_err(Magic.magic_dhist)
2890 2887 return
2891 2888 else:
2892 2889 ini,fin = 0,len(dh)
2893 2890 nlprint(dh,
2894 2891 header = 'Directory history (kept in _dh)',
2895 2892 start=ini,stop=fin)
2896 2893
2897 2894 @testdec.skip_doctest
2898 2895 def magic_sc(self, parameter_s=''):
2899 2896 """Shell capture - execute a shell command and capture its output.
2900 2897
2901 2898 DEPRECATED. Suboptimal, retained for backwards compatibility.
2902 2899
2903 2900 You should use the form 'var = !command' instead. Example:
2904 2901
2905 2902 "%sc -l myfiles = ls ~" should now be written as
2906 2903
2907 2904 "myfiles = !ls ~"
2908 2905
2909 2906 myfiles.s, myfiles.l and myfiles.n still apply as documented
2910 2907 below.
2911 2908
2912 2909 --
2913 2910 %sc [options] varname=command
2914 2911
2915 2912 IPython will run the given command using commands.getoutput(), and
2916 2913 will then update the user's interactive namespace with a variable
2917 2914 called varname, containing the value of the call. Your command can
2918 2915 contain shell wildcards, pipes, etc.
2919 2916
2920 2917 The '=' sign in the syntax is mandatory, and the variable name you
2921 2918 supply must follow Python's standard conventions for valid names.
2922 2919
2923 2920 (A special format without variable name exists for internal use)
2924 2921
2925 2922 Options:
2926 2923
2927 2924 -l: list output. Split the output on newlines into a list before
2928 2925 assigning it to the given variable. By default the output is stored
2929 2926 as a single string.
2930 2927
2931 2928 -v: verbose. Print the contents of the variable.
2932 2929
2933 2930 In most cases you should not need to split as a list, because the
2934 2931 returned value is a special type of string which can automatically
2935 2932 provide its contents either as a list (split on newlines) or as a
2936 2933 space-separated string. These are convenient, respectively, either
2937 2934 for sequential processing or to be passed to a shell command.
2938 2935
2939 2936 For example:
2940 2937
2941 2938 # all-random
2942 2939
2943 2940 # Capture into variable a
2944 2941 In [1]: sc a=ls *py
2945 2942
2946 2943 # a is a string with embedded newlines
2947 2944 In [2]: a
2948 2945 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2949 2946
2950 2947 # which can be seen as a list:
2951 2948 In [3]: a.l
2952 2949 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2953 2950
2954 2951 # or as a whitespace-separated string:
2955 2952 In [4]: a.s
2956 2953 Out[4]: 'setup.py win32_manual_post_install.py'
2957 2954
2958 2955 # a.s is useful to pass as a single command line:
2959 2956 In [5]: !wc -l $a.s
2960 2957 146 setup.py
2961 2958 130 win32_manual_post_install.py
2962 2959 276 total
2963 2960
2964 2961 # while the list form is useful to loop over:
2965 2962 In [6]: for f in a.l:
2966 2963 ...: !wc -l $f
2967 2964 ...:
2968 2965 146 setup.py
2969 2966 130 win32_manual_post_install.py
2970 2967
2971 2968 Similiarly, the lists returned by the -l option are also special, in
2972 2969 the sense that you can equally invoke the .s attribute on them to
2973 2970 automatically get a whitespace-separated string from their contents:
2974 2971
2975 2972 In [7]: sc -l b=ls *py
2976 2973
2977 2974 In [8]: b
2978 2975 Out[8]: ['setup.py', 'win32_manual_post_install.py']
2979 2976
2980 2977 In [9]: b.s
2981 2978 Out[9]: 'setup.py win32_manual_post_install.py'
2982 2979
2983 2980 In summary, both the lists and strings used for ouptut capture have
2984 2981 the following special attributes:
2985 2982
2986 2983 .l (or .list) : value as list.
2987 2984 .n (or .nlstr): value as newline-separated string.
2988 2985 .s (or .spstr): value as space-separated string.
2989 2986 """
2990 2987
2991 2988 opts,args = self.parse_options(parameter_s,'lv')
2992 2989 # Try to get a variable name and command to run
2993 2990 try:
2994 2991 # the variable name must be obtained from the parse_options
2995 2992 # output, which uses shlex.split to strip options out.
2996 2993 var,_ = args.split('=',1)
2997 2994 var = var.strip()
2998 2995 # But the the command has to be extracted from the original input
2999 2996 # parameter_s, not on what parse_options returns, to avoid the
3000 2997 # quote stripping which shlex.split performs on it.
3001 2998 _,cmd = parameter_s.split('=',1)
3002 2999 except ValueError:
3003 3000 var,cmd = '',''
3004 3001 # If all looks ok, proceed
3005 3002 split = 'l' in opts
3006 3003 out = self.shell.getoutput(cmd, split=split)
3007 3004 if opts.has_key('v'):
3008 3005 print '%s ==\n%s' % (var,pformat(out))
3009 3006 if var:
3010 3007 self.shell.user_ns.update({var:out})
3011 3008 else:
3012 3009 return out
3013 3010
3014 3011 def magic_sx(self, parameter_s=''):
3015 3012 """Shell execute - run a shell command and capture its output.
3016 3013
3017 3014 %sx command
3018 3015
3019 3016 IPython will run the given command using commands.getoutput(), and
3020 3017 return the result formatted as a list (split on '\\n'). Since the
3021 3018 output is _returned_, it will be stored in ipython's regular output
3022 3019 cache Out[N] and in the '_N' automatic variables.
3023 3020
3024 3021 Notes:
3025 3022
3026 3023 1) If an input line begins with '!!', then %sx is automatically
3027 3024 invoked. That is, while:
3028 3025 !ls
3029 3026 causes ipython to simply issue system('ls'), typing
3030 3027 !!ls
3031 3028 is a shorthand equivalent to:
3032 3029 %sx ls
3033 3030
3034 3031 2) %sx differs from %sc in that %sx automatically splits into a list,
3035 3032 like '%sc -l'. The reason for this is to make it as easy as possible
3036 3033 to process line-oriented shell output via further python commands.
3037 3034 %sc is meant to provide much finer control, but requires more
3038 3035 typing.
3039 3036
3040 3037 3) Just like %sc -l, this is a list with special attributes:
3041 3038
3042 3039 .l (or .list) : value as list.
3043 3040 .n (or .nlstr): value as newline-separated string.
3044 3041 .s (or .spstr): value as whitespace-separated string.
3045 3042
3046 3043 This is very useful when trying to use such lists as arguments to
3047 3044 system commands."""
3048 3045
3049 3046 if parameter_s:
3050 3047 return self.shell.getoutput(parameter_s)
3051 3048
3052 3049 def magic_r(self, parameter_s=''):
3053 3050 """Repeat previous input.
3054 3051
3055 3052 Note: Consider using the more powerfull %rep instead!
3056 3053
3057 3054 If given an argument, repeats the previous command which starts with
3058 3055 the same string, otherwise it just repeats the previous input.
3059 3056
3060 3057 Shell escaped commands (with ! as first character) are not recognized
3061 3058 by this system, only pure python code and magic commands.
3062 3059 """
3063 3060
3064 3061 start = parameter_s.strip()
3065 3062 esc_magic = ESC_MAGIC
3066 3063 # Identify magic commands even if automagic is on (which means
3067 3064 # the in-memory version is different from that typed by the user).
3068 3065 if self.shell.automagic:
3069 3066 start_magic = esc_magic+start
3070 3067 else:
3071 3068 start_magic = start
3072 3069 # Look through the input history in reverse
3073 3070 for n in range(len(self.shell.history_manager.input_hist_parsed)-2,0,-1):
3074 3071 input = self.shell.history_manager.input_hist_parsed[n]
3075 3072 # skip plain 'r' lines so we don't recurse to infinity
3076 3073 if input != '_ip.magic("r")\n' and \
3077 3074 (input.startswith(start) or input.startswith(start_magic)):
3078 3075 #print 'match',`input` # dbg
3079 3076 print 'Executing:',input,
3080 3077 self.shell.run_cell(input)
3081 3078 return
3082 3079 print 'No previous input matching `%s` found.' % start
3083 3080
3084 3081
3085 3082 def magic_bookmark(self, parameter_s=''):
3086 3083 """Manage IPython's bookmark system.
3087 3084
3088 3085 %bookmark <name> - set bookmark to current dir
3089 3086 %bookmark <name> <dir> - set bookmark to <dir>
3090 3087 %bookmark -l - list all bookmarks
3091 3088 %bookmark -d <name> - remove bookmark
3092 3089 %bookmark -r - remove all bookmarks
3093 3090
3094 3091 You can later on access a bookmarked folder with:
3095 3092 %cd -b <name>
3096 3093 or simply '%cd <name>' if there is no directory called <name> AND
3097 3094 there is such a bookmark defined.
3098 3095
3099 3096 Your bookmarks persist through IPython sessions, but they are
3100 3097 associated with each profile."""
3101 3098
3102 3099 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3103 3100 if len(args) > 2:
3104 3101 raise UsageError("%bookmark: too many arguments")
3105 3102
3106 3103 bkms = self.db.get('bookmarks',{})
3107 3104
3108 3105 if opts.has_key('d'):
3109 3106 try:
3110 3107 todel = args[0]
3111 3108 except IndexError:
3112 3109 raise UsageError(
3113 3110 "%bookmark -d: must provide a bookmark to delete")
3114 3111 else:
3115 3112 try:
3116 3113 del bkms[todel]
3117 3114 except KeyError:
3118 3115 raise UsageError(
3119 3116 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3120 3117
3121 3118 elif opts.has_key('r'):
3122 3119 bkms = {}
3123 3120 elif opts.has_key('l'):
3124 3121 bks = bkms.keys()
3125 3122 bks.sort()
3126 3123 if bks:
3127 3124 size = max(map(len,bks))
3128 3125 else:
3129 3126 size = 0
3130 3127 fmt = '%-'+str(size)+'s -> %s'
3131 3128 print 'Current bookmarks:'
3132 3129 for bk in bks:
3133 3130 print fmt % (bk,bkms[bk])
3134 3131 else:
3135 3132 if not args:
3136 3133 raise UsageError("%bookmark: You must specify the bookmark name")
3137 3134 elif len(args)==1:
3138 3135 bkms[args[0]] = os.getcwd()
3139 3136 elif len(args)==2:
3140 3137 bkms[args[0]] = args[1]
3141 3138 self.db['bookmarks'] = bkms
3142 3139
3143 3140 def magic_pycat(self, parameter_s=''):
3144 3141 """Show a syntax-highlighted file through a pager.
3145 3142
3146 3143 This magic is similar to the cat utility, but it will assume the file
3147 3144 to be Python source and will show it with syntax highlighting. """
3148 3145
3149 3146 try:
3150 3147 filename = get_py_filename(parameter_s)
3151 3148 cont = file_read(filename)
3152 3149 except IOError:
3153 3150 try:
3154 3151 cont = eval(parameter_s,self.user_ns)
3155 3152 except NameError:
3156 3153 cont = None
3157 3154 if cont is None:
3158 3155 print "Error: no such file or variable"
3159 3156 return
3160 3157
3161 3158 page.page(self.shell.pycolorize(cont))
3162 3159
3163 3160 def _rerun_pasted(self):
3164 3161 """ Rerun a previously pasted command.
3165 3162 """
3166 3163 b = self.user_ns.get('pasted_block', None)
3167 3164 if b is None:
3168 3165 raise UsageError('No previous pasted block available')
3169 3166 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3170 3167 exec b in self.user_ns
3171 3168
3172 3169 def _get_pasted_lines(self, sentinel):
3173 3170 """ Yield pasted lines until the user enters the given sentinel value.
3174 3171 """
3175 3172 from IPython.core import interactiveshell
3176 3173 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3177 3174 while True:
3178 3175 l = interactiveshell.raw_input_original(':')
3179 3176 if l == sentinel:
3180 3177 return
3181 3178 else:
3182 3179 yield l
3183 3180
3184 3181 def _strip_pasted_lines_for_code(self, raw_lines):
3185 3182 """ Strip non-code parts of a sequence of lines to return a block of
3186 3183 code.
3187 3184 """
3188 3185 # Regular expressions that declare text we strip from the input:
3189 3186 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3190 3187 r'^\s*(\s?>)+', # Python input prompt
3191 3188 r'^\s*\.{3,}', # Continuation prompts
3192 3189 r'^\++',
3193 3190 ]
3194 3191
3195 3192 strip_from_start = map(re.compile,strip_re)
3196 3193
3197 3194 lines = []
3198 3195 for l in raw_lines:
3199 3196 for pat in strip_from_start:
3200 3197 l = pat.sub('',l)
3201 3198 lines.append(l)
3202 3199
3203 3200 block = "\n".join(lines) + '\n'
3204 3201 #print "block:\n",block
3205 3202 return block
3206 3203
3207 3204 def _execute_block(self, block, par):
3208 3205 """ Execute a block, or store it in a variable, per the user's request.
3209 3206 """
3210 3207 if not par:
3211 3208 b = textwrap.dedent(block)
3212 3209 self.user_ns['pasted_block'] = b
3213 3210 exec b in self.user_ns
3214 3211 else:
3215 3212 self.user_ns[par] = SList(block.splitlines())
3216 3213 print "Block assigned to '%s'" % par
3217 3214
3218 3215 def magic_quickref(self,arg):
3219 3216 """ Show a quick reference sheet """
3220 3217 import IPython.core.usage
3221 3218 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3222 3219
3223 3220 page.page(qr)
3224 3221
3225 3222 def magic_doctest_mode(self,parameter_s=''):
3226 3223 """Toggle doctest mode on and off.
3227 3224
3228 3225 This mode is intended to make IPython behave as much as possible like a
3229 3226 plain Python shell, from the perspective of how its prompts, exceptions
3230 3227 and output look. This makes it easy to copy and paste parts of a
3231 3228 session into doctests. It does so by:
3232 3229
3233 3230 - Changing the prompts to the classic ``>>>`` ones.
3234 3231 - Changing the exception reporting mode to 'Plain'.
3235 3232 - Disabling pretty-printing of output.
3236 3233
3237 3234 Note that IPython also supports the pasting of code snippets that have
3238 3235 leading '>>>' and '...' prompts in them. This means that you can paste
3239 3236 doctests from files or docstrings (even if they have leading
3240 3237 whitespace), and the code will execute correctly. You can then use
3241 3238 '%history -t' to see the translated history; this will give you the
3242 3239 input after removal of all the leading prompts and whitespace, which
3243 3240 can be pasted back into an editor.
3244 3241
3245 3242 With these features, you can switch into this mode easily whenever you
3246 3243 need to do testing and changes to doctests, without having to leave
3247 3244 your existing IPython session.
3248 3245 """
3249 3246
3250 3247 from IPython.utils.ipstruct import Struct
3251 3248
3252 3249 # Shorthands
3253 3250 shell = self.shell
3254 3251 oc = shell.displayhook
3255 3252 meta = shell.meta
3256 3253 disp_formatter = self.shell.display_formatter
3257 3254 ptformatter = disp_formatter.formatters['text/plain']
3258 3255 # dstore is a data store kept in the instance metadata bag to track any
3259 3256 # changes we make, so we can undo them later.
3260 3257 dstore = meta.setdefault('doctest_mode',Struct())
3261 3258 save_dstore = dstore.setdefault
3262 3259
3263 3260 # save a few values we'll need to recover later
3264 3261 mode = save_dstore('mode',False)
3265 3262 save_dstore('rc_pprint',ptformatter.pprint)
3266 3263 save_dstore('xmode',shell.InteractiveTB.mode)
3267 3264 save_dstore('rc_separate_out',shell.separate_out)
3268 3265 save_dstore('rc_separate_out2',shell.separate_out2)
3269 3266 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3270 3267 save_dstore('rc_separate_in',shell.separate_in)
3271 3268 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
3272 3269
3273 3270 if mode == False:
3274 3271 # turn on
3275 3272 oc.prompt1.p_template = '>>> '
3276 3273 oc.prompt2.p_template = '... '
3277 3274 oc.prompt_out.p_template = ''
3278 3275
3279 3276 # Prompt separators like plain python
3280 3277 oc.input_sep = oc.prompt1.sep = ''
3281 3278 oc.output_sep = ''
3282 3279 oc.output_sep2 = ''
3283 3280
3284 3281 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3285 3282 oc.prompt_out.pad_left = False
3286 3283
3287 3284 ptformatter.pprint = False
3288 3285 disp_formatter.plain_text_only = True
3289 3286
3290 3287 shell.magic_xmode('Plain')
3291 3288 else:
3292 3289 # turn off
3293 3290 oc.prompt1.p_template = shell.prompt_in1
3294 3291 oc.prompt2.p_template = shell.prompt_in2
3295 3292 oc.prompt_out.p_template = shell.prompt_out
3296 3293
3297 3294 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3298 3295
3299 3296 oc.output_sep = dstore.rc_separate_out
3300 3297 oc.output_sep2 = dstore.rc_separate_out2
3301 3298
3302 3299 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3303 3300 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3304 3301
3305 3302 ptformatter.pprint = dstore.rc_pprint
3306 3303 disp_formatter.plain_text_only = dstore.rc_plain_text_only
3307 3304
3308 3305 shell.magic_xmode(dstore.xmode)
3309 3306
3310 3307 # Store new mode and inform
3311 3308 dstore.mode = bool(1-int(mode))
3312 3309 mode_label = ['OFF','ON'][dstore.mode]
3313 3310 print 'Doctest mode is:', mode_label
3314 3311
3315 3312 def magic_gui(self, parameter_s=''):
3316 3313 """Enable or disable IPython GUI event loop integration.
3317 3314
3318 3315 %gui [GUINAME]
3319 3316
3320 3317 This magic replaces IPython's threaded shells that were activated
3321 3318 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3322 3319 can now be enabled, disabled and swtiched at runtime and keyboard
3323 3320 interrupts should work without any problems. The following toolkits
3324 3321 are supported: wxPython, PyQt4, PyGTK, and Tk::
3325 3322
3326 3323 %gui wx # enable wxPython event loop integration
3327 3324 %gui qt4|qt # enable PyQt4 event loop integration
3328 3325 %gui gtk # enable PyGTK event loop integration
3329 3326 %gui tk # enable Tk event loop integration
3330 3327 %gui # disable all event loop integration
3331 3328
3332 3329 WARNING: after any of these has been called you can simply create
3333 3330 an application object, but DO NOT start the event loop yourself, as
3334 3331 we have already handled that.
3335 3332 """
3336 3333 from IPython.lib.inputhook import enable_gui
3337 3334 opts, arg = self.parse_options(parameter_s, '')
3338 3335 if arg=='': arg = None
3339 3336 return enable_gui(arg)
3340 3337
3341 3338 def magic_load_ext(self, module_str):
3342 3339 """Load an IPython extension by its module name."""
3343 3340 return self.extension_manager.load_extension(module_str)
3344 3341
3345 3342 def magic_unload_ext(self, module_str):
3346 3343 """Unload an IPython extension by its module name."""
3347 3344 self.extension_manager.unload_extension(module_str)
3348 3345
3349 3346 def magic_reload_ext(self, module_str):
3350 3347 """Reload an IPython extension by its module name."""
3351 3348 self.extension_manager.reload_extension(module_str)
3352 3349
3353 3350 @testdec.skip_doctest
3354 3351 def magic_install_profiles(self, s):
3355 3352 """Install the default IPython profiles into the .ipython dir.
3356 3353
3357 3354 If the default profiles have already been installed, they will not
3358 3355 be overwritten. You can force overwriting them by using the ``-o``
3359 3356 option::
3360 3357
3361 3358 In [1]: %install_profiles -o
3362 3359 """
3363 3360 if '-o' in s:
3364 3361 overwrite = True
3365 3362 else:
3366 3363 overwrite = False
3367 3364 from IPython.config import profile
3368 3365 profile_dir = os.path.split(profile.__file__)[0]
3369 3366 ipython_dir = self.ipython_dir
3370 3367 files = os.listdir(profile_dir)
3371 3368
3372 3369 to_install = []
3373 3370 for f in files:
3374 3371 if f.startswith('ipython_config'):
3375 3372 src = os.path.join(profile_dir, f)
3376 3373 dst = os.path.join(ipython_dir, f)
3377 3374 if (not os.path.isfile(dst)) or overwrite:
3378 3375 to_install.append((f, src, dst))
3379 3376 if len(to_install)>0:
3380 3377 print "Installing profiles to: ", ipython_dir
3381 3378 for (f, src, dst) in to_install:
3382 3379 shutil.copy(src, dst)
3383 3380 print " %s" % f
3384 3381
3385 3382 def magic_install_default_config(self, s):
3386 3383 """Install IPython's default config file into the .ipython dir.
3387 3384
3388 3385 If the default config file (:file:`ipython_config.py`) is already
3389 3386 installed, it will not be overwritten. You can force overwriting
3390 3387 by using the ``-o`` option::
3391 3388
3392 3389 In [1]: %install_default_config
3393 3390 """
3394 3391 if '-o' in s:
3395 3392 overwrite = True
3396 3393 else:
3397 3394 overwrite = False
3398 3395 from IPython.config import default
3399 3396 config_dir = os.path.split(default.__file__)[0]
3400 3397 ipython_dir = self.ipython_dir
3401 3398 default_config_file_name = 'ipython_config.py'
3402 3399 src = os.path.join(config_dir, default_config_file_name)
3403 3400 dst = os.path.join(ipython_dir, default_config_file_name)
3404 3401 if (not os.path.isfile(dst)) or overwrite:
3405 3402 shutil.copy(src, dst)
3406 3403 print "Installing default config file: %s" % dst
3407 3404
3408 3405 # Pylab support: simple wrappers that activate pylab, load gui input
3409 3406 # handling and modify slightly %run
3410 3407
3411 3408 @testdec.skip_doctest
3412 3409 def _pylab_magic_run(self, parameter_s=''):
3413 3410 Magic.magic_run(self, parameter_s,
3414 3411 runner=mpl_runner(self.shell.safe_execfile))
3415 3412
3416 3413 _pylab_magic_run.__doc__ = magic_run.__doc__
3417 3414
3418 3415 @testdec.skip_doctest
3419 3416 def magic_pylab(self, s):
3420 3417 """Load numpy and matplotlib to work interactively.
3421 3418
3422 3419 %pylab [GUINAME]
3423 3420
3424 3421 This function lets you activate pylab (matplotlib, numpy and
3425 3422 interactive support) at any point during an IPython session.
3426 3423
3427 3424 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3428 3425 pylab and mlab, as well as all names from numpy and pylab.
3429 3426
3430 3427 Parameters
3431 3428 ----------
3432 3429 guiname : optional
3433 3430 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or
3434 3431 'tk'). If given, the corresponding Matplotlib backend is used,
3435 3432 otherwise matplotlib's default (which you can override in your
3436 3433 matplotlib config file) is used.
3437 3434
3438 3435 Examples
3439 3436 --------
3440 3437 In this case, where the MPL default is TkAgg:
3441 3438 In [2]: %pylab
3442 3439
3443 3440 Welcome to pylab, a matplotlib-based Python environment.
3444 3441 Backend in use: TkAgg
3445 3442 For more information, type 'help(pylab)'.
3446 3443
3447 3444 But you can explicitly request a different backend:
3448 3445 In [3]: %pylab qt
3449 3446
3450 3447 Welcome to pylab, a matplotlib-based Python environment.
3451 3448 Backend in use: Qt4Agg
3452 3449 For more information, type 'help(pylab)'.
3453 3450 """
3454 3451 self.shell.enable_pylab(s)
3455 3452
3456 3453 def magic_tb(self, s):
3457 3454 """Print the last traceback with the currently active exception mode.
3458 3455
3459 3456 See %xmode for changing exception reporting modes."""
3460 3457 self.shell.showtraceback()
3461 3458
3462 3459 @testdec.skip_doctest
3463 3460 def magic_precision(self, s=''):
3464 3461 """Set floating point precision for pretty printing.
3465 3462
3466 3463 Can set either integer precision or a format string.
3467 3464
3468 3465 If numpy has been imported and precision is an int,
3469 3466 numpy display precision will also be set, via ``numpy.set_printoptions``.
3470 3467
3471 3468 If no argument is given, defaults will be restored.
3472 3469
3473 3470 Examples
3474 3471 --------
3475 3472 ::
3476 3473
3477 3474 In [1]: from math import pi
3478 3475
3479 3476 In [2]: %precision 3
3480 3477 Out[2]: '%.3f'
3481 3478
3482 3479 In [3]: pi
3483 3480 Out[3]: 3.142
3484 3481
3485 3482 In [4]: %precision %i
3486 3483 Out[4]: '%i'
3487 3484
3488 3485 In [5]: pi
3489 3486 Out[5]: 3
3490 3487
3491 3488 In [6]: %precision %e
3492 3489 Out[6]: '%e'
3493 3490
3494 3491 In [7]: pi**10
3495 3492 Out[7]: 9.364805e+04
3496 3493
3497 3494 In [8]: %precision
3498 3495 Out[8]: '%r'
3499 3496
3500 3497 In [9]: pi**10
3501 3498 Out[9]: 93648.047476082982
3502 3499
3503 3500 """
3504 3501
3505 3502 ptformatter = self.shell.display_formatter.formatters['text/plain']
3506 3503 ptformatter.float_precision = s
3507 3504 return ptformatter.float_format
3508 3505
3509 3506 # end Magic
General Comments 0
You need to be logged in to leave comments. Login now