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