##// END OF EJS Templates
Merging upstream from trunk.
Brian Granger -
r2289:e432bee0 merge
parent child Browse files
Show More
@@ -0,0 +1,222 b''
1 """Use pretty.py for configurable pretty-printing.
2
3 To enable this extension in your configuration
4 file, add the following to :file:`ipython_config.py`::
5
6 c.Global.extensions = ['IPython.extensions.pretty']
7 def dict_pprinter(obj, p, cycle):
8 return p.text("<dict>")
9 c.PrettyResultDisplay.verbose = True
10 c.PrettyResultDisplay.defaults_for_type = [
11 (dict, dict_pprinter)
12 ]
13 c.PrettyResultDisplay.defaults_for_type_by_name = [
14 ('numpy', 'dtype', 'IPython.extensions.pretty.dtype_pprinter')
15 ]
16
17 This extension can also be loaded by using the ``%load_ext`` magic::
18
19 %load_ext IPython.extensions.pretty
20
21 If this extension is enabled, you can always add additional pretty printers
22 by doing::
23
24 ip = get_ipython()
25 prd = ip.get_component('pretty_result_display')
26 import numpy
27 from IPython.extensions.pretty import dtype_pprinter
28 prd.for_type(numpy.dtype, dtype_pprinter)
29
30 # If you don't want to have numpy imported until it needs to be:
31 prd.for_type_by_name('numpy', 'dtype', dtype_pprinter)
32 """
33
34 #-----------------------------------------------------------------------------
35 # Imports
36 #-----------------------------------------------------------------------------
37
38 from IPython.core.error import TryNext
39 from IPython.external import pretty
40 from IPython.core.component import Component
41 from IPython.utils.traitlets import Bool, List
42 from IPython.utils.genutils import Term
43 from IPython.utils.autoattr import auto_attr
44 from IPython.utils.importstring import import_item
45
46 #-----------------------------------------------------------------------------
47 # Code
48 #-----------------------------------------------------------------------------
49
50
51 _loaded = False
52
53
54 class PrettyResultDisplay(Component):
55 """A component for pretty printing on steroids."""
56
57 verbose = Bool(False, config=True)
58
59 # A list of (type, func_name), like
60 # [(dict, 'my_dict_printer')]
61 # The final argument can also be a callable
62 defaults_for_type = List(default_value=[], config=True)
63
64 # A list of (module_name, type_name, func_name), like
65 # [('numpy', 'dtype', 'IPython.extensions.pretty.dtype_pprinter')]
66 # The final argument can also be a callable
67 defaults_for_type_by_name = List(default_value=[], config=True)
68
69 def __init__(self, parent, name=None, config=None):
70 super(PrettyResultDisplay, self).__init__(parent, name=name, config=config)
71 self._setup_defaults()
72
73 def _setup_defaults(self):
74 """Initialize the default pretty printers."""
75 for typ, func_name in self.defaults_for_type:
76 func = self._resolve_func_name(func_name)
77 self.for_type(typ, func)
78 for type_module, type_name, func_name in self.defaults_for_type_by_name:
79 func = self._resolve_func_name(func_name)
80 self.for_type_by_name(type_module, type_name, func)
81
82 def _resolve_func_name(self, func_name):
83 if callable(func_name):
84 return func_name
85 elif isinstance(func_name, basestring):
86 return import_item(func_name)
87 else:
88 raise TypeError('func_name must be a str or callable, got: %r' % func_name)
89
90 # Access other components like this rather than by a regular attribute.
91 # This won't lookup the InteractiveShell object until it is used and
92 # then it is cached. This is both efficient and couples this class
93 # more loosely to InteractiveShell.
94 @auto_attr
95 def shell(self):
96 return Component.get_instances(
97 root=self.root,
98 klass='IPython.core.iplib.InteractiveShell')[0]
99
100 def __call__(self, otherself, arg):
101 """Uber-pretty-printing display hook.
102
103 Called for displaying the result to the user.
104 """
105
106 if self.shell.pprint:
107 out = pretty.pretty(arg, verbose=self.verbose)
108 if '\n' in out:
109 # So that multi-line strings line up with the left column of
110 # the screen, instead of having the output prompt mess up
111 # their first line.
112 Term.cout.write('\n')
113 print >>Term.cout, out
114 else:
115 raise TryNext
116
117 def for_type(self, typ, func):
118 """Add a pretty printer for a type."""
119 return pretty.for_type(typ, func)
120
121 def for_type_by_name(self, type_module, type_name, func):
122 """Add a pretty printer for a type by its name and module name."""
123 return pretty.for_type_by_name(type_module, type_name, func)
124
125
126 #-----------------------------------------------------------------------------
127 # Initialization code for the extension
128 #-----------------------------------------------------------------------------
129
130
131 def load_ipython_extension(ip):
132 """Load the extension in IPython as a hook."""
133 global _loaded
134 if not _loaded:
135 prd = PrettyResultDisplay(ip, name='pretty_result_display')
136 ip.set_hook('result_display', prd, priority=99)
137 _loaded = True
138
139 def unload_ipython_extension(ip):
140 """Unload the extension."""
141 # The hook system does not have a way to remove a hook so this is a pass
142 pass
143
144
145 #-----------------------------------------------------------------------------
146 # Example pretty printers
147 #-----------------------------------------------------------------------------
148
149
150 def dtype_pprinter(obj, p, cycle):
151 """ A pretty-printer for numpy dtype objects.
152 """
153 if cycle:
154 return p.text('dtype(...)')
155 if hasattr(obj, 'fields'):
156 if obj.fields is None:
157 p.text(repr(obj))
158 else:
159 p.begin_group(7, 'dtype([')
160 for i, field in enumerate(obj.descr):
161 if i > 0:
162 p.text(',')
163 p.breakable()
164 p.pretty(field)
165 p.end_group(7, '])')
166
167
168 #-----------------------------------------------------------------------------
169 # Tests
170 #-----------------------------------------------------------------------------
171
172
173 def test_pretty():
174 """
175 In [1]: from IPython.extensions import ipy_pretty
176
177 In [2]: ipy_pretty.activate()
178
179 In [3]: class A(object):
180 ...: def __repr__(self):
181 ...: return 'A()'
182 ...:
183 ...:
184
185 In [4]: a = A()
186
187 In [5]: a
188 Out[5]: A()
189
190 In [6]: def a_pretty_printer(obj, p, cycle):
191 ...: p.text('<A>')
192 ...:
193 ...:
194
195 In [7]: ipy_pretty.for_type(A, a_pretty_printer)
196
197 In [8]: a
198 Out[8]: <A>
199
200 In [9]: class B(object):
201 ...: def __repr__(self):
202 ...: return 'B()'
203 ...:
204 ...:
205
206 In [10]: B.__module__, B.__name__
207 Out[10]: ('__main__', 'B')
208
209 In [11]: def b_pretty_printer(obj, p, cycle):
210 ....: p.text('<B>')
211 ....:
212 ....:
213
214 In [12]: ipy_pretty.for_type_by_name('__main__', 'B', b_pretty_printer)
215
216 In [13]: b = B()
217
218 In [14]: b
219 Out[14]: <B>
220 """
221 assert False, "This should only be doctested, not run."
222
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
@@ -0,0 +1,56 b''
1 #!/usr/bin/env python
2 # encoding: utf-8
3 """
4 Simple tests for :mod:`IPython.extensions.pretty`.
5 """
6
7 #-----------------------------------------------------------------------------
8 # Copyright (C) 2008-2009 The IPython Development Team
9 #
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
12 #-----------------------------------------------------------------------------
13
14 #-----------------------------------------------------------------------------
15 # Imports
16 #-----------------------------------------------------------------------------
17
18 import sys
19 from unittest import TestCase
20
21 from IPython.core.component import Component, masquerade_as
22 from IPython.core.iplib import InteractiveShell
23 from IPython.extensions import pretty as pretty_ext
24 from IPython.external import pretty
25
26 from IPython.utils.traitlets import Bool
27
28 #-----------------------------------------------------------------------------
29 # Tests
30 #-----------------------------------------------------------------------------
31
32
33 class InteractiveShellStub(Component):
34 pprint = Bool(True)
35
36 class A(object):
37 pass
38
39 def a_pprinter(o, p, c):
40 return p.text("<A>")
41
42 class TestPrettyResultDisplay(TestCase):
43
44 def setUp(self):
45 self.ip = InteractiveShellStub(None)
46 # This allows our stub to be retrieved instead of the real InteractiveShell
47 masquerade_as(self.ip, InteractiveShell)
48 self.prd = pretty_ext.PrettyResultDisplay(self.ip, name='pretty_result_display')
49
50 def test_for_type(self):
51 self.prd.for_type(A, a_pprinter)
52 a = A()
53 result = pretty.pretty(a)
54 self.assertEquals(result, "<A>")
55
56
@@ -1,116 +1,117 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 A context manager for managing things injected into :mod:`__builtin__`.
4 A context manager for managing things injected into :mod:`__builtin__`.
5
5
6 Authors:
6 Authors:
7
7
8 * Brian Granger
8 * Brian Granger
9 """
9 """
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Copyright (C) 2008-2009 The IPython Development Team
12 # Copyright (C) 2008-2009 The IPython Development Team
13 #
13 #
14 # Distributed under the terms of the BSD License. The full license is in
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
15 # the file COPYING, distributed as part of this software.
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19 # Imports
19 # Imports
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21
21
22 import __builtin__
22 import __builtin__
23
23
24 from IPython.core.component import Component
24 from IPython.core.component import Component
25 from IPython.core.quitter import Quitter
25 from IPython.core.quitter import Quitter
26
26
27 from IPython.utils.autoattr import auto_attr
27 from IPython.utils.autoattr import auto_attr
28
28
29 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
30 # Classes and functions
30 # Classes and functions
31 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
32
32
33
33
34 class BuiltinUndefined(object): pass
34 class BuiltinUndefined(object): pass
35 BuiltinUndefined = BuiltinUndefined()
35 BuiltinUndefined = BuiltinUndefined()
36
36
37
37
38 class BuiltinTrap(Component):
38 class BuiltinTrap(Component):
39
39
40 def __init__(self, parent):
40 def __init__(self, parent):
41 super(BuiltinTrap, self).__init__(parent, None, None)
41 super(BuiltinTrap, self).__init__(parent, None, None)
42 self._orig_builtins = {}
42 self._orig_builtins = {}
43 # We define this to track if a single BuiltinTrap is nested.
43 # We define this to track if a single BuiltinTrap is nested.
44 # Only turn off the trap when the outermost call to __exit__ is made.
44 # Only turn off the trap when the outermost call to __exit__ is made.
45 self._nested_level = 0
45 self._nested_level = 0
46
46
47 @auto_attr
47 @auto_attr
48 def shell(self):
48 def shell(self):
49 return Component.get_instances(
49 return Component.get_instances(
50 root=self.root,
50 root=self.root,
51 klass='IPython.core.iplib.InteractiveShell')[0]
51 klass='IPython.core.iplib.InteractiveShell')[0]
52
52
53 def __enter__(self):
53 def __enter__(self):
54 if self._nested_level == 0:
54 if self._nested_level == 0:
55 self.set()
55 self.set()
56 self._nested_level += 1
56 self._nested_level += 1
57 # I return self, so callers can use add_builtin in a with clause.
57 # I return self, so callers can use add_builtin in a with clause.
58 return self
58 return self
59
59
60 def __exit__(self, type, value, traceback):
60 def __exit__(self, type, value, traceback):
61 if self._nested_level == 1:
61 if self._nested_level == 1:
62 self.unset()
62 self.unset()
63 self._nested_level -= 1
63 self._nested_level -= 1
64 return True
64 # Returning False will cause exceptions to propagate
65 return False
65
66
66 def add_builtin(self, key, value):
67 def add_builtin(self, key, value):
67 """Add a builtin and save the original."""
68 """Add a builtin and save the original."""
68 orig = __builtin__.__dict__.get(key, BuiltinUndefined)
69 orig = __builtin__.__dict__.get(key, BuiltinUndefined)
69 self._orig_builtins[key] = orig
70 self._orig_builtins[key] = orig
70 __builtin__.__dict__[key] = value
71 __builtin__.__dict__[key] = value
71
72
72 def remove_builtin(self, key):
73 def remove_builtin(self, key):
73 """Remove an added builtin and re-set the original."""
74 """Remove an added builtin and re-set the original."""
74 try:
75 try:
75 orig = self._orig_builtins.pop(key)
76 orig = self._orig_builtins.pop(key)
76 except KeyError:
77 except KeyError:
77 pass
78 pass
78 else:
79 else:
79 if orig is BuiltinUndefined:
80 if orig is BuiltinUndefined:
80 del __builtin__.__dict__[key]
81 del __builtin__.__dict__[key]
81 else:
82 else:
82 __builtin__.__dict__[key] = orig
83 __builtin__.__dict__[key] = orig
83
84
84 def set(self):
85 def set(self):
85 """Store ipython references in the __builtin__ namespace."""
86 """Store ipython references in the __builtin__ namespace."""
86 self.add_builtin('exit', Quitter(self.shell, 'exit'))
87 self.add_builtin('exit', Quitter(self.shell, 'exit'))
87 self.add_builtin('quit', Quitter(self.shell, 'quit'))
88 self.add_builtin('quit', Quitter(self.shell, 'quit'))
88
89
89 # Recursive reload function
90 # Recursive reload function
90 try:
91 try:
91 from IPython.lib import deepreload
92 from IPython.lib import deepreload
92 if self.shell.deep_reload:
93 if self.shell.deep_reload:
93 self.add_builtin('reload', deepreload.reload)
94 self.add_builtin('reload', deepreload.reload)
94 else:
95 else:
95 self.add_builtin('dreload', deepreload.reload)
96 self.add_builtin('dreload', deepreload.reload)
96 del deepreload
97 del deepreload
97 except ImportError:
98 except ImportError:
98 pass
99 pass
99
100
100 # Keep in the builtins a flag for when IPython is active. We set it
101 # Keep in the builtins a flag for when IPython is active. We set it
101 # with setdefault so that multiple nested IPythons don't clobber one
102 # with setdefault so that multiple nested IPythons don't clobber one
102 # another. Each will increase its value by one upon being activated,
103 # another. Each will increase its value by one upon being activated,
103 # which also gives us a way to determine the nesting level.
104 # which also gives us a way to determine the nesting level.
104 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
105 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
105
106
106 def unset(self):
107 def unset(self):
107 """Remove any builtins which might have been added by add_builtins, or
108 """Remove any builtins which might have been added by add_builtins, or
108 restore overwritten ones to their previous values."""
109 restore overwritten ones to their previous values."""
109 for key in self._orig_builtins.keys():
110 for key in self._orig_builtins.keys():
110 self.remove_builtin(key)
111 self.remove_builtin(key)
111 self._orig_builtins.clear()
112 self._orig_builtins.clear()
112 self._builtins_added = False
113 self._builtins_added = False
113 try:
114 try:
114 del __builtin__.__dict__['__IPYTHON__active']
115 del __builtin__.__dict__['__IPYTHON__active']
115 except KeyError:
116 except KeyError:
116 pass
117 pass
@@ -1,76 +1,77 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 A context manager for handling sys.displayhook.
4 A context manager for handling sys.displayhook.
5
5
6 Authors:
6 Authors:
7
7
8 * Robert Kern
8 * Robert Kern
9 * Brian Granger
9 * Brian Granger
10 """
10 """
11
11
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Copyright (C) 2008-2009 The IPython Development Team
13 # Copyright (C) 2008-2009 The IPython Development Team
14 #
14 #
15 # Distributed under the terms of the BSD License. The full license is in
15 # Distributed under the terms of the BSD License. The full license is in
16 # the file COPYING, distributed as part of this software.
16 # the file COPYING, distributed as part of this software.
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20 # Imports
20 # Imports
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22
22
23 import sys
23 import sys
24
24
25 from IPython.core.component import Component
25 from IPython.core.component import Component
26
26
27 from IPython.utils.autoattr import auto_attr
27 from IPython.utils.autoattr import auto_attr
28
28
29 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
30 # Classes and functions
30 # Classes and functions
31 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
32
32
33
33
34 class DisplayTrap(Component):
34 class DisplayTrap(Component):
35 """Object to manage sys.displayhook.
35 """Object to manage sys.displayhook.
36
36
37 This came from IPython.core.kernel.display_hook, but is simplified
37 This came from IPython.core.kernel.display_hook, but is simplified
38 (no callbacks or formatters) until more of the core is refactored.
38 (no callbacks or formatters) until more of the core is refactored.
39 """
39 """
40
40
41 def __init__(self, parent, hook):
41 def __init__(self, parent, hook):
42 super(DisplayTrap, self).__init__(parent, None, None)
42 super(DisplayTrap, self).__init__(parent, None, None)
43 self.hook = hook
43 self.hook = hook
44 self.old_hook = None
44 self.old_hook = None
45 # We define this to track if a single BuiltinTrap is nested.
45 # We define this to track if a single BuiltinTrap is nested.
46 # Only turn off the trap when the outermost call to __exit__ is made.
46 # Only turn off the trap when the outermost call to __exit__ is made.
47 self._nested_level = 0
47 self._nested_level = 0
48
48
49 # @auto_attr
49 # @auto_attr
50 # def shell(self):
50 # def shell(self):
51 # return Component.get_instances(
51 # return Component.get_instances(
52 # root=self.root,
52 # root=self.root,
53 # klass='IPython.core.iplib.InteractiveShell')[0]
53 # klass='IPython.core.iplib.InteractiveShell')[0]
54
54
55 def __enter__(self):
55 def __enter__(self):
56 if self._nested_level == 0:
56 if self._nested_level == 0:
57 self.set()
57 self.set()
58 self._nested_level += 1
58 self._nested_level += 1
59 return self
59 return self
60
60
61 def __exit__(self, type, value, traceback):
61 def __exit__(self, type, value, traceback):
62 if self._nested_level == 1:
62 if self._nested_level == 1:
63 self.unset()
63 self.unset()
64 self._nested_level -= 1
64 self._nested_level -= 1
65 return True
65 # Returning False will cause exceptions to propagate
66 return False
66
67
67 def set(self):
68 def set(self):
68 """Set the hook."""
69 """Set the hook."""
69 if sys.displayhook is not self.hook:
70 if sys.displayhook is not self.hook:
70 self.old_hook = sys.displayhook
71 self.old_hook = sys.displayhook
71 sys.displayhook = self.hook
72 sys.displayhook = self.hook
72
73
73 def unset(self):
74 def unset(self):
74 """Unset the hook."""
75 """Unset the hook."""
75 sys.displayhook = self.old_hook
76 sys.displayhook = self.old_hook
76
77
@@ -1,2438 +1,2470 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Main IPython Component
3 Main IPython Component
4 """
4 """
5
5
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
8 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
8 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
9 # Copyright (C) 2008-2009 The IPython Development Team
9 # Copyright (C) 2008-2009 The IPython Development Team
10 #
10 #
11 # Distributed under the terms of the BSD License. The full license is in
11 # Distributed under the terms of the BSD License. The full license is in
12 # the file COPYING, distributed as part of this software.
12 # the file COPYING, distributed as part of this software.
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 # Imports
16 # Imports
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 from __future__ import with_statement
19 from __future__ import with_statement
20
20
21 import __builtin__
21 import __builtin__
22 import StringIO
22 import StringIO
23 import bdb
23 import bdb
24 import codeop
24 import codeop
25 import exceptions
25 import exceptions
26 import new
26 import new
27 import os
27 import os
28 import re
28 import re
29 import string
29 import string
30 import sys
30 import sys
31 import tempfile
31 import tempfile
32 from contextlib import nested
32 from contextlib import nested
33
33
34 from IPython.core import ultratb
34 from IPython.core import ultratb
35 from IPython.core import debugger, oinspect
35 from IPython.core import debugger, oinspect
36 from IPython.core import shadowns
36 from IPython.core import shadowns
37 from IPython.core import history as ipcorehist
37 from IPython.core import history as ipcorehist
38 from IPython.core import prefilter
38 from IPython.core import prefilter
39 from IPython.core.alias import AliasManager
39 from IPython.core.alias import AliasManager
40 from IPython.core.builtin_trap import BuiltinTrap
40 from IPython.core.builtin_trap import BuiltinTrap
41 from IPython.core.display_trap import DisplayTrap
41 from IPython.core.display_trap import DisplayTrap
42 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
42 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
43 from IPython.core.logger import Logger
43 from IPython.core.logger import Logger
44 from IPython.core.magic import Magic
44 from IPython.core.magic import Magic
45 from IPython.core.prompts import CachedOutput
45 from IPython.core.prompts import CachedOutput
46 from IPython.core.prefilter import PrefilterManager
46 from IPython.core.prefilter import PrefilterManager
47 from IPython.core.component import Component
47 from IPython.core.component import Component
48 from IPython.core.usage import interactive_usage, default_banner
48 from IPython.core.usage import interactive_usage, default_banner
49 from IPython.core.error import TryNext, UsageError
49 from IPython.core.error import TryNext, UsageError
50
50
51 from IPython.utils import pickleshare
51 from IPython.utils import pickleshare
52 from IPython.external.Itpl import ItplNS
52 from IPython.external.Itpl import ItplNS
53 from IPython.lib.backgroundjobs import BackgroundJobManager
53 from IPython.lib.backgroundjobs import BackgroundJobManager
54 from IPython.utils.ipstruct import Struct
54 from IPython.utils.ipstruct import Struct
55 from IPython.utils import PyColorize
55 from IPython.utils import PyColorize
56 from IPython.utils.genutils import *
56 from IPython.utils.genutils import *
57 from IPython.utils.genutils import get_ipython_dir
57 from IPython.utils.genutils import get_ipython_dir
58 from IPython.utils.platutils import toggle_set_term_title, set_term_title
58 from IPython.utils.platutils import toggle_set_term_title, set_term_title
59 from IPython.utils.strdispatch import StrDispatch
59 from IPython.utils.strdispatch import StrDispatch
60 from IPython.utils.syspathcontext import prepended_to_syspath
60 from IPython.utils.syspathcontext import prepended_to_syspath
61
61
62 # from IPython.utils import growl
62 # from IPython.utils import growl
63 # growl.start("IPython")
63 # growl.start("IPython")
64
64
65 from IPython.utils.traitlets import (
65 from IPython.utils.traitlets import (
66 Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode
66 Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode
67 )
67 )
68
68
69 #-----------------------------------------------------------------------------
69 #-----------------------------------------------------------------------------
70 # Globals
70 # Globals
71 #-----------------------------------------------------------------------------
71 #-----------------------------------------------------------------------------
72
72
73
73
74 # store the builtin raw_input globally, and use this always, in case user code
74 # store the builtin raw_input globally, and use this always, in case user code
75 # overwrites it (like wx.py.PyShell does)
75 # overwrites it (like wx.py.PyShell does)
76 raw_input_original = raw_input
76 raw_input_original = raw_input
77
77
78 # compiled regexps for autoindent management
78 # compiled regexps for autoindent management
79 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
79 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
80
80
81
81
82 #-----------------------------------------------------------------------------
82 #-----------------------------------------------------------------------------
83 # Utilities
83 # Utilities
84 #-----------------------------------------------------------------------------
84 #-----------------------------------------------------------------------------
85
85
86
86
87 ini_spaces_re = re.compile(r'^(\s+)')
87 ini_spaces_re = re.compile(r'^(\s+)')
88
88
89
89
90 def num_ini_spaces(strng):
90 def num_ini_spaces(strng):
91 """Return the number of initial spaces in a string"""
91 """Return the number of initial spaces in a string"""
92
92
93 ini_spaces = ini_spaces_re.match(strng)
93 ini_spaces = ini_spaces_re.match(strng)
94 if ini_spaces:
94 if ini_spaces:
95 return ini_spaces.end()
95 return ini_spaces.end()
96 else:
96 else:
97 return 0
97 return 0
98
98
99
99
100 def softspace(file, newvalue):
100 def softspace(file, newvalue):
101 """Copied from code.py, to remove the dependency"""
101 """Copied from code.py, to remove the dependency"""
102
102
103 oldvalue = 0
103 oldvalue = 0
104 try:
104 try:
105 oldvalue = file.softspace
105 oldvalue = file.softspace
106 except AttributeError:
106 except AttributeError:
107 pass
107 pass
108 try:
108 try:
109 file.softspace = newvalue
109 file.softspace = newvalue
110 except (AttributeError, TypeError):
110 except (AttributeError, TypeError):
111 # "attribute-less object" or "read-only attributes"
111 # "attribute-less object" or "read-only attributes"
112 pass
112 pass
113 return oldvalue
113 return oldvalue
114
114
115
115
116 class SpaceInInput(exceptions.Exception): pass
116 class SpaceInInput(exceptions.Exception): pass
117
117
118 class Bunch: pass
118 class Bunch: pass
119
119
120 class InputList(list):
120 class InputList(list):
121 """Class to store user input.
121 """Class to store user input.
122
122
123 It's basically a list, but slices return a string instead of a list, thus
123 It's basically a list, but slices return a string instead of a list, thus
124 allowing things like (assuming 'In' is an instance):
124 allowing things like (assuming 'In' is an instance):
125
125
126 exec In[4:7]
126 exec In[4:7]
127
127
128 or
128 or
129
129
130 exec In[5:9] + In[14] + In[21:25]"""
130 exec In[5:9] + In[14] + In[21:25]"""
131
131
132 def __getslice__(self,i,j):
132 def __getslice__(self,i,j):
133 return ''.join(list.__getslice__(self,i,j))
133 return ''.join(list.__getslice__(self,i,j))
134
134
135
135
136 class SyntaxTB(ultratb.ListTB):
136 class SyntaxTB(ultratb.ListTB):
137 """Extension which holds some state: the last exception value"""
137 """Extension which holds some state: the last exception value"""
138
138
139 def __init__(self,color_scheme = 'NoColor'):
139 def __init__(self,color_scheme = 'NoColor'):
140 ultratb.ListTB.__init__(self,color_scheme)
140 ultratb.ListTB.__init__(self,color_scheme)
141 self.last_syntax_error = None
141 self.last_syntax_error = None
142
142
143 def __call__(self, etype, value, elist):
143 def __call__(self, etype, value, elist):
144 self.last_syntax_error = value
144 self.last_syntax_error = value
145 ultratb.ListTB.__call__(self,etype,value,elist)
145 ultratb.ListTB.__call__(self,etype,value,elist)
146
146
147 def clear_err_state(self):
147 def clear_err_state(self):
148 """Return the current error state and clear it"""
148 """Return the current error state and clear it"""
149 e = self.last_syntax_error
149 e = self.last_syntax_error
150 self.last_syntax_error = None
150 self.last_syntax_error = None
151 return e
151 return e
152
152
153
153
154 def get_default_editor():
154 def get_default_editor():
155 try:
155 try:
156 ed = os.environ['EDITOR']
156 ed = os.environ['EDITOR']
157 except KeyError:
157 except KeyError:
158 if os.name == 'posix':
158 if os.name == 'posix':
159 ed = 'vi' # the only one guaranteed to be there!
159 ed = 'vi' # the only one guaranteed to be there!
160 else:
160 else:
161 ed = 'notepad' # same in Windows!
161 ed = 'notepad' # same in Windows!
162 return ed
162 return ed
163
163
164
164
165 class SeparateStr(Str):
165 class SeparateStr(Str):
166 """A Str subclass to validate separate_in, separate_out, etc.
166 """A Str subclass to validate separate_in, separate_out, etc.
167
167
168 This is a Str based traitlet that converts '0'->'' and '\\n'->'\n'.
168 This is a Str based traitlet that converts '0'->'' and '\\n'->'\n'.
169 """
169 """
170
170
171 def validate(self, obj, value):
171 def validate(self, obj, value):
172 if value == '0': value = ''
172 if value == '0': value = ''
173 value = value.replace('\\n','\n')
173 value = value.replace('\\n','\n')
174 return super(SeparateStr, self).validate(obj, value)
174 return super(SeparateStr, self).validate(obj, value)
175
175
176
176
177 #-----------------------------------------------------------------------------
177 #-----------------------------------------------------------------------------
178 # Main IPython class
178 # Main IPython class
179 #-----------------------------------------------------------------------------
179 #-----------------------------------------------------------------------------
180
180
181
181
182 class InteractiveShell(Component, Magic):
182 class InteractiveShell(Component, Magic):
183 """An enhanced, interactive shell for Python."""
183 """An enhanced, interactive shell for Python."""
184
184
185 autocall = Enum((0,1,2), config=True)
185 autocall = Enum((0,1,2), config=True)
186 autoedit_syntax = CBool(False, config=True)
186 autoedit_syntax = CBool(False, config=True)
187 autoindent = CBool(True, config=True)
187 autoindent = CBool(True, config=True)
188 automagic = CBool(True, config=True)
188 automagic = CBool(True, config=True)
189 banner = Str('')
189 banner = Str('')
190 banner1 = Str(default_banner, config=True)
190 banner1 = Str(default_banner, config=True)
191 banner2 = Str('', config=True)
191 banner2 = Str('', config=True)
192 cache_size = Int(1000, config=True)
192 cache_size = Int(1000, config=True)
193 color_info = CBool(True, config=True)
193 color_info = CBool(True, config=True)
194 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
194 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
195 default_value='LightBG', config=True)
195 default_value='LightBG', config=True)
196 confirm_exit = CBool(True, config=True)
196 confirm_exit = CBool(True, config=True)
197 debug = CBool(False, config=True)
197 debug = CBool(False, config=True)
198 deep_reload = CBool(False, config=True)
198 deep_reload = CBool(False, config=True)
199 # This display_banner only controls whether or not self.show_banner()
199 # This display_banner only controls whether or not self.show_banner()
200 # is called when mainloop/interact are called. The default is False
200 # is called when mainloop/interact are called. The default is False
201 # because for the terminal based application, the banner behavior
201 # because for the terminal based application, the banner behavior
202 # is controlled by Global.display_banner, which IPythonApp looks at
202 # is controlled by Global.display_banner, which IPythonApp looks at
203 # to determine if *it* should call show_banner() by hand or not.
203 # to determine if *it* should call show_banner() by hand or not.
204 display_banner = CBool(False) # This isn't configurable!
204 display_banner = CBool(False) # This isn't configurable!
205 embedded = CBool(False)
205 embedded = CBool(False)
206 embedded_active = CBool(False)
206 embedded_active = CBool(False)
207 editor = Str(get_default_editor(), config=True)
207 editor = Str(get_default_editor(), config=True)
208 filename = Str("<ipython console>")
208 filename = Str("<ipython console>")
209 ipythondir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
209 ipythondir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
210 logstart = CBool(False, config=True)
210 logstart = CBool(False, config=True)
211 logfile = Str('', config=True)
211 logfile = Str('', config=True)
212 logappend = Str('', config=True)
212 logappend = Str('', config=True)
213 object_info_string_level = Enum((0,1,2), default_value=0,
213 object_info_string_level = Enum((0,1,2), default_value=0,
214 config=True)
214 config=True)
215 pager = Str('less', config=True)
215 pager = Str('less', config=True)
216 pdb = CBool(False, config=True)
216 pdb = CBool(False, config=True)
217 pprint = CBool(True, config=True)
217 pprint = CBool(True, config=True)
218 profile = Str('', config=True)
218 profile = Str('', config=True)
219 prompt_in1 = Str('In [\\#]: ', config=True)
219 prompt_in1 = Str('In [\\#]: ', config=True)
220 prompt_in2 = Str(' .\\D.: ', config=True)
220 prompt_in2 = Str(' .\\D.: ', config=True)
221 prompt_out = Str('Out[\\#]: ', config=True)
221 prompt_out = Str('Out[\\#]: ', config=True)
222 prompts_pad_left = CBool(True, config=True)
222 prompts_pad_left = CBool(True, config=True)
223 quiet = CBool(False, config=True)
223 quiet = CBool(False, config=True)
224
224
225 readline_use = CBool(True, config=True)
225 readline_use = CBool(True, config=True)
226 readline_merge_completions = CBool(True, config=True)
226 readline_merge_completions = CBool(True, config=True)
227 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
227 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
228 readline_remove_delims = Str('-/~', config=True)
228 readline_remove_delims = Str('-/~', config=True)
229 readline_parse_and_bind = List([
229 readline_parse_and_bind = List([
230 'tab: complete',
230 'tab: complete',
231 '"\C-l": possible-completions',
231 '"\C-l": possible-completions',
232 'set show-all-if-ambiguous on',
232 'set show-all-if-ambiguous on',
233 '"\C-o": tab-insert',
233 '"\C-o": tab-insert',
234 '"\M-i": " "',
234 '"\M-i": " "',
235 '"\M-o": "\d\d\d\d"',
235 '"\M-o": "\d\d\d\d"',
236 '"\M-I": "\d\d\d\d"',
236 '"\M-I": "\d\d\d\d"',
237 '"\C-r": reverse-search-history',
237 '"\C-r": reverse-search-history',
238 '"\C-s": forward-search-history',
238 '"\C-s": forward-search-history',
239 '"\C-p": history-search-backward',
239 '"\C-p": history-search-backward',
240 '"\C-n": history-search-forward',
240 '"\C-n": history-search-forward',
241 '"\e[A": history-search-backward',
241 '"\e[A": history-search-backward',
242 '"\e[B": history-search-forward',
242 '"\e[B": history-search-forward',
243 '"\C-k": kill-line',
243 '"\C-k": kill-line',
244 '"\C-u": unix-line-discard',
244 '"\C-u": unix-line-discard',
245 ], allow_none=False, config=True)
245 ], allow_none=False, config=True)
246
246
247 screen_length = Int(0, config=True)
247 screen_length = Int(0, config=True)
248
248
249 # Use custom TraitletTypes that convert '0'->'' and '\\n'->'\n'
249 # Use custom TraitletTypes that convert '0'->'' and '\\n'->'\n'
250 separate_in = SeparateStr('\n', config=True)
250 separate_in = SeparateStr('\n', config=True)
251 separate_out = SeparateStr('', config=True)
251 separate_out = SeparateStr('', config=True)
252 separate_out2 = SeparateStr('', config=True)
252 separate_out2 = SeparateStr('', config=True)
253
253
254 system_header = Str('IPython system call: ', config=True)
254 system_header = Str('IPython system call: ', config=True)
255 system_verbose = CBool(False, config=True)
255 system_verbose = CBool(False, config=True)
256 term_title = CBool(False, config=True)
256 term_title = CBool(False, config=True)
257 wildcards_case_sensitive = CBool(True, config=True)
257 wildcards_case_sensitive = CBool(True, config=True)
258 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
258 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
259 default_value='Context', config=True)
259 default_value='Context', config=True)
260
260
261 autoexec = List(allow_none=False)
261 autoexec = List(allow_none=False)
262
262
263 # class attribute to indicate whether the class supports threads or not.
263 # class attribute to indicate whether the class supports threads or not.
264 # Subclasses with thread support should override this as needed.
264 # Subclasses with thread support should override this as needed.
265 isthreaded = False
265 isthreaded = False
266
266
267 def __init__(self, parent=None, config=None, ipythondir=None, usage=None,
267 def __init__(self, parent=None, config=None, ipythondir=None, usage=None,
268 user_ns=None, user_global_ns=None,
268 user_ns=None, user_global_ns=None,
269 banner1=None, banner2=None, display_banner=None,
269 banner1=None, banner2=None, display_banner=None,
270 custom_exceptions=((),None)):
270 custom_exceptions=((),None)):
271
271
272 # This is where traitlets with a config_key argument are updated
272 # This is where traitlets with a config_key argument are updated
273 # from the values on config.
273 # from the values on config.
274 super(InteractiveShell, self).__init__(parent, config=config)
274 super(InteractiveShell, self).__init__(parent, config=config)
275
275
276 # These are relatively independent and stateless
276 # These are relatively independent and stateless
277 self.init_ipythondir(ipythondir)
277 self.init_ipythondir(ipythondir)
278 self.init_instance_attrs()
278 self.init_instance_attrs()
279 self.init_term_title()
279 self.init_term_title()
280 self.init_usage(usage)
280 self.init_usage(usage)
281 self.init_banner(banner1, banner2, display_banner)
281 self.init_banner(banner1, banner2, display_banner)
282
282
283 # Create namespaces (user_ns, user_global_ns, etc.)
283 # Create namespaces (user_ns, user_global_ns, etc.)
284 self.init_create_namespaces(user_ns, user_global_ns)
284 self.init_create_namespaces(user_ns, user_global_ns)
285 # This has to be done after init_create_namespaces because it uses
285 # This has to be done after init_create_namespaces because it uses
286 # something in self.user_ns, but before init_sys_modules, which
286 # something in self.user_ns, but before init_sys_modules, which
287 # is the first thing to modify sys.
287 # is the first thing to modify sys.
288 self.save_sys_module_state()
288 self.save_sys_module_state()
289 self.init_sys_modules()
289 self.init_sys_modules()
290
290
291 self.init_history()
291 self.init_history()
292 self.init_encoding()
292 self.init_encoding()
293 self.init_prefilter()
293 self.init_prefilter()
294
294
295 Magic.__init__(self, self)
295 Magic.__init__(self, self)
296
296
297 self.init_syntax_highlighting()
297 self.init_syntax_highlighting()
298 self.init_hooks()
298 self.init_hooks()
299 self.init_pushd_popd_magic()
299 self.init_pushd_popd_magic()
300 self.init_traceback_handlers(custom_exceptions)
300 self.init_traceback_handlers(custom_exceptions)
301 self.init_user_ns()
301 self.init_user_ns()
302 self.init_logger()
302 self.init_logger()
303 self.init_alias()
303 self.init_alias()
304 self.init_builtins()
304 self.init_builtins()
305
305
306 # pre_config_initialization
306 # pre_config_initialization
307 self.init_shadow_hist()
307 self.init_shadow_hist()
308
308
309 # The next section should contain averything that was in ipmaker.
309 # The next section should contain averything that was in ipmaker.
310 self.init_logstart()
310 self.init_logstart()
311
311
312 # The following was in post_config_initialization
312 # The following was in post_config_initialization
313 self.init_inspector()
313 self.init_inspector()
314 self.init_readline()
314 self.init_readline()
315 self.init_prompts()
315 self.init_prompts()
316 self.init_displayhook()
316 self.init_displayhook()
317 self.init_reload_doctest()
317 self.init_reload_doctest()
318 self.init_magics()
318 self.init_magics()
319 self.init_pdb()
319 self.init_pdb()
320 self.hooks.late_startup_hook()
320 self.hooks.late_startup_hook()
321
321
322 def get_ipython(self):
322 def get_ipython(self):
323 return self
323 return self
324
324
325 #-------------------------------------------------------------------------
325 #-------------------------------------------------------------------------
326 # Traitlet changed handlers
326 # Traitlet changed handlers
327 #-------------------------------------------------------------------------
327 #-------------------------------------------------------------------------
328
328
329 def _banner1_changed(self):
329 def _banner1_changed(self):
330 self.compute_banner()
330 self.compute_banner()
331
331
332 def _banner2_changed(self):
332 def _banner2_changed(self):
333 self.compute_banner()
333 self.compute_banner()
334
334
335 def _ipythondir_changed(self, name, new):
335 def _ipythondir_changed(self, name, new):
336 if not os.path.isdir(new):
336 if not os.path.isdir(new):
337 os.makedirs(new, mode = 0777)
337 os.makedirs(new, mode = 0777)
338 if not os.path.isdir(self.ipython_extension_dir):
338 if not os.path.isdir(self.ipython_extension_dir):
339 os.makedirs(self.ipython_extension_dir, mode = 0777)
339 os.makedirs(self.ipython_extension_dir, mode = 0777)
340
340
341 @property
341 @property
342 def ipython_extension_dir(self):
342 def ipython_extension_dir(self):
343 return os.path.join(self.ipythondir, 'extensions')
343 return os.path.join(self.ipythondir, 'extensions')
344
344
345 @property
345 @property
346 def usable_screen_length(self):
346 def usable_screen_length(self):
347 if self.screen_length == 0:
347 if self.screen_length == 0:
348 return 0
348 return 0
349 else:
349 else:
350 num_lines_bot = self.separate_in.count('\n')+1
350 num_lines_bot = self.separate_in.count('\n')+1
351 return self.screen_length - num_lines_bot
351 return self.screen_length - num_lines_bot
352
352
353 def _term_title_changed(self, name, new_value):
353 def _term_title_changed(self, name, new_value):
354 self.init_term_title()
354 self.init_term_title()
355
355
356 def set_autoindent(self,value=None):
356 def set_autoindent(self,value=None):
357 """Set the autoindent flag, checking for readline support.
357 """Set the autoindent flag, checking for readline support.
358
358
359 If called with no arguments, it acts as a toggle."""
359 If called with no arguments, it acts as a toggle."""
360
360
361 if not self.has_readline:
361 if not self.has_readline:
362 if os.name == 'posix':
362 if os.name == 'posix':
363 warn("The auto-indent feature requires the readline library")
363 warn("The auto-indent feature requires the readline library")
364 self.autoindent = 0
364 self.autoindent = 0
365 return
365 return
366 if value is None:
366 if value is None:
367 self.autoindent = not self.autoindent
367 self.autoindent = not self.autoindent
368 else:
368 else:
369 self.autoindent = value
369 self.autoindent = value
370
370
371 #-------------------------------------------------------------------------
371 #-------------------------------------------------------------------------
372 # init_* methods called by __init__
372 # init_* methods called by __init__
373 #-------------------------------------------------------------------------
373 #-------------------------------------------------------------------------
374
374
375 def init_ipythondir(self, ipythondir):
375 def init_ipythondir(self, ipythondir):
376 if ipythondir is not None:
376 if ipythondir is not None:
377 self.ipythondir = ipythondir
377 self.ipythondir = ipythondir
378 self.config.Global.ipythondir = self.ipythondir
378 self.config.Global.ipythondir = self.ipythondir
379 return
379 return
380
380
381 if hasattr(self.config.Global, 'ipythondir'):
381 if hasattr(self.config.Global, 'ipythondir'):
382 self.ipythondir = self.config.Global.ipythondir
382 self.ipythondir = self.config.Global.ipythondir
383 else:
383 else:
384 self.ipythondir = get_ipython_dir()
384 self.ipythondir = get_ipython_dir()
385
385
386 # All children can just read this
386 # All children can just read this
387 self.config.Global.ipythondir = self.ipythondir
387 self.config.Global.ipythondir = self.ipythondir
388
388
389 def init_instance_attrs(self):
389 def init_instance_attrs(self):
390 self.jobs = BackgroundJobManager()
390 self.jobs = BackgroundJobManager()
391 self.more = False
391 self.more = False
392
392
393 # command compiler
393 # command compiler
394 self.compile = codeop.CommandCompiler()
394 self.compile = codeop.CommandCompiler()
395
395
396 # User input buffer
396 # User input buffer
397 self.buffer = []
397 self.buffer = []
398
398
399 # Make an empty namespace, which extension writers can rely on both
399 # Make an empty namespace, which extension writers can rely on both
400 # existing and NEVER being used by ipython itself. This gives them a
400 # existing and NEVER being used by ipython itself. This gives them a
401 # convenient location for storing additional information and state
401 # convenient location for storing additional information and state
402 # their extensions may require, without fear of collisions with other
402 # their extensions may require, without fear of collisions with other
403 # ipython names that may develop later.
403 # ipython names that may develop later.
404 self.meta = Struct()
404 self.meta = Struct()
405
405
406 # Object variable to store code object waiting execution. This is
406 # Object variable to store code object waiting execution. This is
407 # used mainly by the multithreaded shells, but it can come in handy in
407 # used mainly by the multithreaded shells, but it can come in handy in
408 # other situations. No need to use a Queue here, since it's a single
408 # other situations. No need to use a Queue here, since it's a single
409 # item which gets cleared once run.
409 # item which gets cleared once run.
410 self.code_to_run = None
410 self.code_to_run = None
411
411
412 # Flag to mark unconditional exit
412 # Flag to mark unconditional exit
413 self.exit_now = False
413 self.exit_now = False
414
414
415 # Temporary files used for various purposes. Deleted at exit.
415 # Temporary files used for various purposes. Deleted at exit.
416 self.tempfiles = []
416 self.tempfiles = []
417
417
418 # Keep track of readline usage (later set by init_readline)
418 # Keep track of readline usage (later set by init_readline)
419 self.has_readline = False
419 self.has_readline = False
420
420
421 # keep track of where we started running (mainly for crash post-mortem)
421 # keep track of where we started running (mainly for crash post-mortem)
422 # This is not being used anywhere currently.
422 # This is not being used anywhere currently.
423 self.starting_dir = os.getcwd()
423 self.starting_dir = os.getcwd()
424
424
425 # Indentation management
425 # Indentation management
426 self.indent_current_nsp = 0
426 self.indent_current_nsp = 0
427
427
428 def init_term_title(self):
428 def init_term_title(self):
429 # Enable or disable the terminal title.
429 # Enable or disable the terminal title.
430 if self.term_title:
430 if self.term_title:
431 toggle_set_term_title(True)
431 toggle_set_term_title(True)
432 set_term_title('IPython: ' + abbrev_cwd())
432 set_term_title('IPython: ' + abbrev_cwd())
433 else:
433 else:
434 toggle_set_term_title(False)
434 toggle_set_term_title(False)
435
435
436 def init_usage(self, usage=None):
436 def init_usage(self, usage=None):
437 if usage is None:
437 if usage is None:
438 self.usage = interactive_usage
438 self.usage = interactive_usage
439 else:
439 else:
440 self.usage = usage
440 self.usage = usage
441
441
442 def init_encoding(self):
442 def init_encoding(self):
443 # Get system encoding at startup time. Certain terminals (like Emacs
443 # Get system encoding at startup time. Certain terminals (like Emacs
444 # under Win32 have it set to None, and we need to have a known valid
444 # under Win32 have it set to None, and we need to have a known valid
445 # encoding to use in the raw_input() method
445 # encoding to use in the raw_input() method
446 try:
446 try:
447 self.stdin_encoding = sys.stdin.encoding or 'ascii'
447 self.stdin_encoding = sys.stdin.encoding or 'ascii'
448 except AttributeError:
448 except AttributeError:
449 self.stdin_encoding = 'ascii'
449 self.stdin_encoding = 'ascii'
450
450
451 def init_syntax_highlighting(self):
451 def init_syntax_highlighting(self):
452 # Python source parser/formatter for syntax highlighting
452 # Python source parser/formatter for syntax highlighting
453 pyformat = PyColorize.Parser().format
453 pyformat = PyColorize.Parser().format
454 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
454 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
455
455
456 def init_pushd_popd_magic(self):
456 def init_pushd_popd_magic(self):
457 # for pushd/popd management
457 # for pushd/popd management
458 try:
458 try:
459 self.home_dir = get_home_dir()
459 self.home_dir = get_home_dir()
460 except HomeDirError, msg:
460 except HomeDirError, msg:
461 fatal(msg)
461 fatal(msg)
462
462
463 self.dir_stack = []
463 self.dir_stack = []
464
464
465 def init_logger(self):
465 def init_logger(self):
466 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
466 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
467 # local shortcut, this is used a LOT
467 # local shortcut, this is used a LOT
468 self.log = self.logger.log
468 self.log = self.logger.log
469
469
470 def init_logstart(self):
470 def init_logstart(self):
471 if self.logappend:
471 if self.logappend:
472 self.magic_logstart(self.logappend + ' append')
472 self.magic_logstart(self.logappend + ' append')
473 elif self.logfile:
473 elif self.logfile:
474 self.magic_logstart(self.logfile)
474 self.magic_logstart(self.logfile)
475 elif self.logstart:
475 elif self.logstart:
476 self.magic_logstart()
476 self.magic_logstart()
477
477
478 def init_builtins(self):
478 def init_builtins(self):
479 self.builtin_trap = BuiltinTrap(self)
479 self.builtin_trap = BuiltinTrap(self)
480
480
481 def init_inspector(self):
481 def init_inspector(self):
482 # Object inspector
482 # Object inspector
483 self.inspector = oinspect.Inspector(oinspect.InspectColors,
483 self.inspector = oinspect.Inspector(oinspect.InspectColors,
484 PyColorize.ANSICodeColors,
484 PyColorize.ANSICodeColors,
485 'NoColor',
485 'NoColor',
486 self.object_info_string_level)
486 self.object_info_string_level)
487
487
488 def init_prompts(self):
488 def init_prompts(self):
489 # Initialize cache, set in/out prompts and printing system
489 # Initialize cache, set in/out prompts and printing system
490 self.outputcache = CachedOutput(self,
490 self.outputcache = CachedOutput(self,
491 self.cache_size,
491 self.cache_size,
492 self.pprint,
492 self.pprint,
493 input_sep = self.separate_in,
493 input_sep = self.separate_in,
494 output_sep = self.separate_out,
494 output_sep = self.separate_out,
495 output_sep2 = self.separate_out2,
495 output_sep2 = self.separate_out2,
496 ps1 = self.prompt_in1,
496 ps1 = self.prompt_in1,
497 ps2 = self.prompt_in2,
497 ps2 = self.prompt_in2,
498 ps_out = self.prompt_out,
498 ps_out = self.prompt_out,
499 pad_left = self.prompts_pad_left)
499 pad_left = self.prompts_pad_left)
500
500
501 # user may have over-ridden the default print hook:
501 # user may have over-ridden the default print hook:
502 try:
502 try:
503 self.outputcache.__class__.display = self.hooks.display
503 self.outputcache.__class__.display = self.hooks.display
504 except AttributeError:
504 except AttributeError:
505 pass
505 pass
506
506
507 def init_displayhook(self):
507 def init_displayhook(self):
508 self.display_trap = DisplayTrap(self, self.outputcache)
508 self.display_trap = DisplayTrap(self, self.outputcache)
509
509
510 def init_reload_doctest(self):
510 def init_reload_doctest(self):
511 # Do a proper resetting of doctest, including the necessary displayhook
511 # Do a proper resetting of doctest, including the necessary displayhook
512 # monkeypatching
512 # monkeypatching
513 try:
513 try:
514 doctest_reload()
514 doctest_reload()
515 except ImportError:
515 except ImportError:
516 warn("doctest module does not exist.")
516 warn("doctest module does not exist.")
517
517
518 #-------------------------------------------------------------------------
518 #-------------------------------------------------------------------------
519 # Things related to the banner
519 # Things related to the banner
520 #-------------------------------------------------------------------------
520 #-------------------------------------------------------------------------
521
521
522 def init_banner(self, banner1, banner2, display_banner):
522 def init_banner(self, banner1, banner2, display_banner):
523 if banner1 is not None:
523 if banner1 is not None:
524 self.banner1 = banner1
524 self.banner1 = banner1
525 if banner2 is not None:
525 if banner2 is not None:
526 self.banner2 = banner2
526 self.banner2 = banner2
527 if display_banner is not None:
527 if display_banner is not None:
528 self.display_banner = display_banner
528 self.display_banner = display_banner
529 self.compute_banner()
529 self.compute_banner()
530
530
531 def show_banner(self, banner=None):
531 def show_banner(self, banner=None):
532 if banner is None:
532 if banner is None:
533 banner = self.banner
533 banner = self.banner
534 self.write(banner)
534 self.write(banner)
535
535
536 def compute_banner(self):
536 def compute_banner(self):
537 self.banner = self.banner1 + '\n'
537 self.banner = self.banner1 + '\n'
538 if self.profile:
538 if self.profile:
539 self.banner += '\nIPython profile: %s\n' % self.profile
539 self.banner += '\nIPython profile: %s\n' % self.profile
540 if self.banner2:
540 if self.banner2:
541 self.banner += '\n' + self.banner2 + '\n'
541 self.banner += '\n' + self.banner2 + '\n'
542
542
543 #-------------------------------------------------------------------------
543 #-------------------------------------------------------------------------
544 # Things related to injections into the sys module
544 # Things related to injections into the sys module
545 #-------------------------------------------------------------------------
545 #-------------------------------------------------------------------------
546
546
547 def save_sys_module_state(self):
547 def save_sys_module_state(self):
548 """Save the state of hooks in the sys module.
548 """Save the state of hooks in the sys module.
549
549
550 This has to be called after self.user_ns is created.
550 This has to be called after self.user_ns is created.
551 """
551 """
552 self._orig_sys_module_state = {}
552 self._orig_sys_module_state = {}
553 self._orig_sys_module_state['stdin'] = sys.stdin
553 self._orig_sys_module_state['stdin'] = sys.stdin
554 self._orig_sys_module_state['stdout'] = sys.stdout
554 self._orig_sys_module_state['stdout'] = sys.stdout
555 self._orig_sys_module_state['stderr'] = sys.stderr
555 self._orig_sys_module_state['stderr'] = sys.stderr
556 self._orig_sys_module_state['excepthook'] = sys.excepthook
556 self._orig_sys_module_state['excepthook'] = sys.excepthook
557 try:
557 try:
558 self._orig_sys_modules_main_name = self.user_ns['__name__']
558 self._orig_sys_modules_main_name = self.user_ns['__name__']
559 except KeyError:
559 except KeyError:
560 pass
560 pass
561
561
562 def restore_sys_module_state(self):
562 def restore_sys_module_state(self):
563 """Restore the state of the sys module."""
563 """Restore the state of the sys module."""
564 try:
564 try:
565 for k, v in self._orig_sys_module_state.items():
565 for k, v in self._orig_sys_module_state.items():
566 setattr(sys, k, v)
566 setattr(sys, k, v)
567 except AttributeError:
567 except AttributeError:
568 pass
568 pass
569 try:
569 try:
570 delattr(sys, 'ipcompleter')
570 delattr(sys, 'ipcompleter')
571 except AttributeError:
571 except AttributeError:
572 pass
572 pass
573 # Reset what what done in self.init_sys_modules
573 # Reset what what done in self.init_sys_modules
574 try:
574 try:
575 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
575 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
576 except (AttributeError, KeyError):
576 except (AttributeError, KeyError):
577 pass
577 pass
578
578
579 #-------------------------------------------------------------------------
579 #-------------------------------------------------------------------------
580 # Things related to hooks
580 # Things related to hooks
581 #-------------------------------------------------------------------------
581 #-------------------------------------------------------------------------
582
582
583 def init_hooks(self):
583 def init_hooks(self):
584 # hooks holds pointers used for user-side customizations
584 # hooks holds pointers used for user-side customizations
585 self.hooks = Struct()
585 self.hooks = Struct()
586
586
587 self.strdispatchers = {}
587 self.strdispatchers = {}
588
588
589 # Set all default hooks, defined in the IPython.hooks module.
589 # Set all default hooks, defined in the IPython.hooks module.
590 import IPython.core.hooks
590 import IPython.core.hooks
591 hooks = IPython.core.hooks
591 hooks = IPython.core.hooks
592 for hook_name in hooks.__all__:
592 for hook_name in hooks.__all__:
593 # default hooks have priority 100, i.e. low; user hooks should have
593 # default hooks have priority 100, i.e. low; user hooks should have
594 # 0-100 priority
594 # 0-100 priority
595 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
595 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
596
596
597 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
597 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
598 """set_hook(name,hook) -> sets an internal IPython hook.
598 """set_hook(name,hook) -> sets an internal IPython hook.
599
599
600 IPython exposes some of its internal API as user-modifiable hooks. By
600 IPython exposes some of its internal API as user-modifiable hooks. By
601 adding your function to one of these hooks, you can modify IPython's
601 adding your function to one of these hooks, you can modify IPython's
602 behavior to call at runtime your own routines."""
602 behavior to call at runtime your own routines."""
603
603
604 # At some point in the future, this should validate the hook before it
604 # At some point in the future, this should validate the hook before it
605 # accepts it. Probably at least check that the hook takes the number
605 # accepts it. Probably at least check that the hook takes the number
606 # of args it's supposed to.
606 # of args it's supposed to.
607
607
608 f = new.instancemethod(hook,self,self.__class__)
608 f = new.instancemethod(hook,self,self.__class__)
609
609
610 # check if the hook is for strdispatcher first
610 # check if the hook is for strdispatcher first
611 if str_key is not None:
611 if str_key is not None:
612 sdp = self.strdispatchers.get(name, StrDispatch())
612 sdp = self.strdispatchers.get(name, StrDispatch())
613 sdp.add_s(str_key, f, priority )
613 sdp.add_s(str_key, f, priority )
614 self.strdispatchers[name] = sdp
614 self.strdispatchers[name] = sdp
615 return
615 return
616 if re_key is not None:
616 if re_key is not None:
617 sdp = self.strdispatchers.get(name, StrDispatch())
617 sdp = self.strdispatchers.get(name, StrDispatch())
618 sdp.add_re(re.compile(re_key), f, priority )
618 sdp.add_re(re.compile(re_key), f, priority )
619 self.strdispatchers[name] = sdp
619 self.strdispatchers[name] = sdp
620 return
620 return
621
621
622 dp = getattr(self.hooks, name, None)
622 dp = getattr(self.hooks, name, None)
623 if name not in IPython.core.hooks.__all__:
623 if name not in IPython.core.hooks.__all__:
624 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
624 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
625 if not dp:
625 if not dp:
626 dp = IPython.core.hooks.CommandChainDispatcher()
626 dp = IPython.core.hooks.CommandChainDispatcher()
627
627
628 try:
628 try:
629 dp.add(f,priority)
629 dp.add(f,priority)
630 except AttributeError:
630 except AttributeError:
631 # it was not commandchain, plain old func - replace
631 # it was not commandchain, plain old func - replace
632 dp = f
632 dp = f
633
633
634 setattr(self.hooks,name, dp)
634 setattr(self.hooks,name, dp)
635
635
636 #-------------------------------------------------------------------------
636 #-------------------------------------------------------------------------
637 # Things related to the "main" module
637 # Things related to the "main" module
638 #-------------------------------------------------------------------------
638 #-------------------------------------------------------------------------
639
639
640 def new_main_mod(self,ns=None):
640 def new_main_mod(self,ns=None):
641 """Return a new 'main' module object for user code execution.
641 """Return a new 'main' module object for user code execution.
642 """
642 """
643 main_mod = self._user_main_module
643 main_mod = self._user_main_module
644 init_fakemod_dict(main_mod,ns)
644 init_fakemod_dict(main_mod,ns)
645 return main_mod
645 return main_mod
646
646
647 def cache_main_mod(self,ns,fname):
647 def cache_main_mod(self,ns,fname):
648 """Cache a main module's namespace.
648 """Cache a main module's namespace.
649
649
650 When scripts are executed via %run, we must keep a reference to the
650 When scripts are executed via %run, we must keep a reference to the
651 namespace of their __main__ module (a FakeModule instance) around so
651 namespace of their __main__ module (a FakeModule instance) around so
652 that Python doesn't clear it, rendering objects defined therein
652 that Python doesn't clear it, rendering objects defined therein
653 useless.
653 useless.
654
654
655 This method keeps said reference in a private dict, keyed by the
655 This method keeps said reference in a private dict, keyed by the
656 absolute path of the module object (which corresponds to the script
656 absolute path of the module object (which corresponds to the script
657 path). This way, for multiple executions of the same script we only
657 path). This way, for multiple executions of the same script we only
658 keep one copy of the namespace (the last one), thus preventing memory
658 keep one copy of the namespace (the last one), thus preventing memory
659 leaks from old references while allowing the objects from the last
659 leaks from old references while allowing the objects from the last
660 execution to be accessible.
660 execution to be accessible.
661
661
662 Note: we can not allow the actual FakeModule instances to be deleted,
662 Note: we can not allow the actual FakeModule instances to be deleted,
663 because of how Python tears down modules (it hard-sets all their
663 because of how Python tears down modules (it hard-sets all their
664 references to None without regard for reference counts). This method
664 references to None without regard for reference counts). This method
665 must therefore make a *copy* of the given namespace, to allow the
665 must therefore make a *copy* of the given namespace, to allow the
666 original module's __dict__ to be cleared and reused.
666 original module's __dict__ to be cleared and reused.
667
667
668
668
669 Parameters
669 Parameters
670 ----------
670 ----------
671 ns : a namespace (a dict, typically)
671 ns : a namespace (a dict, typically)
672
672
673 fname : str
673 fname : str
674 Filename associated with the namespace.
674 Filename associated with the namespace.
675
675
676 Examples
676 Examples
677 --------
677 --------
678
678
679 In [10]: import IPython
679 In [10]: import IPython
680
680
681 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
681 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
682
682
683 In [12]: IPython.__file__ in _ip._main_ns_cache
683 In [12]: IPython.__file__ in _ip._main_ns_cache
684 Out[12]: True
684 Out[12]: True
685 """
685 """
686 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
686 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
687
687
688 def clear_main_mod_cache(self):
688 def clear_main_mod_cache(self):
689 """Clear the cache of main modules.
689 """Clear the cache of main modules.
690
690
691 Mainly for use by utilities like %reset.
691 Mainly for use by utilities like %reset.
692
692
693 Examples
693 Examples
694 --------
694 --------
695
695
696 In [15]: import IPython
696 In [15]: import IPython
697
697
698 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
698 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
699
699
700 In [17]: len(_ip._main_ns_cache) > 0
700 In [17]: len(_ip._main_ns_cache) > 0
701 Out[17]: True
701 Out[17]: True
702
702
703 In [18]: _ip.clear_main_mod_cache()
703 In [18]: _ip.clear_main_mod_cache()
704
704
705 In [19]: len(_ip._main_ns_cache) == 0
705 In [19]: len(_ip._main_ns_cache) == 0
706 Out[19]: True
706 Out[19]: True
707 """
707 """
708 self._main_ns_cache.clear()
708 self._main_ns_cache.clear()
709
709
710 #-------------------------------------------------------------------------
710 #-------------------------------------------------------------------------
711 # Things related to debugging
711 # Things related to debugging
712 #-------------------------------------------------------------------------
712 #-------------------------------------------------------------------------
713
713
714 def init_pdb(self):
714 def init_pdb(self):
715 # Set calling of pdb on exceptions
715 # Set calling of pdb on exceptions
716 # self.call_pdb is a property
716 # self.call_pdb is a property
717 self.call_pdb = self.pdb
717 self.call_pdb = self.pdb
718
718
719 def _get_call_pdb(self):
719 def _get_call_pdb(self):
720 return self._call_pdb
720 return self._call_pdb
721
721
722 def _set_call_pdb(self,val):
722 def _set_call_pdb(self,val):
723
723
724 if val not in (0,1,False,True):
724 if val not in (0,1,False,True):
725 raise ValueError,'new call_pdb value must be boolean'
725 raise ValueError,'new call_pdb value must be boolean'
726
726
727 # store value in instance
727 # store value in instance
728 self._call_pdb = val
728 self._call_pdb = val
729
729
730 # notify the actual exception handlers
730 # notify the actual exception handlers
731 self.InteractiveTB.call_pdb = val
731 self.InteractiveTB.call_pdb = val
732 if self.isthreaded:
732 if self.isthreaded:
733 try:
733 try:
734 self.sys_excepthook.call_pdb = val
734 self.sys_excepthook.call_pdb = val
735 except:
735 except:
736 warn('Failed to activate pdb for threaded exception handler')
736 warn('Failed to activate pdb for threaded exception handler')
737
737
738 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
738 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
739 'Control auto-activation of pdb at exceptions')
739 'Control auto-activation of pdb at exceptions')
740
740
741 def debugger(self,force=False):
741 def debugger(self,force=False):
742 """Call the pydb/pdb debugger.
742 """Call the pydb/pdb debugger.
743
743
744 Keywords:
744 Keywords:
745
745
746 - force(False): by default, this routine checks the instance call_pdb
746 - force(False): by default, this routine checks the instance call_pdb
747 flag and does not actually invoke the debugger if the flag is false.
747 flag and does not actually invoke the debugger if the flag is false.
748 The 'force' option forces the debugger to activate even if the flag
748 The 'force' option forces the debugger to activate even if the flag
749 is false.
749 is false.
750 """
750 """
751
751
752 if not (force or self.call_pdb):
752 if not (force or self.call_pdb):
753 return
753 return
754
754
755 if not hasattr(sys,'last_traceback'):
755 if not hasattr(sys,'last_traceback'):
756 error('No traceback has been produced, nothing to debug.')
756 error('No traceback has been produced, nothing to debug.')
757 return
757 return
758
758
759 # use pydb if available
759 # use pydb if available
760 if debugger.has_pydb:
760 if debugger.has_pydb:
761 from pydb import pm
761 from pydb import pm
762 else:
762 else:
763 # fallback to our internal debugger
763 # fallback to our internal debugger
764 pm = lambda : self.InteractiveTB.debugger(force=True)
764 pm = lambda : self.InteractiveTB.debugger(force=True)
765 self.history_saving_wrapper(pm)()
765 self.history_saving_wrapper(pm)()
766
766
767 #-------------------------------------------------------------------------
767 #-------------------------------------------------------------------------
768 # Things related to IPython's various namespaces
768 # Things related to IPython's various namespaces
769 #-------------------------------------------------------------------------
769 #-------------------------------------------------------------------------
770
770
771 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
771 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
772 # Create the namespace where the user will operate. user_ns is
772 # Create the namespace where the user will operate. user_ns is
773 # normally the only one used, and it is passed to the exec calls as
773 # normally the only one used, and it is passed to the exec calls as
774 # the locals argument. But we do carry a user_global_ns namespace
774 # the locals argument. But we do carry a user_global_ns namespace
775 # given as the exec 'globals' argument, This is useful in embedding
775 # given as the exec 'globals' argument, This is useful in embedding
776 # situations where the ipython shell opens in a context where the
776 # situations where the ipython shell opens in a context where the
777 # distinction between locals and globals is meaningful. For
777 # distinction between locals and globals is meaningful. For
778 # non-embedded contexts, it is just the same object as the user_ns dict.
778 # non-embedded contexts, it is just the same object as the user_ns dict.
779
779
780 # FIXME. For some strange reason, __builtins__ is showing up at user
780 # FIXME. For some strange reason, __builtins__ is showing up at user
781 # level as a dict instead of a module. This is a manual fix, but I
781 # level as a dict instead of a module. This is a manual fix, but I
782 # should really track down where the problem is coming from. Alex
782 # should really track down where the problem is coming from. Alex
783 # Schmolck reported this problem first.
783 # Schmolck reported this problem first.
784
784
785 # A useful post by Alex Martelli on this topic:
785 # A useful post by Alex Martelli on this topic:
786 # Re: inconsistent value from __builtins__
786 # Re: inconsistent value from __builtins__
787 # Von: Alex Martelli <aleaxit@yahoo.com>
787 # Von: Alex Martelli <aleaxit@yahoo.com>
788 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
788 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
789 # Gruppen: comp.lang.python
789 # Gruppen: comp.lang.python
790
790
791 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
791 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
792 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
792 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
793 # > <type 'dict'>
793 # > <type 'dict'>
794 # > >>> print type(__builtins__)
794 # > >>> print type(__builtins__)
795 # > <type 'module'>
795 # > <type 'module'>
796 # > Is this difference in return value intentional?
796 # > Is this difference in return value intentional?
797
797
798 # Well, it's documented that '__builtins__' can be either a dictionary
798 # Well, it's documented that '__builtins__' can be either a dictionary
799 # or a module, and it's been that way for a long time. Whether it's
799 # or a module, and it's been that way for a long time. Whether it's
800 # intentional (or sensible), I don't know. In any case, the idea is
800 # intentional (or sensible), I don't know. In any case, the idea is
801 # that if you need to access the built-in namespace directly, you
801 # that if you need to access the built-in namespace directly, you
802 # should start with "import __builtin__" (note, no 's') which will
802 # should start with "import __builtin__" (note, no 's') which will
803 # definitely give you a module. Yeah, it's somewhat confusing:-(.
803 # definitely give you a module. Yeah, it's somewhat confusing:-(.
804
804
805 # These routines return properly built dicts as needed by the rest of
805 # These routines return properly built dicts as needed by the rest of
806 # the code, and can also be used by extension writers to generate
806 # the code, and can also be used by extension writers to generate
807 # properly initialized namespaces.
807 # properly initialized namespaces.
808 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
808 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
809 user_global_ns)
809 user_global_ns)
810
810
811 # Assign namespaces
811 # Assign namespaces
812 # This is the namespace where all normal user variables live
812 # This is the namespace where all normal user variables live
813 self.user_ns = user_ns
813 self.user_ns = user_ns
814 self.user_global_ns = user_global_ns
814 self.user_global_ns = user_global_ns
815
815
816 # An auxiliary namespace that checks what parts of the user_ns were
816 # An auxiliary namespace that checks what parts of the user_ns were
817 # loaded at startup, so we can list later only variables defined in
817 # loaded at startup, so we can list later only variables defined in
818 # actual interactive use. Since it is always a subset of user_ns, it
818 # actual interactive use. Since it is always a subset of user_ns, it
819 # doesn't need to be seaparately tracked in the ns_table
819 # doesn't need to be seaparately tracked in the ns_table
820 self.user_config_ns = {}
820 self.user_config_ns = {}
821
821
822 # A namespace to keep track of internal data structures to prevent
822 # A namespace to keep track of internal data structures to prevent
823 # them from cluttering user-visible stuff. Will be updated later
823 # them from cluttering user-visible stuff. Will be updated later
824 self.internal_ns = {}
824 self.internal_ns = {}
825
825
826 # Now that FakeModule produces a real module, we've run into a nasty
826 # Now that FakeModule produces a real module, we've run into a nasty
827 # problem: after script execution (via %run), the module where the user
827 # problem: after script execution (via %run), the module where the user
828 # code ran is deleted. Now that this object is a true module (needed
828 # code ran is deleted. Now that this object is a true module (needed
829 # so docetst and other tools work correctly), the Python module
829 # so docetst and other tools work correctly), the Python module
830 # teardown mechanism runs over it, and sets to None every variable
830 # teardown mechanism runs over it, and sets to None every variable
831 # present in that module. Top-level references to objects from the
831 # present in that module. Top-level references to objects from the
832 # script survive, because the user_ns is updated with them. However,
832 # script survive, because the user_ns is updated with them. However,
833 # calling functions defined in the script that use other things from
833 # calling functions defined in the script that use other things from
834 # the script will fail, because the function's closure had references
834 # the script will fail, because the function's closure had references
835 # to the original objects, which are now all None. So we must protect
835 # to the original objects, which are now all None. So we must protect
836 # these modules from deletion by keeping a cache.
836 # these modules from deletion by keeping a cache.
837 #
837 #
838 # To avoid keeping stale modules around (we only need the one from the
838 # To avoid keeping stale modules around (we only need the one from the
839 # last run), we use a dict keyed with the full path to the script, so
839 # last run), we use a dict keyed with the full path to the script, so
840 # only the last version of the module is held in the cache. Note,
840 # only the last version of the module is held in the cache. Note,
841 # however, that we must cache the module *namespace contents* (their
841 # however, that we must cache the module *namespace contents* (their
842 # __dict__). Because if we try to cache the actual modules, old ones
842 # __dict__). Because if we try to cache the actual modules, old ones
843 # (uncached) could be destroyed while still holding references (such as
843 # (uncached) could be destroyed while still holding references (such as
844 # those held by GUI objects that tend to be long-lived)>
844 # those held by GUI objects that tend to be long-lived)>
845 #
845 #
846 # The %reset command will flush this cache. See the cache_main_mod()
846 # The %reset command will flush this cache. See the cache_main_mod()
847 # and clear_main_mod_cache() methods for details on use.
847 # and clear_main_mod_cache() methods for details on use.
848
848
849 # This is the cache used for 'main' namespaces
849 # This is the cache used for 'main' namespaces
850 self._main_ns_cache = {}
850 self._main_ns_cache = {}
851 # And this is the single instance of FakeModule whose __dict__ we keep
851 # And this is the single instance of FakeModule whose __dict__ we keep
852 # copying and clearing for reuse on each %run
852 # copying and clearing for reuse on each %run
853 self._user_main_module = FakeModule()
853 self._user_main_module = FakeModule()
854
854
855 # A table holding all the namespaces IPython deals with, so that
855 # A table holding all the namespaces IPython deals with, so that
856 # introspection facilities can search easily.
856 # introspection facilities can search easily.
857 self.ns_table = {'user':user_ns,
857 self.ns_table = {'user':user_ns,
858 'user_global':user_global_ns,
858 'user_global':user_global_ns,
859 'internal':self.internal_ns,
859 'internal':self.internal_ns,
860 'builtin':__builtin__.__dict__
860 'builtin':__builtin__.__dict__
861 }
861 }
862
862
863 # Similarly, track all namespaces where references can be held and that
863 # Similarly, track all namespaces where references can be held and that
864 # we can safely clear (so it can NOT include builtin). This one can be
864 # we can safely clear (so it can NOT include builtin). This one can be
865 # a simple list.
865 # a simple list.
866 self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns,
866 self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns,
867 self.internal_ns, self._main_ns_cache ]
867 self.internal_ns, self._main_ns_cache ]
868
868
869 def init_sys_modules(self):
869 def init_sys_modules(self):
870 # We need to insert into sys.modules something that looks like a
870 # We need to insert into sys.modules something that looks like a
871 # module but which accesses the IPython namespace, for shelve and
871 # module but which accesses the IPython namespace, for shelve and
872 # pickle to work interactively. Normally they rely on getting
872 # pickle to work interactively. Normally they rely on getting
873 # everything out of __main__, but for embedding purposes each IPython
873 # everything out of __main__, but for embedding purposes each IPython
874 # instance has its own private namespace, so we can't go shoving
874 # instance has its own private namespace, so we can't go shoving
875 # everything into __main__.
875 # everything into __main__.
876
876
877 # note, however, that we should only do this for non-embedded
877 # note, however, that we should only do this for non-embedded
878 # ipythons, which really mimic the __main__.__dict__ with their own
878 # ipythons, which really mimic the __main__.__dict__ with their own
879 # namespace. Embedded instances, on the other hand, should not do
879 # namespace. Embedded instances, on the other hand, should not do
880 # this because they need to manage the user local/global namespaces
880 # this because they need to manage the user local/global namespaces
881 # only, but they live within a 'normal' __main__ (meaning, they
881 # only, but they live within a 'normal' __main__ (meaning, they
882 # shouldn't overtake the execution environment of the script they're
882 # shouldn't overtake the execution environment of the script they're
883 # embedded in).
883 # embedded in).
884
884
885 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
885 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
886
886
887 try:
887 try:
888 main_name = self.user_ns['__name__']
888 main_name = self.user_ns['__name__']
889 except KeyError:
889 except KeyError:
890 raise KeyError('user_ns dictionary MUST have a "__name__" key')
890 raise KeyError('user_ns dictionary MUST have a "__name__" key')
891 else:
891 else:
892 sys.modules[main_name] = FakeModule(self.user_ns)
892 sys.modules[main_name] = FakeModule(self.user_ns)
893
893
894 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
894 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
895 """Return a valid local and global user interactive namespaces.
895 """Return a valid local and global user interactive namespaces.
896
896
897 This builds a dict with the minimal information needed to operate as a
897 This builds a dict with the minimal information needed to operate as a
898 valid IPython user namespace, which you can pass to the various
898 valid IPython user namespace, which you can pass to the various
899 embedding classes in ipython. The default implementation returns the
899 embedding classes in ipython. The default implementation returns the
900 same dict for both the locals and the globals to allow functions to
900 same dict for both the locals and the globals to allow functions to
901 refer to variables in the namespace. Customized implementations can
901 refer to variables in the namespace. Customized implementations can
902 return different dicts. The locals dictionary can actually be anything
902 return different dicts. The locals dictionary can actually be anything
903 following the basic mapping protocol of a dict, but the globals dict
903 following the basic mapping protocol of a dict, but the globals dict
904 must be a true dict, not even a subclass. It is recommended that any
904 must be a true dict, not even a subclass. It is recommended that any
905 custom object for the locals namespace synchronize with the globals
905 custom object for the locals namespace synchronize with the globals
906 dict somehow.
906 dict somehow.
907
907
908 Raises TypeError if the provided globals namespace is not a true dict.
908 Raises TypeError if the provided globals namespace is not a true dict.
909
909
910 :Parameters:
910 :Parameters:
911 user_ns : dict-like, optional
911 user_ns : dict-like, optional
912 The current user namespace. The items in this namespace should
912 The current user namespace. The items in this namespace should
913 be included in the output. If None, an appropriate blank
913 be included in the output. If None, an appropriate blank
914 namespace should be created.
914 namespace should be created.
915 user_global_ns : dict, optional
915 user_global_ns : dict, optional
916 The current user global namespace. The items in this namespace
916 The current user global namespace. The items in this namespace
917 should be included in the output. If None, an appropriate
917 should be included in the output. If None, an appropriate
918 blank namespace should be created.
918 blank namespace should be created.
919
919
920 :Returns:
920 :Returns:
921 A tuple pair of dictionary-like object to be used as the local namespace
921 A tuple pair of dictionary-like object to be used as the local namespace
922 of the interpreter and a dict to be used as the global namespace.
922 of the interpreter and a dict to be used as the global namespace.
923 """
923 """
924
924
925 if user_ns is None:
925 if user_ns is None:
926 # Set __name__ to __main__ to better match the behavior of the
926 # Set __name__ to __main__ to better match the behavior of the
927 # normal interpreter.
927 # normal interpreter.
928 user_ns = {'__name__' :'__main__',
928 user_ns = {'__name__' :'__main__',
929 '__builtins__' : __builtin__,
929 '__builtins__' : __builtin__,
930 }
930 }
931 else:
931 else:
932 user_ns.setdefault('__name__','__main__')
932 user_ns.setdefault('__name__','__main__')
933 user_ns.setdefault('__builtins__',__builtin__)
933 user_ns.setdefault('__builtins__',__builtin__)
934
934
935 if user_global_ns is None:
935 if user_global_ns is None:
936 user_global_ns = user_ns
936 user_global_ns = user_ns
937 if type(user_global_ns) is not dict:
937 if type(user_global_ns) is not dict:
938 raise TypeError("user_global_ns must be a true dict; got %r"
938 raise TypeError("user_global_ns must be a true dict; got %r"
939 % type(user_global_ns))
939 % type(user_global_ns))
940
940
941 return user_ns, user_global_ns
941 return user_ns, user_global_ns
942
942
943 def init_user_ns(self):
943 def init_user_ns(self):
944 """Initialize all user-visible namespaces to their minimum defaults.
944 """Initialize all user-visible namespaces to their minimum defaults.
945
945
946 Certain history lists are also initialized here, as they effectively
946 Certain history lists are also initialized here, as they effectively
947 act as user namespaces.
947 act as user namespaces.
948
948
949 Notes
949 Notes
950 -----
950 -----
951 All data structures here are only filled in, they are NOT reset by this
951 All data structures here are only filled in, they are NOT reset by this
952 method. If they were not empty before, data will simply be added to
952 method. If they were not empty before, data will simply be added to
953 therm.
953 therm.
954 """
954 """
955 # Store myself as the public api!!!
955 # Store myself as the public api!!!
956 self.user_ns['get_ipython'] = self.get_ipython
956 self.user_ns['get_ipython'] = self.get_ipython
957
957
958 # make global variables for user access to the histories
958 # make global variables for user access to the histories
959 self.user_ns['_ih'] = self.input_hist
959 self.user_ns['_ih'] = self.input_hist
960 self.user_ns['_oh'] = self.output_hist
960 self.user_ns['_oh'] = self.output_hist
961 self.user_ns['_dh'] = self.dir_hist
961 self.user_ns['_dh'] = self.dir_hist
962
962
963 # user aliases to input and output histories
963 # user aliases to input and output histories
964 self.user_ns['In'] = self.input_hist
964 self.user_ns['In'] = self.input_hist
965 self.user_ns['Out'] = self.output_hist
965 self.user_ns['Out'] = self.output_hist
966
966
967 self.user_ns['_sh'] = shadowns
967 self.user_ns['_sh'] = shadowns
968
968
969 # Put 'help' in the user namespace
969 # Put 'help' in the user namespace
970 try:
970 try:
971 from site import _Helper
971 from site import _Helper
972 self.user_ns['help'] = _Helper()
972 self.user_ns['help'] = _Helper()
973 except ImportError:
973 except ImportError:
974 warn('help() not available - check site.py')
974 warn('help() not available - check site.py')
975
975
976 def reset(self):
976 def reset(self):
977 """Clear all internal namespaces.
977 """Clear all internal namespaces.
978
978
979 Note that this is much more aggressive than %reset, since it clears
979 Note that this is much more aggressive than %reset, since it clears
980 fully all namespaces, as well as all input/output lists.
980 fully all namespaces, as well as all input/output lists.
981 """
981 """
982 for ns in self.ns_refs_table:
982 for ns in self.ns_refs_table:
983 ns.clear()
983 ns.clear()
984
984
985 self.alias_manager.clear_aliases()
985 self.alias_manager.clear_aliases()
986
986
987 # Clear input and output histories
987 # Clear input and output histories
988 self.input_hist[:] = []
988 self.input_hist[:] = []
989 self.input_hist_raw[:] = []
989 self.input_hist_raw[:] = []
990 self.output_hist.clear()
990 self.output_hist.clear()
991
991
992 # Restore the user namespaces to minimal usability
992 # Restore the user namespaces to minimal usability
993 self.init_user_ns()
993 self.init_user_ns()
994
994
995 # Restore the default and user aliases
995 # Restore the default and user aliases
996 self.alias_manager.init_aliases()
996 self.alias_manager.init_aliases()
997
997
998 def push(self, variables, interactive=True):
998 def push(self, variables, interactive=True):
999 """Inject a group of variables into the IPython user namespace.
999 """Inject a group of variables into the IPython user namespace.
1000
1000
1001 Parameters
1001 Parameters
1002 ----------
1002 ----------
1003 variables : dict, str or list/tuple of str
1003 variables : dict, str or list/tuple of str
1004 The variables to inject into the user's namespace. If a dict,
1004 The variables to inject into the user's namespace. If a dict,
1005 a simple update is done. If a str, the string is assumed to
1005 a simple update is done. If a str, the string is assumed to
1006 have variable names separated by spaces. A list/tuple of str
1006 have variable names separated by spaces. A list/tuple of str
1007 can also be used to give the variable names. If just the variable
1007 can also be used to give the variable names. If just the variable
1008 names are give (list/tuple/str) then the variable values looked
1008 names are give (list/tuple/str) then the variable values looked
1009 up in the callers frame.
1009 up in the callers frame.
1010 interactive : bool
1010 interactive : bool
1011 If True (default), the variables will be listed with the ``who``
1011 If True (default), the variables will be listed with the ``who``
1012 magic.
1012 magic.
1013 """
1013 """
1014 vdict = None
1014 vdict = None
1015
1015
1016 # We need a dict of name/value pairs to do namespace updates.
1016 # We need a dict of name/value pairs to do namespace updates.
1017 if isinstance(variables, dict):
1017 if isinstance(variables, dict):
1018 vdict = variables
1018 vdict = variables
1019 elif isinstance(variables, (basestring, list, tuple)):
1019 elif isinstance(variables, (basestring, list, tuple)):
1020 if isinstance(variables, basestring):
1020 if isinstance(variables, basestring):
1021 vlist = variables.split()
1021 vlist = variables.split()
1022 else:
1022 else:
1023 vlist = variables
1023 vlist = variables
1024 vdict = {}
1024 vdict = {}
1025 cf = sys._getframe(1)
1025 cf = sys._getframe(1)
1026 for name in vlist:
1026 for name in vlist:
1027 try:
1027 try:
1028 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1028 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1029 except:
1029 except:
1030 print ('Could not get variable %s from %s' %
1030 print ('Could not get variable %s from %s' %
1031 (name,cf.f_code.co_name))
1031 (name,cf.f_code.co_name))
1032 else:
1032 else:
1033 raise ValueError('variables must be a dict/str/list/tuple')
1033 raise ValueError('variables must be a dict/str/list/tuple')
1034
1034
1035 # Propagate variables to user namespace
1035 # Propagate variables to user namespace
1036 self.user_ns.update(vdict)
1036 self.user_ns.update(vdict)
1037
1037
1038 # And configure interactive visibility
1038 # And configure interactive visibility
1039 config_ns = self.user_config_ns
1039 config_ns = self.user_config_ns
1040 if interactive:
1040 if interactive:
1041 for name, val in vdict.iteritems():
1041 for name, val in vdict.iteritems():
1042 config_ns.pop(name, None)
1042 config_ns.pop(name, None)
1043 else:
1043 else:
1044 for name,val in vdict.iteritems():
1044 for name,val in vdict.iteritems():
1045 config_ns[name] = val
1045 config_ns[name] = val
1046
1046
1047 #-------------------------------------------------------------------------
1047 #-------------------------------------------------------------------------
1048 # Things related to history management
1048 # Things related to history management
1049 #-------------------------------------------------------------------------
1049 #-------------------------------------------------------------------------
1050
1050
1051 def init_history(self):
1051 def init_history(self):
1052 # List of input with multi-line handling.
1052 # List of input with multi-line handling.
1053 self.input_hist = InputList()
1053 self.input_hist = InputList()
1054 # This one will hold the 'raw' input history, without any
1054 # This one will hold the 'raw' input history, without any
1055 # pre-processing. This will allow users to retrieve the input just as
1055 # pre-processing. This will allow users to retrieve the input just as
1056 # it was exactly typed in by the user, with %hist -r.
1056 # it was exactly typed in by the user, with %hist -r.
1057 self.input_hist_raw = InputList()
1057 self.input_hist_raw = InputList()
1058
1058
1059 # list of visited directories
1059 # list of visited directories
1060 try:
1060 try:
1061 self.dir_hist = [os.getcwd()]
1061 self.dir_hist = [os.getcwd()]
1062 except OSError:
1062 except OSError:
1063 self.dir_hist = []
1063 self.dir_hist = []
1064
1064
1065 # dict of output history
1065 # dict of output history
1066 self.output_hist = {}
1066 self.output_hist = {}
1067
1067
1068 # Now the history file
1068 # Now the history file
1069 if self.profile:
1069 if self.profile:
1070 histfname = 'history-%s' % self.profile
1070 histfname = 'history-%s' % self.profile
1071 else:
1071 else:
1072 histfname = 'history'
1072 histfname = 'history'
1073 self.histfile = os.path.join(self.ipythondir, histfname)
1073 self.histfile = os.path.join(self.ipythondir, histfname)
1074
1074
1075 # Fill the history zero entry, user counter starts at 1
1075 # Fill the history zero entry, user counter starts at 1
1076 self.input_hist.append('\n')
1076 self.input_hist.append('\n')
1077 self.input_hist_raw.append('\n')
1077 self.input_hist_raw.append('\n')
1078
1078
1079 def init_shadow_hist(self):
1079 def init_shadow_hist(self):
1080 try:
1080 try:
1081 self.db = pickleshare.PickleShareDB(self.ipythondir + "/db")
1081 self.db = pickleshare.PickleShareDB(self.ipythondir + "/db")
1082 except exceptions.UnicodeDecodeError:
1082 except exceptions.UnicodeDecodeError:
1083 print "Your ipythondir can't be decoded to unicode!"
1083 print "Your ipythondir can't be decoded to unicode!"
1084 print "Please set HOME environment variable to something that"
1084 print "Please set HOME environment variable to something that"
1085 print r"only has ASCII characters, e.g. c:\home"
1085 print r"only has ASCII characters, e.g. c:\home"
1086 print "Now it is", self.ipythondir
1086 print "Now it is", self.ipythondir
1087 sys.exit()
1087 sys.exit()
1088 self.shadowhist = ipcorehist.ShadowHist(self.db)
1088 self.shadowhist = ipcorehist.ShadowHist(self.db)
1089
1089
1090 def savehist(self):
1090 def savehist(self):
1091 """Save input history to a file (via readline library)."""
1091 """Save input history to a file (via readline library)."""
1092
1092
1093 if not self.has_readline:
1093 if not self.has_readline:
1094 return
1094 return
1095
1095
1096 try:
1096 try:
1097 self.readline.write_history_file(self.histfile)
1097 self.readline.write_history_file(self.histfile)
1098 except:
1098 except:
1099 print 'Unable to save IPython command history to file: ' + \
1099 print 'Unable to save IPython command history to file: ' + \
1100 `self.histfile`
1100 `self.histfile`
1101
1101
1102 def reloadhist(self):
1102 def reloadhist(self):
1103 """Reload the input history from disk file."""
1103 """Reload the input history from disk file."""
1104
1104
1105 if self.has_readline:
1105 if self.has_readline:
1106 try:
1106 try:
1107 self.readline.clear_history()
1107 self.readline.clear_history()
1108 self.readline.read_history_file(self.shell.histfile)
1108 self.readline.read_history_file(self.shell.histfile)
1109 except AttributeError:
1109 except AttributeError:
1110 pass
1110 pass
1111
1111
1112 def history_saving_wrapper(self, func):
1112 def history_saving_wrapper(self, func):
1113 """ Wrap func for readline history saving
1113 """ Wrap func for readline history saving
1114
1114
1115 Convert func into callable that saves & restores
1115 Convert func into callable that saves & restores
1116 history around the call """
1116 history around the call """
1117
1117
1118 if not self.has_readline:
1118 if not self.has_readline:
1119 return func
1119 return func
1120
1120
1121 def wrapper():
1121 def wrapper():
1122 self.savehist()
1122 self.savehist()
1123 try:
1123 try:
1124 func()
1124 func()
1125 finally:
1125 finally:
1126 readline.read_history_file(self.histfile)
1126 readline.read_history_file(self.histfile)
1127 return wrapper
1127 return wrapper
1128
1128
1129 #-------------------------------------------------------------------------
1129 #-------------------------------------------------------------------------
1130 # Things related to exception handling and tracebacks (not debugging)
1130 # Things related to exception handling and tracebacks (not debugging)
1131 #-------------------------------------------------------------------------
1131 #-------------------------------------------------------------------------
1132
1132
1133 def init_traceback_handlers(self, custom_exceptions):
1133 def init_traceback_handlers(self, custom_exceptions):
1134 # Syntax error handler.
1134 # Syntax error handler.
1135 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
1135 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
1136
1136
1137 # The interactive one is initialized with an offset, meaning we always
1137 # The interactive one is initialized with an offset, meaning we always
1138 # want to remove the topmost item in the traceback, which is our own
1138 # want to remove the topmost item in the traceback, which is our own
1139 # internal code. Valid modes: ['Plain','Context','Verbose']
1139 # internal code. Valid modes: ['Plain','Context','Verbose']
1140 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1140 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1141 color_scheme='NoColor',
1141 color_scheme='NoColor',
1142 tb_offset = 1)
1142 tb_offset = 1)
1143
1143
1144 # IPython itself shouldn't crash. This will produce a detailed
1144 # IPython itself shouldn't crash. This will produce a detailed
1145 # post-mortem if it does. But we only install the crash handler for
1145 # post-mortem if it does. But we only install the crash handler for
1146 # non-threaded shells, the threaded ones use a normal verbose reporter
1146 # non-threaded shells, the threaded ones use a normal verbose reporter
1147 # and lose the crash handler. This is because exceptions in the main
1147 # and lose the crash handler. This is because exceptions in the main
1148 # thread (such as in GUI code) propagate directly to sys.excepthook,
1148 # thread (such as in GUI code) propagate directly to sys.excepthook,
1149 # and there's no point in printing crash dumps for every user exception.
1149 # and there's no point in printing crash dumps for every user exception.
1150 if self.isthreaded:
1150 if self.isthreaded:
1151 ipCrashHandler = ultratb.FormattedTB()
1151 ipCrashHandler = ultratb.FormattedTB()
1152 else:
1152 else:
1153 from IPython.core import crashhandler
1153 from IPython.core import crashhandler
1154 ipCrashHandler = crashhandler.IPythonCrashHandler(self)
1154 ipCrashHandler = crashhandler.IPythonCrashHandler(self)
1155 self.set_crash_handler(ipCrashHandler)
1155 self.set_crash_handler(ipCrashHandler)
1156
1156
1157 # and add any custom exception handlers the user may have specified
1157 # and add any custom exception handlers the user may have specified
1158 self.set_custom_exc(*custom_exceptions)
1158 self.set_custom_exc(*custom_exceptions)
1159
1159
1160 def set_crash_handler(self, crashHandler):
1160 def set_crash_handler(self, crashHandler):
1161 """Set the IPython crash handler.
1161 """Set the IPython crash handler.
1162
1162
1163 This must be a callable with a signature suitable for use as
1163 This must be a callable with a signature suitable for use as
1164 sys.excepthook."""
1164 sys.excepthook."""
1165
1165
1166 # Install the given crash handler as the Python exception hook
1166 # Install the given crash handler as the Python exception hook
1167 sys.excepthook = crashHandler
1167 sys.excepthook = crashHandler
1168
1168
1169 # The instance will store a pointer to this, so that runtime code
1169 # The instance will store a pointer to this, so that runtime code
1170 # (such as magics) can access it. This is because during the
1170 # (such as magics) can access it. This is because during the
1171 # read-eval loop, it gets temporarily overwritten (to deal with GUI
1171 # read-eval loop, it gets temporarily overwritten (to deal with GUI
1172 # frameworks).
1172 # frameworks).
1173 self.sys_excepthook = sys.excepthook
1173 self.sys_excepthook = sys.excepthook
1174
1174
1175 def set_custom_exc(self,exc_tuple,handler):
1175 def set_custom_exc(self,exc_tuple,handler):
1176 """set_custom_exc(exc_tuple,handler)
1176 """set_custom_exc(exc_tuple,handler)
1177
1177
1178 Set a custom exception handler, which will be called if any of the
1178 Set a custom exception handler, which will be called if any of the
1179 exceptions in exc_tuple occur in the mainloop (specifically, in the
1179 exceptions in exc_tuple occur in the mainloop (specifically, in the
1180 runcode() method.
1180 runcode() method.
1181
1181
1182 Inputs:
1182 Inputs:
1183
1183
1184 - exc_tuple: a *tuple* of valid exceptions to call the defined
1184 - exc_tuple: a *tuple* of valid exceptions to call the defined
1185 handler for. It is very important that you use a tuple, and NOT A
1185 handler for. It is very important that you use a tuple, and NOT A
1186 LIST here, because of the way Python's except statement works. If
1186 LIST here, because of the way Python's except statement works. If
1187 you only want to trap a single exception, use a singleton tuple:
1187 you only want to trap a single exception, use a singleton tuple:
1188
1188
1189 exc_tuple == (MyCustomException,)
1189 exc_tuple == (MyCustomException,)
1190
1190
1191 - handler: this must be defined as a function with the following
1191 - handler: this must be defined as a function with the following
1192 basic interface: def my_handler(self,etype,value,tb).
1192 basic interface: def my_handler(self,etype,value,tb).
1193
1193
1194 This will be made into an instance method (via new.instancemethod)
1194 This will be made into an instance method (via new.instancemethod)
1195 of IPython itself, and it will be called if any of the exceptions
1195 of IPython itself, and it will be called if any of the exceptions
1196 listed in the exc_tuple are caught. If the handler is None, an
1196 listed in the exc_tuple are caught. If the handler is None, an
1197 internal basic one is used, which just prints basic info.
1197 internal basic one is used, which just prints basic info.
1198
1198
1199 WARNING: by putting in your own exception handler into IPython's main
1199 WARNING: by putting in your own exception handler into IPython's main
1200 execution loop, you run a very good chance of nasty crashes. This
1200 execution loop, you run a very good chance of nasty crashes. This
1201 facility should only be used if you really know what you are doing."""
1201 facility should only be used if you really know what you are doing."""
1202
1202
1203 assert type(exc_tuple)==type(()) , \
1203 assert type(exc_tuple)==type(()) , \
1204 "The custom exceptions must be given AS A TUPLE."
1204 "The custom exceptions must be given AS A TUPLE."
1205
1205
1206 def dummy_handler(self,etype,value,tb):
1206 def dummy_handler(self,etype,value,tb):
1207 print '*** Simple custom exception handler ***'
1207 print '*** Simple custom exception handler ***'
1208 print 'Exception type :',etype
1208 print 'Exception type :',etype
1209 print 'Exception value:',value
1209 print 'Exception value:',value
1210 print 'Traceback :',tb
1210 print 'Traceback :',tb
1211 print 'Source code :','\n'.join(self.buffer)
1211 print 'Source code :','\n'.join(self.buffer)
1212
1212
1213 if handler is None: handler = dummy_handler
1213 if handler is None: handler = dummy_handler
1214
1214
1215 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1215 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1216 self.custom_exceptions = exc_tuple
1216 self.custom_exceptions = exc_tuple
1217
1217
1218 def excepthook(self, etype, value, tb):
1218 def excepthook(self, etype, value, tb):
1219 """One more defense for GUI apps that call sys.excepthook.
1219 """One more defense for GUI apps that call sys.excepthook.
1220
1220
1221 GUI frameworks like wxPython trap exceptions and call
1221 GUI frameworks like wxPython trap exceptions and call
1222 sys.excepthook themselves. I guess this is a feature that
1222 sys.excepthook themselves. I guess this is a feature that
1223 enables them to keep running after exceptions that would
1223 enables them to keep running after exceptions that would
1224 otherwise kill their mainloop. This is a bother for IPython
1224 otherwise kill their mainloop. This is a bother for IPython
1225 which excepts to catch all of the program exceptions with a try:
1225 which excepts to catch all of the program exceptions with a try:
1226 except: statement.
1226 except: statement.
1227
1227
1228 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1228 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1229 any app directly invokes sys.excepthook, it will look to the user like
1229 any app directly invokes sys.excepthook, it will look to the user like
1230 IPython crashed. In order to work around this, we can disable the
1230 IPython crashed. In order to work around this, we can disable the
1231 CrashHandler and replace it with this excepthook instead, which prints a
1231 CrashHandler and replace it with this excepthook instead, which prints a
1232 regular traceback using our InteractiveTB. In this fashion, apps which
1232 regular traceback using our InteractiveTB. In this fashion, apps which
1233 call sys.excepthook will generate a regular-looking exception from
1233 call sys.excepthook will generate a regular-looking exception from
1234 IPython, and the CrashHandler will only be triggered by real IPython
1234 IPython, and the CrashHandler will only be triggered by real IPython
1235 crashes.
1235 crashes.
1236
1236
1237 This hook should be used sparingly, only in places which are not likely
1237 This hook should be used sparingly, only in places which are not likely
1238 to be true IPython errors.
1238 to be true IPython errors.
1239 """
1239 """
1240 self.showtraceback((etype,value,tb),tb_offset=0)
1240 self.showtraceback((etype,value,tb),tb_offset=0)
1241
1241
1242 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1242 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1243 """Display the exception that just occurred.
1243 """Display the exception that just occurred.
1244
1244
1245 If nothing is known about the exception, this is the method which
1245 If nothing is known about the exception, this is the method which
1246 should be used throughout the code for presenting user tracebacks,
1246 should be used throughout the code for presenting user tracebacks,
1247 rather than directly invoking the InteractiveTB object.
1247 rather than directly invoking the InteractiveTB object.
1248
1248
1249 A specific showsyntaxerror() also exists, but this method can take
1249 A specific showsyntaxerror() also exists, but this method can take
1250 care of calling it if needed, so unless you are explicitly catching a
1250 care of calling it if needed, so unless you are explicitly catching a
1251 SyntaxError exception, don't try to analyze the stack manually and
1251 SyntaxError exception, don't try to analyze the stack manually and
1252 simply call this method."""
1252 simply call this method."""
1253
1253
1254
1254
1255 # Though this won't be called by syntax errors in the input line,
1255 # Though this won't be called by syntax errors in the input line,
1256 # there may be SyntaxError cases whith imported code.
1256 # there may be SyntaxError cases whith imported code.
1257
1257
1258 try:
1258 try:
1259 if exc_tuple is None:
1259 if exc_tuple is None:
1260 etype, value, tb = sys.exc_info()
1260 etype, value, tb = sys.exc_info()
1261 else:
1261 else:
1262 etype, value, tb = exc_tuple
1262 etype, value, tb = exc_tuple
1263
1263
1264 if etype is SyntaxError:
1264 if etype is SyntaxError:
1265 self.showsyntaxerror(filename)
1265 self.showsyntaxerror(filename)
1266 elif etype is UsageError:
1266 elif etype is UsageError:
1267 print "UsageError:", value
1267 print "UsageError:", value
1268 else:
1268 else:
1269 # WARNING: these variables are somewhat deprecated and not
1269 # WARNING: these variables are somewhat deprecated and not
1270 # necessarily safe to use in a threaded environment, but tools
1270 # necessarily safe to use in a threaded environment, but tools
1271 # like pdb depend on their existence, so let's set them. If we
1271 # like pdb depend on their existence, so let's set them. If we
1272 # find problems in the field, we'll need to revisit their use.
1272 # find problems in the field, we'll need to revisit their use.
1273 sys.last_type = etype
1273 sys.last_type = etype
1274 sys.last_value = value
1274 sys.last_value = value
1275 sys.last_traceback = tb
1275 sys.last_traceback = tb
1276
1276
1277 if etype in self.custom_exceptions:
1277 if etype in self.custom_exceptions:
1278 self.CustomTB(etype,value,tb)
1278 self.CustomTB(etype,value,tb)
1279 else:
1279 else:
1280 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1280 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1281 if self.InteractiveTB.call_pdb and self.has_readline:
1281 if self.InteractiveTB.call_pdb and self.has_readline:
1282 # pdb mucks up readline, fix it back
1282 # pdb mucks up readline, fix it back
1283 self.set_completer()
1283 self.set_completer()
1284 except KeyboardInterrupt:
1284 except KeyboardInterrupt:
1285 self.write("\nKeyboardInterrupt\n")
1285 self.write("\nKeyboardInterrupt\n")
1286
1286
1287 def showsyntaxerror(self, filename=None):
1287 def showsyntaxerror(self, filename=None):
1288 """Display the syntax error that just occurred.
1288 """Display the syntax error that just occurred.
1289
1289
1290 This doesn't display a stack trace because there isn't one.
1290 This doesn't display a stack trace because there isn't one.
1291
1291
1292 If a filename is given, it is stuffed in the exception instead
1292 If a filename is given, it is stuffed in the exception instead
1293 of what was there before (because Python's parser always uses
1293 of what was there before (because Python's parser always uses
1294 "<string>" when reading from a string).
1294 "<string>" when reading from a string).
1295 """
1295 """
1296 etype, value, last_traceback = sys.exc_info()
1296 etype, value, last_traceback = sys.exc_info()
1297
1297
1298 # See note about these variables in showtraceback() below
1298 # See note about these variables in showtraceback() below
1299 sys.last_type = etype
1299 sys.last_type = etype
1300 sys.last_value = value
1300 sys.last_value = value
1301 sys.last_traceback = last_traceback
1301 sys.last_traceback = last_traceback
1302
1302
1303 if filename and etype is SyntaxError:
1303 if filename and etype is SyntaxError:
1304 # Work hard to stuff the correct filename in the exception
1304 # Work hard to stuff the correct filename in the exception
1305 try:
1305 try:
1306 msg, (dummy_filename, lineno, offset, line) = value
1306 msg, (dummy_filename, lineno, offset, line) = value
1307 except:
1307 except:
1308 # Not the format we expect; leave it alone
1308 # Not the format we expect; leave it alone
1309 pass
1309 pass
1310 else:
1310 else:
1311 # Stuff in the right filename
1311 # Stuff in the right filename
1312 try:
1312 try:
1313 # Assume SyntaxError is a class exception
1313 # Assume SyntaxError is a class exception
1314 value = SyntaxError(msg, (filename, lineno, offset, line))
1314 value = SyntaxError(msg, (filename, lineno, offset, line))
1315 except:
1315 except:
1316 # If that failed, assume SyntaxError is a string
1316 # If that failed, assume SyntaxError is a string
1317 value = msg, (filename, lineno, offset, line)
1317 value = msg, (filename, lineno, offset, line)
1318 self.SyntaxTB(etype,value,[])
1318 self.SyntaxTB(etype,value,[])
1319
1319
1320 def edit_syntax_error(self):
1320 def edit_syntax_error(self):
1321 """The bottom half of the syntax error handler called in the main loop.
1321 """The bottom half of the syntax error handler called in the main loop.
1322
1322
1323 Loop until syntax error is fixed or user cancels.
1323 Loop until syntax error is fixed or user cancels.
1324 """
1324 """
1325
1325
1326 while self.SyntaxTB.last_syntax_error:
1326 while self.SyntaxTB.last_syntax_error:
1327 # copy and clear last_syntax_error
1327 # copy and clear last_syntax_error
1328 err = self.SyntaxTB.clear_err_state()
1328 err = self.SyntaxTB.clear_err_state()
1329 if not self._should_recompile(err):
1329 if not self._should_recompile(err):
1330 return
1330 return
1331 try:
1331 try:
1332 # may set last_syntax_error again if a SyntaxError is raised
1332 # may set last_syntax_error again if a SyntaxError is raised
1333 self.safe_execfile(err.filename,self.user_ns)
1333 self.safe_execfile(err.filename,self.user_ns)
1334 except:
1334 except:
1335 self.showtraceback()
1335 self.showtraceback()
1336 else:
1336 else:
1337 try:
1337 try:
1338 f = file(err.filename)
1338 f = file(err.filename)
1339 try:
1339 try:
1340 # This should be inside a display_trap block and I
1340 # This should be inside a display_trap block and I
1341 # think it is.
1341 # think it is.
1342 sys.displayhook(f.read())
1342 sys.displayhook(f.read())
1343 finally:
1343 finally:
1344 f.close()
1344 f.close()
1345 except:
1345 except:
1346 self.showtraceback()
1346 self.showtraceback()
1347
1347
1348 def _should_recompile(self,e):
1348 def _should_recompile(self,e):
1349 """Utility routine for edit_syntax_error"""
1349 """Utility routine for edit_syntax_error"""
1350
1350
1351 if e.filename in ('<ipython console>','<input>','<string>',
1351 if e.filename in ('<ipython console>','<input>','<string>',
1352 '<console>','<BackgroundJob compilation>',
1352 '<console>','<BackgroundJob compilation>',
1353 None):
1353 None):
1354
1354
1355 return False
1355 return False
1356 try:
1356 try:
1357 if (self.autoedit_syntax and
1357 if (self.autoedit_syntax and
1358 not self.ask_yes_no('Return to editor to correct syntax error? '
1358 not self.ask_yes_no('Return to editor to correct syntax error? '
1359 '[Y/n] ','y')):
1359 '[Y/n] ','y')):
1360 return False
1360 return False
1361 except EOFError:
1361 except EOFError:
1362 return False
1362 return False
1363
1363
1364 def int0(x):
1364 def int0(x):
1365 try:
1365 try:
1366 return int(x)
1366 return int(x)
1367 except TypeError:
1367 except TypeError:
1368 return 0
1368 return 0
1369 # always pass integer line and offset values to editor hook
1369 # always pass integer line and offset values to editor hook
1370 try:
1370 try:
1371 self.hooks.fix_error_editor(e.filename,
1371 self.hooks.fix_error_editor(e.filename,
1372 int0(e.lineno),int0(e.offset),e.msg)
1372 int0(e.lineno),int0(e.offset),e.msg)
1373 except TryNext:
1373 except TryNext:
1374 warn('Could not open editor')
1374 warn('Could not open editor')
1375 return False
1375 return False
1376 return True
1376 return True
1377
1377
1378 #-------------------------------------------------------------------------
1378 #-------------------------------------------------------------------------
1379 # Things related to tab completion
1379 # Things related to tab completion
1380 #-------------------------------------------------------------------------
1380 #-------------------------------------------------------------------------
1381
1381
1382 def complete(self, text):
1382 def complete(self, text):
1383 """Return a sorted list of all possible completions on text.
1383 """Return a sorted list of all possible completions on text.
1384
1384
1385 Inputs:
1385 Inputs:
1386
1386
1387 - text: a string of text to be completed on.
1387 - text: a string of text to be completed on.
1388
1388
1389 This is a wrapper around the completion mechanism, similar to what
1389 This is a wrapper around the completion mechanism, similar to what
1390 readline does at the command line when the TAB key is hit. By
1390 readline does at the command line when the TAB key is hit. By
1391 exposing it as a method, it can be used by other non-readline
1391 exposing it as a method, it can be used by other non-readline
1392 environments (such as GUIs) for text completion.
1392 environments (such as GUIs) for text completion.
1393
1393
1394 Simple usage example:
1394 Simple usage example:
1395
1395
1396 In [7]: x = 'hello'
1396 In [7]: x = 'hello'
1397
1397
1398 In [8]: x
1398 In [8]: x
1399 Out[8]: 'hello'
1399 Out[8]: 'hello'
1400
1400
1401 In [9]: print x
1401 In [9]: print x
1402 hello
1402 hello
1403
1403
1404 In [10]: _ip.complete('x.l')
1404 In [10]: _ip.complete('x.l')
1405 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1405 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1406 """
1406 """
1407
1407
1408 # Inject names into __builtin__ so we can complete on the added names.
1408 # Inject names into __builtin__ so we can complete on the added names.
1409 with self.builtin_trap:
1409 with self.builtin_trap:
1410 complete = self.Completer.complete
1410 complete = self.Completer.complete
1411 state = 0
1411 state = 0
1412 # use a dict so we get unique keys, since ipyhton's multiple
1412 # use a dict so we get unique keys, since ipyhton's multiple
1413 # completers can return duplicates. When we make 2.4 a requirement,
1413 # completers can return duplicates. When we make 2.4 a requirement,
1414 # start using sets instead, which are faster.
1414 # start using sets instead, which are faster.
1415 comps = {}
1415 comps = {}
1416 while True:
1416 while True:
1417 newcomp = complete(text,state,line_buffer=text)
1417 newcomp = complete(text,state,line_buffer=text)
1418 if newcomp is None:
1418 if newcomp is None:
1419 break
1419 break
1420 comps[newcomp] = 1
1420 comps[newcomp] = 1
1421 state += 1
1421 state += 1
1422 outcomps = comps.keys()
1422 outcomps = comps.keys()
1423 outcomps.sort()
1423 outcomps.sort()
1424 #print "T:",text,"OC:",outcomps # dbg
1424 #print "T:",text,"OC:",outcomps # dbg
1425 #print "vars:",self.user_ns.keys()
1425 #print "vars:",self.user_ns.keys()
1426 return outcomps
1426 return outcomps
1427
1427
1428 def set_custom_completer(self,completer,pos=0):
1428 def set_custom_completer(self,completer,pos=0):
1429 """set_custom_completer(completer,pos=0)
1429 """set_custom_completer(completer,pos=0)
1430
1430
1431 Adds a new custom completer function.
1431 Adds a new custom completer function.
1432
1432
1433 The position argument (defaults to 0) is the index in the completers
1433 The position argument (defaults to 0) is the index in the completers
1434 list where you want the completer to be inserted."""
1434 list where you want the completer to be inserted."""
1435
1435
1436 newcomp = new.instancemethod(completer,self.Completer,
1436 newcomp = new.instancemethod(completer,self.Completer,
1437 self.Completer.__class__)
1437 self.Completer.__class__)
1438 self.Completer.matchers.insert(pos,newcomp)
1438 self.Completer.matchers.insert(pos,newcomp)
1439
1439
1440 def set_completer(self):
1440 def set_completer(self):
1441 """reset readline's completer to be our own."""
1441 """reset readline's completer to be our own."""
1442 self.readline.set_completer(self.Completer.complete)
1442 self.readline.set_completer(self.Completer.complete)
1443
1443
1444 #-------------------------------------------------------------------------
1444 #-------------------------------------------------------------------------
1445 # Things related to readline
1445 # Things related to readline
1446 #-------------------------------------------------------------------------
1446 #-------------------------------------------------------------------------
1447
1447
1448 def init_readline(self):
1448 def init_readline(self):
1449 """Command history completion/saving/reloading."""
1449 """Command history completion/saving/reloading."""
1450
1450
1451 self.rl_next_input = None
1451 self.rl_next_input = None
1452 self.rl_do_indent = False
1452 self.rl_do_indent = False
1453
1453
1454 if not self.readline_use:
1454 if not self.readline_use:
1455 return
1455 return
1456
1456
1457 import IPython.utils.rlineimpl as readline
1457 import IPython.utils.rlineimpl as readline
1458
1458
1459 if not readline.have_readline:
1459 if not readline.have_readline:
1460 self.has_readline = 0
1460 self.has_readline = 0
1461 self.readline = None
1461 self.readline = None
1462 # no point in bugging windows users with this every time:
1462 # no point in bugging windows users with this every time:
1463 warn('Readline services not available on this platform.')
1463 warn('Readline services not available on this platform.')
1464 else:
1464 else:
1465 sys.modules['readline'] = readline
1465 sys.modules['readline'] = readline
1466 import atexit
1466 import atexit
1467 from IPython.core.completer import IPCompleter
1467 from IPython.core.completer import IPCompleter
1468 self.Completer = IPCompleter(self,
1468 self.Completer = IPCompleter(self,
1469 self.user_ns,
1469 self.user_ns,
1470 self.user_global_ns,
1470 self.user_global_ns,
1471 self.readline_omit__names,
1471 self.readline_omit__names,
1472 self.alias_manager.alias_table)
1472 self.alias_manager.alias_table)
1473 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1473 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1474 self.strdispatchers['complete_command'] = sdisp
1474 self.strdispatchers['complete_command'] = sdisp
1475 self.Completer.custom_completers = sdisp
1475 self.Completer.custom_completers = sdisp
1476 # Platform-specific configuration
1476 # Platform-specific configuration
1477 if os.name == 'nt':
1477 if os.name == 'nt':
1478 self.readline_startup_hook = readline.set_pre_input_hook
1478 self.readline_startup_hook = readline.set_pre_input_hook
1479 else:
1479 else:
1480 self.readline_startup_hook = readline.set_startup_hook
1480 self.readline_startup_hook = readline.set_startup_hook
1481
1481
1482 # Load user's initrc file (readline config)
1482 # Load user's initrc file (readline config)
1483 # Or if libedit is used, load editrc.
1483 # Or if libedit is used, load editrc.
1484 inputrc_name = os.environ.get('INPUTRC')
1484 inputrc_name = os.environ.get('INPUTRC')
1485 if inputrc_name is None:
1485 if inputrc_name is None:
1486 home_dir = get_home_dir()
1486 home_dir = get_home_dir()
1487 if home_dir is not None:
1487 if home_dir is not None:
1488 inputrc_name = '.inputrc'
1488 inputrc_name = '.inputrc'
1489 if readline.uses_libedit:
1489 if readline.uses_libedit:
1490 inputrc_name = '.editrc'
1490 inputrc_name = '.editrc'
1491 inputrc_name = os.path.join(home_dir, inputrc_name)
1491 inputrc_name = os.path.join(home_dir, inputrc_name)
1492 if os.path.isfile(inputrc_name):
1492 if os.path.isfile(inputrc_name):
1493 try:
1493 try:
1494 readline.read_init_file(inputrc_name)
1494 readline.read_init_file(inputrc_name)
1495 except:
1495 except:
1496 warn('Problems reading readline initialization file <%s>'
1496 warn('Problems reading readline initialization file <%s>'
1497 % inputrc_name)
1497 % inputrc_name)
1498
1498
1499 self.has_readline = 1
1499 self.has_readline = 1
1500 self.readline = readline
1500 self.readline = readline
1501 # save this in sys so embedded copies can restore it properly
1501 # save this in sys so embedded copies can restore it properly
1502 sys.ipcompleter = self.Completer.complete
1502 sys.ipcompleter = self.Completer.complete
1503 self.set_completer()
1503 self.set_completer()
1504
1504
1505 # Configure readline according to user's prefs
1505 # Configure readline according to user's prefs
1506 # This is only done if GNU readline is being used. If libedit
1506 # This is only done if GNU readline is being used. If libedit
1507 # is being used (as on Leopard) the readline config is
1507 # is being used (as on Leopard) the readline config is
1508 # not run as the syntax for libedit is different.
1508 # not run as the syntax for libedit is different.
1509 if not readline.uses_libedit:
1509 if not readline.uses_libedit:
1510 for rlcommand in self.readline_parse_and_bind:
1510 for rlcommand in self.readline_parse_and_bind:
1511 #print "loading rl:",rlcommand # dbg
1511 #print "loading rl:",rlcommand # dbg
1512 readline.parse_and_bind(rlcommand)
1512 readline.parse_and_bind(rlcommand)
1513
1513
1514 # Remove some chars from the delimiters list. If we encounter
1514 # Remove some chars from the delimiters list. If we encounter
1515 # unicode chars, discard them.
1515 # unicode chars, discard them.
1516 delims = readline.get_completer_delims().encode("ascii", "ignore")
1516 delims = readline.get_completer_delims().encode("ascii", "ignore")
1517 delims = delims.translate(string._idmap,
1517 delims = delims.translate(string._idmap,
1518 self.readline_remove_delims)
1518 self.readline_remove_delims)
1519 readline.set_completer_delims(delims)
1519 readline.set_completer_delims(delims)
1520 # otherwise we end up with a monster history after a while:
1520 # otherwise we end up with a monster history after a while:
1521 readline.set_history_length(1000)
1521 readline.set_history_length(1000)
1522 try:
1522 try:
1523 #print '*** Reading readline history' # dbg
1523 #print '*** Reading readline history' # dbg
1524 readline.read_history_file(self.histfile)
1524 readline.read_history_file(self.histfile)
1525 except IOError:
1525 except IOError:
1526 pass # It doesn't exist yet.
1526 pass # It doesn't exist yet.
1527
1527
1528 atexit.register(self.atexit_operations)
1528 atexit.register(self.atexit_operations)
1529 del atexit
1529 del atexit
1530
1530
1531 # Configure auto-indent for all platforms
1531 # Configure auto-indent for all platforms
1532 self.set_autoindent(self.autoindent)
1532 self.set_autoindent(self.autoindent)
1533
1533
1534 def set_next_input(self, s):
1534 def set_next_input(self, s):
1535 """ Sets the 'default' input string for the next command line.
1535 """ Sets the 'default' input string for the next command line.
1536
1536
1537 Requires readline.
1537 Requires readline.
1538
1538
1539 Example:
1539 Example:
1540
1540
1541 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1541 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1542 [D:\ipython]|2> Hello Word_ # cursor is here
1542 [D:\ipython]|2> Hello Word_ # cursor is here
1543 """
1543 """
1544
1544
1545 self.rl_next_input = s
1545 self.rl_next_input = s
1546
1546
1547 def pre_readline(self):
1547 def pre_readline(self):
1548 """readline hook to be used at the start of each line.
1548 """readline hook to be used at the start of each line.
1549
1549
1550 Currently it handles auto-indent only."""
1550 Currently it handles auto-indent only."""
1551
1551
1552 #debugx('self.indent_current_nsp','pre_readline:')
1552 #debugx('self.indent_current_nsp','pre_readline:')
1553
1553
1554 if self.rl_do_indent:
1554 if self.rl_do_indent:
1555 self.readline.insert_text(self._indent_current_str())
1555 self.readline.insert_text(self._indent_current_str())
1556 if self.rl_next_input is not None:
1556 if self.rl_next_input is not None:
1557 self.readline.insert_text(self.rl_next_input)
1557 self.readline.insert_text(self.rl_next_input)
1558 self.rl_next_input = None
1558 self.rl_next_input = None
1559
1559
1560 def _indent_current_str(self):
1560 def _indent_current_str(self):
1561 """return the current level of indentation as a string"""
1561 """return the current level of indentation as a string"""
1562 return self.indent_current_nsp * ' '
1562 return self.indent_current_nsp * ' '
1563
1563
1564 #-------------------------------------------------------------------------
1564 #-------------------------------------------------------------------------
1565 # Things related to magics
1565 # Things related to magics
1566 #-------------------------------------------------------------------------
1566 #-------------------------------------------------------------------------
1567
1567
1568 def init_magics(self):
1568 def init_magics(self):
1569 # Set user colors (don't do it in the constructor above so that it
1569 # Set user colors (don't do it in the constructor above so that it
1570 # doesn't crash if colors option is invalid)
1570 # doesn't crash if colors option is invalid)
1571 self.magic_colors(self.colors)
1571 self.magic_colors(self.colors)
1572
1572
1573 def magic(self,arg_s):
1573 def magic(self,arg_s):
1574 """Call a magic function by name.
1574 """Call a magic function by name.
1575
1575
1576 Input: a string containing the name of the magic function to call and any
1576 Input: a string containing the name of the magic function to call and any
1577 additional arguments to be passed to the magic.
1577 additional arguments to be passed to the magic.
1578
1578
1579 magic('name -opt foo bar') is equivalent to typing at the ipython
1579 magic('name -opt foo bar') is equivalent to typing at the ipython
1580 prompt:
1580 prompt:
1581
1581
1582 In[1]: %name -opt foo bar
1582 In[1]: %name -opt foo bar
1583
1583
1584 To call a magic without arguments, simply use magic('name').
1584 To call a magic without arguments, simply use magic('name').
1585
1585
1586 This provides a proper Python function to call IPython's magics in any
1586 This provides a proper Python function to call IPython's magics in any
1587 valid Python code you can type at the interpreter, including loops and
1587 valid Python code you can type at the interpreter, including loops and
1588 compound statements.
1588 compound statements.
1589 """
1589 """
1590
1590
1591 args = arg_s.split(' ',1)
1591 args = arg_s.split(' ',1)
1592 magic_name = args[0]
1592 magic_name = args[0]
1593 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1593 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1594
1594
1595 try:
1595 try:
1596 magic_args = args[1]
1596 magic_args = args[1]
1597 except IndexError:
1597 except IndexError:
1598 magic_args = ''
1598 magic_args = ''
1599 fn = getattr(self,'magic_'+magic_name,None)
1599 fn = getattr(self,'magic_'+magic_name,None)
1600 if fn is None:
1600 if fn is None:
1601 error("Magic function `%s` not found." % magic_name)
1601 error("Magic function `%s` not found." % magic_name)
1602 else:
1602 else:
1603 magic_args = self.var_expand(magic_args,1)
1603 magic_args = self.var_expand(magic_args,1)
1604 with nested(self.builtin_trap,):
1604 with nested(self.builtin_trap,):
1605 return fn(magic_args)
1605 result = fn(magic_args)
1606 # Unfortunately, the return statement is what will trigger
1606 return result
1607 # the displayhook, but it is no longer set!
1608 # return result
1609
1607
1610 def define_magic(self, magicname, func):
1608 def define_magic(self, magicname, func):
1611 """Expose own function as magic function for ipython
1609 """Expose own function as magic function for ipython
1612
1610
1613 def foo_impl(self,parameter_s=''):
1611 def foo_impl(self,parameter_s=''):
1614 'My very own magic!. (Use docstrings, IPython reads them).'
1612 'My very own magic!. (Use docstrings, IPython reads them).'
1615 print 'Magic function. Passed parameter is between < >:'
1613 print 'Magic function. Passed parameter is between < >:'
1616 print '<%s>' % parameter_s
1614 print '<%s>' % parameter_s
1617 print 'The self object is:',self
1615 print 'The self object is:',self
1618
1616
1619 self.define_magic('foo',foo_impl)
1617 self.define_magic('foo',foo_impl)
1620 """
1618 """
1621
1619
1622 import new
1620 import new
1623 im = new.instancemethod(func,self, self.__class__)
1621 im = new.instancemethod(func,self, self.__class__)
1624 old = getattr(self, "magic_" + magicname, None)
1622 old = getattr(self, "magic_" + magicname, None)
1625 setattr(self, "magic_" + magicname, im)
1623 setattr(self, "magic_" + magicname, im)
1626 return old
1624 return old
1627
1625
1628 #-------------------------------------------------------------------------
1626 #-------------------------------------------------------------------------
1629 # Things related to macros
1627 # Things related to macros
1630 #-------------------------------------------------------------------------
1628 #-------------------------------------------------------------------------
1631
1629
1632 def define_macro(self, name, themacro):
1630 def define_macro(self, name, themacro):
1633 """Define a new macro
1631 """Define a new macro
1634
1632
1635 Parameters
1633 Parameters
1636 ----------
1634 ----------
1637 name : str
1635 name : str
1638 The name of the macro.
1636 The name of the macro.
1639 themacro : str or Macro
1637 themacro : str or Macro
1640 The action to do upon invoking the macro. If a string, a new
1638 The action to do upon invoking the macro. If a string, a new
1641 Macro object is created by passing the string to it.
1639 Macro object is created by passing the string to it.
1642 """
1640 """
1643
1641
1644 from IPython.core import macro
1642 from IPython.core import macro
1645
1643
1646 if isinstance(themacro, basestring):
1644 if isinstance(themacro, basestring):
1647 themacro = macro.Macro(themacro)
1645 themacro = macro.Macro(themacro)
1648 if not isinstance(themacro, macro.Macro):
1646 if not isinstance(themacro, macro.Macro):
1649 raise ValueError('A macro must be a string or a Macro instance.')
1647 raise ValueError('A macro must be a string or a Macro instance.')
1650 self.user_ns[name] = themacro
1648 self.user_ns[name] = themacro
1651
1649
1652 #-------------------------------------------------------------------------
1650 #-------------------------------------------------------------------------
1653 # Things related to the running of system commands
1651 # Things related to the running of system commands
1654 #-------------------------------------------------------------------------
1652 #-------------------------------------------------------------------------
1655
1653
1656 def system(self, cmd):
1654 def system(self, cmd):
1657 """Make a system call, using IPython."""
1655 """Make a system call, using IPython."""
1658 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1656 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1659
1657
1660 #-------------------------------------------------------------------------
1658 #-------------------------------------------------------------------------
1661 # Things related to aliases
1659 # Things related to aliases
1662 #-------------------------------------------------------------------------
1660 #-------------------------------------------------------------------------
1663
1661
1664 def init_alias(self):
1662 def init_alias(self):
1665 self.alias_manager = AliasManager(self, config=self.config)
1663 self.alias_manager = AliasManager(self, config=self.config)
1666 self.ns_table['alias'] = self.alias_manager.alias_table,
1664 self.ns_table['alias'] = self.alias_manager.alias_table,
1667
1665
1668 #-------------------------------------------------------------------------
1666 #-------------------------------------------------------------------------
1669 # Things related to the running of code
1667 # Things related to the running of code
1670 #-------------------------------------------------------------------------
1668 #-------------------------------------------------------------------------
1671
1669
1672 def ex(self, cmd):
1670 def ex(self, cmd):
1673 """Execute a normal python statement in user namespace."""
1671 """Execute a normal python statement in user namespace."""
1674 with nested(self.builtin_trap,):
1672 with nested(self.builtin_trap,):
1675 exec cmd in self.user_global_ns, self.user_ns
1673 exec cmd in self.user_global_ns, self.user_ns
1676
1674
1677 def ev(self, expr):
1675 def ev(self, expr):
1678 """Evaluate python expression expr in user namespace.
1676 """Evaluate python expression expr in user namespace.
1679
1677
1680 Returns the result of evaluation
1678 Returns the result of evaluation
1681 """
1679 """
1682 with nested(self.builtin_trap,):
1680 with nested(self.builtin_trap,):
1683 return eval(expr, self.user_global_ns, self.user_ns)
1681 return eval(expr, self.user_global_ns, self.user_ns)
1684
1682
1685 def mainloop(self, display_banner=None):
1683 def mainloop(self, display_banner=None):
1686 """Start the mainloop.
1684 """Start the mainloop.
1687
1685
1688 If an optional banner argument is given, it will override the
1686 If an optional banner argument is given, it will override the
1689 internally created default banner.
1687 internally created default banner.
1690 """
1688 """
1691
1689
1692 with nested(self.builtin_trap, self.display_trap):
1690 with nested(self.builtin_trap, self.display_trap):
1693
1691
1694 # if you run stuff with -c <cmd>, raw hist is not updated
1692 # if you run stuff with -c <cmd>, raw hist is not updated
1695 # ensure that it's in sync
1693 # ensure that it's in sync
1696 if len(self.input_hist) != len (self.input_hist_raw):
1694 if len(self.input_hist) != len (self.input_hist_raw):
1697 self.input_hist_raw = InputList(self.input_hist)
1695 self.input_hist_raw = InputList(self.input_hist)
1698
1696
1699 while 1:
1697 while 1:
1700 try:
1698 try:
1701 self.interact(display_banner=display_banner)
1699 self.interact(display_banner=display_banner)
1702 #self.interact_with_readline()
1700 #self.interact_with_readline()
1703 # XXX for testing of a readline-decoupled repl loop, call
1701 # XXX for testing of a readline-decoupled repl loop, call
1704 # interact_with_readline above
1702 # interact_with_readline above
1705 break
1703 break
1706 except KeyboardInterrupt:
1704 except KeyboardInterrupt:
1707 # this should not be necessary, but KeyboardInterrupt
1705 # this should not be necessary, but KeyboardInterrupt
1708 # handling seems rather unpredictable...
1706 # handling seems rather unpredictable...
1709 self.write("\nKeyboardInterrupt in interact()\n")
1707 self.write("\nKeyboardInterrupt in interact()\n")
1710
1708
1711 def interact_prompt(self):
1709 def interact_prompt(self):
1712 """ Print the prompt (in read-eval-print loop)
1710 """ Print the prompt (in read-eval-print loop)
1713
1711
1714 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1712 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1715 used in standard IPython flow.
1713 used in standard IPython flow.
1716 """
1714 """
1717 if self.more:
1715 if self.more:
1718 try:
1716 try:
1719 prompt = self.hooks.generate_prompt(True)
1717 prompt = self.hooks.generate_prompt(True)
1720 except:
1718 except:
1721 self.showtraceback()
1719 self.showtraceback()
1722 if self.autoindent:
1720 if self.autoindent:
1723 self.rl_do_indent = True
1721 self.rl_do_indent = True
1724
1722
1725 else:
1723 else:
1726 try:
1724 try:
1727 prompt = self.hooks.generate_prompt(False)
1725 prompt = self.hooks.generate_prompt(False)
1728 except:
1726 except:
1729 self.showtraceback()
1727 self.showtraceback()
1730 self.write(prompt)
1728 self.write(prompt)
1731
1729
1732 def interact_handle_input(self,line):
1730 def interact_handle_input(self,line):
1733 """ Handle the input line (in read-eval-print loop)
1731 """ Handle the input line (in read-eval-print loop)
1734
1732
1735 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1733 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1736 used in standard IPython flow.
1734 used in standard IPython flow.
1737 """
1735 """
1738 if line.lstrip() == line:
1736 if line.lstrip() == line:
1739 self.shadowhist.add(line.strip())
1737 self.shadowhist.add(line.strip())
1740 lineout = self.prefilter_manager.prefilter_lines(line,self.more)
1738 lineout = self.prefilter_manager.prefilter_lines(line,self.more)
1741
1739
1742 if line.strip():
1740 if line.strip():
1743 if self.more:
1741 if self.more:
1744 self.input_hist_raw[-1] += '%s\n' % line
1742 self.input_hist_raw[-1] += '%s\n' % line
1745 else:
1743 else:
1746 self.input_hist_raw.append('%s\n' % line)
1744 self.input_hist_raw.append('%s\n' % line)
1747
1745
1748
1746
1749 self.more = self.push_line(lineout)
1747 self.more = self.push_line(lineout)
1750 if (self.SyntaxTB.last_syntax_error and
1748 if (self.SyntaxTB.last_syntax_error and
1751 self.autoedit_syntax):
1749 self.autoedit_syntax):
1752 self.edit_syntax_error()
1750 self.edit_syntax_error()
1753
1751
1754 def interact_with_readline(self):
1752 def interact_with_readline(self):
1755 """ Demo of using interact_handle_input, interact_prompt
1753 """ Demo of using interact_handle_input, interact_prompt
1756
1754
1757 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1755 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1758 it should work like this.
1756 it should work like this.
1759 """
1757 """
1760 self.readline_startup_hook(self.pre_readline)
1758 self.readline_startup_hook(self.pre_readline)
1761 while not self.exit_now:
1759 while not self.exit_now:
1762 self.interact_prompt()
1760 self.interact_prompt()
1763 if self.more:
1761 if self.more:
1764 self.rl_do_indent = True
1762 self.rl_do_indent = True
1765 else:
1763 else:
1766 self.rl_do_indent = False
1764 self.rl_do_indent = False
1767 line = raw_input_original().decode(self.stdin_encoding)
1765 line = raw_input_original().decode(self.stdin_encoding)
1768 self.interact_handle_input(line)
1766 self.interact_handle_input(line)
1769
1767
1770 def interact(self, display_banner=None):
1768 def interact(self, display_banner=None):
1771 """Closely emulate the interactive Python console."""
1769 """Closely emulate the interactive Python console."""
1772
1770
1773 # batch run -> do not interact
1771 # batch run -> do not interact
1774 if self.exit_now:
1772 if self.exit_now:
1775 return
1773 return
1776
1774
1777 if display_banner is None:
1775 if display_banner is None:
1778 display_banner = self.display_banner
1776 display_banner = self.display_banner
1779 if display_banner:
1777 if display_banner:
1780 self.show_banner()
1778 self.show_banner()
1781
1779
1782 more = 0
1780 more = 0
1783
1781
1784 # Mark activity in the builtins
1782 # Mark activity in the builtins
1785 __builtin__.__dict__['__IPYTHON__active'] += 1
1783 __builtin__.__dict__['__IPYTHON__active'] += 1
1786
1784
1787 if self.has_readline:
1785 if self.has_readline:
1788 self.readline_startup_hook(self.pre_readline)
1786 self.readline_startup_hook(self.pre_readline)
1789 # exit_now is set by a call to %Exit or %Quit, through the
1787 # exit_now is set by a call to %Exit or %Quit, through the
1790 # ask_exit callback.
1788 # ask_exit callback.
1791
1789
1792 while not self.exit_now:
1790 while not self.exit_now:
1793 self.hooks.pre_prompt_hook()
1791 self.hooks.pre_prompt_hook()
1794 if more:
1792 if more:
1795 try:
1793 try:
1796 prompt = self.hooks.generate_prompt(True)
1794 prompt = self.hooks.generate_prompt(True)
1797 except:
1795 except:
1798 self.showtraceback()
1796 self.showtraceback()
1799 if self.autoindent:
1797 if self.autoindent:
1800 self.rl_do_indent = True
1798 self.rl_do_indent = True
1801
1799
1802 else:
1800 else:
1803 try:
1801 try:
1804 prompt = self.hooks.generate_prompt(False)
1802 prompt = self.hooks.generate_prompt(False)
1805 except:
1803 except:
1806 self.showtraceback()
1804 self.showtraceback()
1807 try:
1805 try:
1808 line = self.raw_input(prompt, more)
1806 line = self.raw_input(prompt, more)
1809 if self.exit_now:
1807 if self.exit_now:
1810 # quick exit on sys.std[in|out] close
1808 # quick exit on sys.std[in|out] close
1811 break
1809 break
1812 if self.autoindent:
1810 if self.autoindent:
1813 self.rl_do_indent = False
1811 self.rl_do_indent = False
1814
1812
1815 except KeyboardInterrupt:
1813 except KeyboardInterrupt:
1816 #double-guard against keyboardinterrupts during kbdint handling
1814 #double-guard against keyboardinterrupts during kbdint handling
1817 try:
1815 try:
1818 self.write('\nKeyboardInterrupt\n')
1816 self.write('\nKeyboardInterrupt\n')
1819 self.resetbuffer()
1817 self.resetbuffer()
1820 # keep cache in sync with the prompt counter:
1818 # keep cache in sync with the prompt counter:
1821 self.outputcache.prompt_count -= 1
1819 self.outputcache.prompt_count -= 1
1822
1820
1823 if self.autoindent:
1821 if self.autoindent:
1824 self.indent_current_nsp = 0
1822 self.indent_current_nsp = 0
1825 more = 0
1823 more = 0
1826 except KeyboardInterrupt:
1824 except KeyboardInterrupt:
1827 pass
1825 pass
1828 except EOFError:
1826 except EOFError:
1829 if self.autoindent:
1827 if self.autoindent:
1830 self.rl_do_indent = False
1828 self.rl_do_indent = False
1831 self.readline_startup_hook(None)
1829 self.readline_startup_hook(None)
1832 self.write('\n')
1830 self.write('\n')
1833 self.exit()
1831 self.exit()
1834 except bdb.BdbQuit:
1832 except bdb.BdbQuit:
1835 warn('The Python debugger has exited with a BdbQuit exception.\n'
1833 warn('The Python debugger has exited with a BdbQuit exception.\n'
1836 'Because of how pdb handles the stack, it is impossible\n'
1834 'Because of how pdb handles the stack, it is impossible\n'
1837 'for IPython to properly format this particular exception.\n'
1835 'for IPython to properly format this particular exception.\n'
1838 'IPython will resume normal operation.')
1836 'IPython will resume normal operation.')
1839 except:
1837 except:
1840 # exceptions here are VERY RARE, but they can be triggered
1838 # exceptions here are VERY RARE, but they can be triggered
1841 # asynchronously by signal handlers, for example.
1839 # asynchronously by signal handlers, for example.
1842 self.showtraceback()
1840 self.showtraceback()
1843 else:
1841 else:
1844 more = self.push_line(line)
1842 more = self.push_line(line)
1845 if (self.SyntaxTB.last_syntax_error and
1843 if (self.SyntaxTB.last_syntax_error and
1846 self.autoedit_syntax):
1844 self.autoedit_syntax):
1847 self.edit_syntax_error()
1845 self.edit_syntax_error()
1848
1846
1849 # We are off again...
1847 # We are off again...
1850 __builtin__.__dict__['__IPYTHON__active'] -= 1
1848 __builtin__.__dict__['__IPYTHON__active'] -= 1
1851
1849
1852 def safe_execfile(self, fname, *where, **kw):
1850 def safe_execfile(self, fname, *where, **kw):
1853 """A safe version of the builtin execfile().
1851 """A safe version of the builtin execfile().
1854
1852
1855 This version will never throw an exception, but instead print
1853 This version will never throw an exception, but instead print
1856 helpful error messages to the screen. This only works on pure
1854 helpful error messages to the screen. This only works on pure
1857 Python files with the .py extension.
1855 Python files with the .py extension.
1858
1856
1859 Parameters
1857 Parameters
1860 ----------
1858 ----------
1861 fname : string
1859 fname : string
1862 The name of the file to be executed.
1860 The name of the file to be executed.
1863 where : tuple
1861 where : tuple
1864 One or two namespaces, passed to execfile() as (globals,locals).
1862 One or two namespaces, passed to execfile() as (globals,locals).
1865 If only one is given, it is passed as both.
1863 If only one is given, it is passed as both.
1866 exit_ignore : bool (False)
1864 exit_ignore : bool (False)
1867 If True, then don't print errors for non-zero exit statuses.
1865 If True, then don't print errors for non-zero exit statuses.
1868 """
1866 """
1869 kw.setdefault('exit_ignore', False)
1867 kw.setdefault('exit_ignore', False)
1870
1868
1871 fname = os.path.abspath(os.path.expanduser(fname))
1869 fname = os.path.abspath(os.path.expanduser(fname))
1872
1870
1873 # Make sure we have a .py file
1871 # Make sure we have a .py file
1874 if not fname.endswith('.py'):
1872 if not fname.endswith('.py'):
1875 warn('File must end with .py to be run using execfile: <%s>' % fname)
1873 warn('File must end with .py to be run using execfile: <%s>' % fname)
1876
1874
1877 # Make sure we can open the file
1875 # Make sure we can open the file
1878 try:
1876 try:
1879 with open(fname) as thefile:
1877 with open(fname) as thefile:
1880 pass
1878 pass
1881 except:
1879 except:
1882 warn('Could not open file <%s> for safe execution.' % fname)
1880 warn('Could not open file <%s> for safe execution.' % fname)
1883 return
1881 return
1884
1882
1885 # Find things also in current directory. This is needed to mimic the
1883 # Find things also in current directory. This is needed to mimic the
1886 # behavior of running a script from the system command line, where
1884 # behavior of running a script from the system command line, where
1887 # Python inserts the script's directory into sys.path
1885 # Python inserts the script's directory into sys.path
1888 dname = os.path.dirname(fname)
1886 dname = os.path.dirname(fname)
1889
1887
1890 with prepended_to_syspath(dname):
1888 with prepended_to_syspath(dname):
1891 try:
1889 try:
1892 if sys.platform == 'win32' and sys.version_info < (2,5,1):
1890 if sys.platform == 'win32' and sys.version_info < (2,5,1):
1893 # Work around a bug in Python for Windows. The bug was
1891 # Work around a bug in Python for Windows. The bug was
1894 # fixed in in Python 2.5 r54159 and 54158, but that's still
1892 # fixed in in Python 2.5 r54159 and 54158, but that's still
1895 # SVN Python as of March/07. For details, see:
1893 # SVN Python as of March/07. For details, see:
1896 # http://projects.scipy.org/ipython/ipython/ticket/123
1894 # http://projects.scipy.org/ipython/ipython/ticket/123
1897 try:
1895 try:
1898 globs,locs = where[0:2]
1896 globs,locs = where[0:2]
1899 except:
1897 except:
1900 try:
1898 try:
1901 globs = locs = where[0]
1899 globs = locs = where[0]
1902 except:
1900 except:
1903 globs = locs = globals()
1901 globs = locs = globals()
1904 exec file(fname) in globs,locs
1902 exec file(fname) in globs,locs
1905 else:
1903 else:
1906 execfile(fname,*where)
1904 execfile(fname,*where)
1907 except SyntaxError:
1905 except SyntaxError:
1908 self.showsyntaxerror()
1906 self.showsyntaxerror()
1909 warn('Failure executing file: <%s>' % fname)
1907 warn('Failure executing file: <%s>' % fname)
1910 except SystemExit, status:
1908 except SystemExit, status:
1911 # Code that correctly sets the exit status flag to success (0)
1909 # Code that correctly sets the exit status flag to success (0)
1912 # shouldn't be bothered with a traceback. Note that a plain
1910 # shouldn't be bothered with a traceback. Note that a plain
1913 # sys.exit() does NOT set the message to 0 (it's empty) so that
1911 # sys.exit() does NOT set the message to 0 (it's empty) so that
1914 # will still get a traceback. Note that the structure of the
1912 # will still get a traceback. Note that the structure of the
1915 # SystemExit exception changed between Python 2.4 and 2.5, so
1913 # SystemExit exception changed between Python 2.4 and 2.5, so
1916 # the checks must be done in a version-dependent way.
1914 # the checks must be done in a version-dependent way.
1917 show = False
1915 show = False
1918 if status.message!=0 and not kw['exit_ignore']:
1916 if status.message!=0 and not kw['exit_ignore']:
1919 show = True
1917 show = True
1920 if show:
1918 if show:
1921 self.showtraceback()
1919 self.showtraceback()
1922 warn('Failure executing file: <%s>' % fname)
1920 warn('Failure executing file: <%s>' % fname)
1923 except:
1921 except:
1924 self.showtraceback()
1922 self.showtraceback()
1925 warn('Failure executing file: <%s>' % fname)
1923 warn('Failure executing file: <%s>' % fname)
1926
1924
1927 def safe_execfile_ipy(self, fname):
1925 def safe_execfile_ipy(self, fname):
1928 """Like safe_execfile, but for .ipy files with IPython syntax.
1926 """Like safe_execfile, but for .ipy files with IPython syntax.
1929
1927
1930 Parameters
1928 Parameters
1931 ----------
1929 ----------
1932 fname : str
1930 fname : str
1933 The name of the file to execute. The filename must have a
1931 The name of the file to execute. The filename must have a
1934 .ipy extension.
1932 .ipy extension.
1935 """
1933 """
1936 fname = os.path.abspath(os.path.expanduser(fname))
1934 fname = os.path.abspath(os.path.expanduser(fname))
1937
1935
1938 # Make sure we have a .py file
1936 # Make sure we have a .py file
1939 if not fname.endswith('.ipy'):
1937 if not fname.endswith('.ipy'):
1940 warn('File must end with .py to be run using execfile: <%s>' % fname)
1938 warn('File must end with .py to be run using execfile: <%s>' % fname)
1941
1939
1942 # Make sure we can open the file
1940 # Make sure we can open the file
1943 try:
1941 try:
1944 with open(fname) as thefile:
1942 with open(fname) as thefile:
1945 pass
1943 pass
1946 except:
1944 except:
1947 warn('Could not open file <%s> for safe execution.' % fname)
1945 warn('Could not open file <%s> for safe execution.' % fname)
1948 return
1946 return
1949
1947
1950 # Find things also in current directory. This is needed to mimic the
1948 # Find things also in current directory. This is needed to mimic the
1951 # behavior of running a script from the system command line, where
1949 # behavior of running a script from the system command line, where
1952 # Python inserts the script's directory into sys.path
1950 # Python inserts the script's directory into sys.path
1953 dname = os.path.dirname(fname)
1951 dname = os.path.dirname(fname)
1954
1952
1955 with prepended_to_syspath(dname):
1953 with prepended_to_syspath(dname):
1956 try:
1954 try:
1957 with open(fname) as thefile:
1955 with open(fname) as thefile:
1958 script = thefile.read()
1956 script = thefile.read()
1959 # self.runlines currently captures all exceptions
1957 # self.runlines currently captures all exceptions
1960 # raise in user code. It would be nice if there were
1958 # raise in user code. It would be nice if there were
1961 # versions of runlines, execfile that did raise, so
1959 # versions of runlines, execfile that did raise, so
1962 # we could catch the errors.
1960 # we could catch the errors.
1963 self.runlines(script, clean=True)
1961 self.runlines(script, clean=True)
1964 except:
1962 except:
1965 self.showtraceback()
1963 self.showtraceback()
1966 warn('Unknown failure executing file: <%s>' % fname)
1964 warn('Unknown failure executing file: <%s>' % fname)
1967
1965
1968 def _is_secondary_block_start(self, s):
1966 def _is_secondary_block_start(self, s):
1969 if not s.endswith(':'):
1967 if not s.endswith(':'):
1970 return False
1968 return False
1971 if (s.startswith('elif') or
1969 if (s.startswith('elif') or
1972 s.startswith('else') or
1970 s.startswith('else') or
1973 s.startswith('except') or
1971 s.startswith('except') or
1974 s.startswith('finally')):
1972 s.startswith('finally')):
1975 return True
1973 return True
1976
1974
1977 def cleanup_ipy_script(self, script):
1975 def cleanup_ipy_script(self, script):
1978 """Make a script safe for self.runlines()
1976 """Make a script safe for self.runlines()
1979
1977
1980 Currently, IPython is lines based, with blocks being detected by
1978 Currently, IPython is lines based, with blocks being detected by
1981 empty lines. This is a problem for block based scripts that may
1979 empty lines. This is a problem for block based scripts that may
1982 not have empty lines after blocks. This script adds those empty
1980 not have empty lines after blocks. This script adds those empty
1983 lines to make scripts safe for running in the current line based
1981 lines to make scripts safe for running in the current line based
1984 IPython.
1982 IPython.
1985 """
1983 """
1986 res = []
1984 res = []
1987 lines = script.splitlines()
1985 lines = script.splitlines()
1988 level = 0
1986 level = 0
1989
1987
1990 for l in lines:
1988 for l in lines:
1991 lstripped = l.lstrip()
1989 lstripped = l.lstrip()
1992 stripped = l.strip()
1990 stripped = l.strip()
1993 if not stripped:
1991 if not stripped:
1994 continue
1992 continue
1995 newlevel = len(l) - len(lstripped)
1993 newlevel = len(l) - len(lstripped)
1996 if level > 0 and newlevel == 0 and \
1994 if level > 0 and newlevel == 0 and \
1997 not self._is_secondary_block_start(stripped):
1995 not self._is_secondary_block_start(stripped):
1998 # add empty line
1996 # add empty line
1999 res.append('')
1997 res.append('')
2000 res.append(l)
1998 res.append(l)
2001 level = newlevel
1999 level = newlevel
2002
2000
2003 return '\n'.join(res) + '\n'
2001 return '\n'.join(res) + '\n'
2004
2002
2005 def runlines(self, lines, clean=False):
2003 def runlines(self, lines, clean=False):
2006 """Run a string of one or more lines of source.
2004 """Run a string of one or more lines of source.
2007
2005
2008 This method is capable of running a string containing multiple source
2006 This method is capable of running a string containing multiple source
2009 lines, as if they had been entered at the IPython prompt. Since it
2007 lines, as if they had been entered at the IPython prompt. Since it
2010 exposes IPython's processing machinery, the given strings can contain
2008 exposes IPython's processing machinery, the given strings can contain
2011 magic calls (%magic), special shell access (!cmd), etc.
2009 magic calls (%magic), special shell access (!cmd), etc.
2012 """
2010 """
2013
2011
2014 if isinstance(lines, (list, tuple)):
2012 if isinstance(lines, (list, tuple)):
2015 lines = '\n'.join(lines)
2013 lines = '\n'.join(lines)
2016
2014
2017 if clean:
2015 if clean:
2018 lines = self.cleanup_ipy_script(lines)
2016 lines = self.cleanup_ipy_script(lines)
2019
2017
2020 # We must start with a clean buffer, in case this is run from an
2018 # We must start with a clean buffer, in case this is run from an
2021 # interactive IPython session (via a magic, for example).
2019 # interactive IPython session (via a magic, for example).
2022 self.resetbuffer()
2020 self.resetbuffer()
2023 lines = lines.splitlines()
2021 lines = lines.splitlines()
2024 more = 0
2022 more = 0
2025
2023
2026 with nested(self.builtin_trap, self.display_trap):
2024 with nested(self.builtin_trap, self.display_trap):
2027 for line in lines:
2025 for line in lines:
2028 # skip blank lines so we don't mess up the prompt counter, but do
2026 # skip blank lines so we don't mess up the prompt counter, but do
2029 # NOT skip even a blank line if we are in a code block (more is
2027 # NOT skip even a blank line if we are in a code block (more is
2030 # true)
2028 # true)
2031
2029
2032 if line or more:
2030 if line or more:
2033 # push to raw history, so hist line numbers stay in sync
2031 # push to raw history, so hist line numbers stay in sync
2034 self.input_hist_raw.append("# " + line + "\n")
2032 self.input_hist_raw.append("# " + line + "\n")
2035 prefiltered = self.prefilter_manager.prefilter_lines(line,more)
2033 prefiltered = self.prefilter_manager.prefilter_lines(line,more)
2036 more = self.push_line(prefiltered)
2034 more = self.push_line(prefiltered)
2037 # IPython's runsource returns None if there was an error
2035 # IPython's runsource returns None if there was an error
2038 # compiling the code. This allows us to stop processing right
2036 # compiling the code. This allows us to stop processing right
2039 # away, so the user gets the error message at the right place.
2037 # away, so the user gets the error message at the right place.
2040 if more is None:
2038 if more is None:
2041 break
2039 break
2042 else:
2040 else:
2043 self.input_hist_raw.append("\n")
2041 self.input_hist_raw.append("\n")
2044 # final newline in case the input didn't have it, so that the code
2042 # final newline in case the input didn't have it, so that the code
2045 # actually does get executed
2043 # actually does get executed
2046 if more:
2044 if more:
2047 self.push_line('\n')
2045 self.push_line('\n')
2048
2046
2049 def runsource(self, source, filename='<input>', symbol='single'):
2047 def runsource(self, source, filename='<input>', symbol='single'):
2050 """Compile and run some source in the interpreter.
2048 """Compile and run some source in the interpreter.
2051
2049
2052 Arguments are as for compile_command().
2050 Arguments are as for compile_command().
2053
2051
2054 One several things can happen:
2052 One several things can happen:
2055
2053
2056 1) The input is incorrect; compile_command() raised an
2054 1) The input is incorrect; compile_command() raised an
2057 exception (SyntaxError or OverflowError). A syntax traceback
2055 exception (SyntaxError or OverflowError). A syntax traceback
2058 will be printed by calling the showsyntaxerror() method.
2056 will be printed by calling the showsyntaxerror() method.
2059
2057
2060 2) The input is incomplete, and more input is required;
2058 2) The input is incomplete, and more input is required;
2061 compile_command() returned None. Nothing happens.
2059 compile_command() returned None. Nothing happens.
2062
2060
2063 3) The input is complete; compile_command() returned a code
2061 3) The input is complete; compile_command() returned a code
2064 object. The code is executed by calling self.runcode() (which
2062 object. The code is executed by calling self.runcode() (which
2065 also handles run-time exceptions, except for SystemExit).
2063 also handles run-time exceptions, except for SystemExit).
2066
2064
2067 The return value is:
2065 The return value is:
2068
2066
2069 - True in case 2
2067 - True in case 2
2070
2068
2071 - False in the other cases, unless an exception is raised, where
2069 - False in the other cases, unless an exception is raised, where
2072 None is returned instead. This can be used by external callers to
2070 None is returned instead. This can be used by external callers to
2073 know whether to continue feeding input or not.
2071 know whether to continue feeding input or not.
2074
2072
2075 The return value can be used to decide whether to use sys.ps1 or
2073 The return value can be used to decide whether to use sys.ps1 or
2076 sys.ps2 to prompt the next line."""
2074 sys.ps2 to prompt the next line."""
2077
2075
2078 # if the source code has leading blanks, add 'if 1:\n' to it
2076 # if the source code has leading blanks, add 'if 1:\n' to it
2079 # this allows execution of indented pasted code. It is tempting
2077 # this allows execution of indented pasted code. It is tempting
2080 # to add '\n' at the end of source to run commands like ' a=1'
2078 # to add '\n' at the end of source to run commands like ' a=1'
2081 # directly, but this fails for more complicated scenarios
2079 # directly, but this fails for more complicated scenarios
2082 source=source.encode(self.stdin_encoding)
2080 source=source.encode(self.stdin_encoding)
2083 if source[:1] in [' ', '\t']:
2081 if source[:1] in [' ', '\t']:
2084 source = 'if 1:\n%s' % source
2082 source = 'if 1:\n%s' % source
2085
2083
2086 try:
2084 try:
2087 code = self.compile(source,filename,symbol)
2085 code = self.compile(source,filename,symbol)
2088 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2086 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2089 # Case 1
2087 # Case 1
2090 self.showsyntaxerror(filename)
2088 self.showsyntaxerror(filename)
2091 return None
2089 return None
2092
2090
2093 if code is None:
2091 if code is None:
2094 # Case 2
2092 # Case 2
2095 return True
2093 return True
2096
2094
2097 # Case 3
2095 # Case 3
2098 # We store the code object so that threaded shells and
2096 # We store the code object so that threaded shells and
2099 # custom exception handlers can access all this info if needed.
2097 # custom exception handlers can access all this info if needed.
2100 # The source corresponding to this can be obtained from the
2098 # The source corresponding to this can be obtained from the
2101 # buffer attribute as '\n'.join(self.buffer).
2099 # buffer attribute as '\n'.join(self.buffer).
2102 self.code_to_run = code
2100 self.code_to_run = code
2103 # now actually execute the code object
2101 # now actually execute the code object
2104 if self.runcode(code) == 0:
2102 if self.runcode(code) == 0:
2105 return False
2103 return False
2106 else:
2104 else:
2107 return None
2105 return None
2108
2106
2109 def runcode(self,code_obj):
2107 def runcode(self,code_obj):
2110 """Execute a code object.
2108 """Execute a code object.
2111
2109
2112 When an exception occurs, self.showtraceback() is called to display a
2110 When an exception occurs, self.showtraceback() is called to display a
2113 traceback.
2111 traceback.
2114
2112
2115 Return value: a flag indicating whether the code to be run completed
2113 Return value: a flag indicating whether the code to be run completed
2116 successfully:
2114 successfully:
2117
2115
2118 - 0: successful execution.
2116 - 0: successful execution.
2119 - 1: an error occurred.
2117 - 1: an error occurred.
2120 """
2118 """
2121
2119
2122 # Set our own excepthook in case the user code tries to call it
2120 # Set our own excepthook in case the user code tries to call it
2123 # directly, so that the IPython crash handler doesn't get triggered
2121 # directly, so that the IPython crash handler doesn't get triggered
2124 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2122 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2125
2123
2126 # we save the original sys.excepthook in the instance, in case config
2124 # we save the original sys.excepthook in the instance, in case config
2127 # code (such as magics) needs access to it.
2125 # code (such as magics) needs access to it.
2128 self.sys_excepthook = old_excepthook
2126 self.sys_excepthook = old_excepthook
2129 outflag = 1 # happens in more places, so it's easier as default
2127 outflag = 1 # happens in more places, so it's easier as default
2130 try:
2128 try:
2131 try:
2129 try:
2132 self.hooks.pre_runcode_hook()
2130 self.hooks.pre_runcode_hook()
2133 exec code_obj in self.user_global_ns, self.user_ns
2131 exec code_obj in self.user_global_ns, self.user_ns
2134 finally:
2132 finally:
2135 # Reset our crash handler in place
2133 # Reset our crash handler in place
2136 sys.excepthook = old_excepthook
2134 sys.excepthook = old_excepthook
2137 except SystemExit:
2135 except SystemExit:
2138 self.resetbuffer()
2136 self.resetbuffer()
2139 self.showtraceback()
2137 self.showtraceback()
2140 warn("Type %exit or %quit to exit IPython "
2138 warn("Type %exit or %quit to exit IPython "
2141 "(%Exit or %Quit do so unconditionally).",level=1)
2139 "(%Exit or %Quit do so unconditionally).",level=1)
2142 except self.custom_exceptions:
2140 except self.custom_exceptions:
2143 etype,value,tb = sys.exc_info()
2141 etype,value,tb = sys.exc_info()
2144 self.CustomTB(etype,value,tb)
2142 self.CustomTB(etype,value,tb)
2145 except:
2143 except:
2146 self.showtraceback()
2144 self.showtraceback()
2147 else:
2145 else:
2148 outflag = 0
2146 outflag = 0
2149 if softspace(sys.stdout, 0):
2147 if softspace(sys.stdout, 0):
2150 print
2148 print
2151 # Flush out code object which has been run (and source)
2149 # Flush out code object which has been run (and source)
2152 self.code_to_run = None
2150 self.code_to_run = None
2153 return outflag
2151 return outflag
2154
2152
2155 def push_line(self, line):
2153 def push_line(self, line):
2156 """Push a line to the interpreter.
2154 """Push a line to the interpreter.
2157
2155
2158 The line should not have a trailing newline; it may have
2156 The line should not have a trailing newline; it may have
2159 internal newlines. The line is appended to a buffer and the
2157 internal newlines. The line is appended to a buffer and the
2160 interpreter's runsource() method is called with the
2158 interpreter's runsource() method is called with the
2161 concatenated contents of the buffer as source. If this
2159 concatenated contents of the buffer as source. If this
2162 indicates that the command was executed or invalid, the buffer
2160 indicates that the command was executed or invalid, the buffer
2163 is reset; otherwise, the command is incomplete, and the buffer
2161 is reset; otherwise, the command is incomplete, and the buffer
2164 is left as it was after the line was appended. The return
2162 is left as it was after the line was appended. The return
2165 value is 1 if more input is required, 0 if the line was dealt
2163 value is 1 if more input is required, 0 if the line was dealt
2166 with in some way (this is the same as runsource()).
2164 with in some way (this is the same as runsource()).
2167 """
2165 """
2168
2166
2169 # autoindent management should be done here, and not in the
2167 # autoindent management should be done here, and not in the
2170 # interactive loop, since that one is only seen by keyboard input. We
2168 # interactive loop, since that one is only seen by keyboard input. We
2171 # need this done correctly even for code run via runlines (which uses
2169 # need this done correctly even for code run via runlines (which uses
2172 # push).
2170 # push).
2173
2171
2174 #print 'push line: <%s>' % line # dbg
2172 #print 'push line: <%s>' % line # dbg
2175 for subline in line.splitlines():
2173 for subline in line.splitlines():
2176 self._autoindent_update(subline)
2174 self._autoindent_update(subline)
2177 self.buffer.append(line)
2175 self.buffer.append(line)
2178 more = self.runsource('\n'.join(self.buffer), self.filename)
2176 more = self.runsource('\n'.join(self.buffer), self.filename)
2179 if not more:
2177 if not more:
2180 self.resetbuffer()
2178 self.resetbuffer()
2181 return more
2179 return more
2182
2180
2183 def _autoindent_update(self,line):
2181 def _autoindent_update(self,line):
2184 """Keep track of the indent level."""
2182 """Keep track of the indent level."""
2185
2183
2186 #debugx('line')
2184 #debugx('line')
2187 #debugx('self.indent_current_nsp')
2185 #debugx('self.indent_current_nsp')
2188 if self.autoindent:
2186 if self.autoindent:
2189 if line:
2187 if line:
2190 inisp = num_ini_spaces(line)
2188 inisp = num_ini_spaces(line)
2191 if inisp < self.indent_current_nsp:
2189 if inisp < self.indent_current_nsp:
2192 self.indent_current_nsp = inisp
2190 self.indent_current_nsp = inisp
2193
2191
2194 if line[-1] == ':':
2192 if line[-1] == ':':
2195 self.indent_current_nsp += 4
2193 self.indent_current_nsp += 4
2196 elif dedent_re.match(line):
2194 elif dedent_re.match(line):
2197 self.indent_current_nsp -= 4
2195 self.indent_current_nsp -= 4
2198 else:
2196 else:
2199 self.indent_current_nsp = 0
2197 self.indent_current_nsp = 0
2200
2198
2201 def resetbuffer(self):
2199 def resetbuffer(self):
2202 """Reset the input buffer."""
2200 """Reset the input buffer."""
2203 self.buffer[:] = []
2201 self.buffer[:] = []
2204
2202
2205 def raw_input(self,prompt='',continue_prompt=False):
2203 def raw_input(self,prompt='',continue_prompt=False):
2206 """Write a prompt and read a line.
2204 """Write a prompt and read a line.
2207
2205
2208 The returned line does not include the trailing newline.
2206 The returned line does not include the trailing newline.
2209 When the user enters the EOF key sequence, EOFError is raised.
2207 When the user enters the EOF key sequence, EOFError is raised.
2210
2208
2211 Optional inputs:
2209 Optional inputs:
2212
2210
2213 - prompt(''): a string to be printed to prompt the user.
2211 - prompt(''): a string to be printed to prompt the user.
2214
2212
2215 - continue_prompt(False): whether this line is the first one or a
2213 - continue_prompt(False): whether this line is the first one or a
2216 continuation in a sequence of inputs.
2214 continuation in a sequence of inputs.
2217 """
2215 """
2218 # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt))
2216 # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt))
2219
2217
2220 # Code run by the user may have modified the readline completer state.
2218 # Code run by the user may have modified the readline completer state.
2221 # We must ensure that our completer is back in place.
2219 # We must ensure that our completer is back in place.
2222
2220
2223 if self.has_readline:
2221 if self.has_readline:
2224 self.set_completer()
2222 self.set_completer()
2225
2223
2226 try:
2224 try:
2227 line = raw_input_original(prompt).decode(self.stdin_encoding)
2225 line = raw_input_original(prompt).decode(self.stdin_encoding)
2228 except ValueError:
2226 except ValueError:
2229 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2227 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2230 " or sys.stdout.close()!\nExiting IPython!")
2228 " or sys.stdout.close()!\nExiting IPython!")
2231 self.ask_exit()
2229 self.ask_exit()
2232 return ""
2230 return ""
2233
2231
2234 # Try to be reasonably smart about not re-indenting pasted input more
2232 # Try to be reasonably smart about not re-indenting pasted input more
2235 # than necessary. We do this by trimming out the auto-indent initial
2233 # than necessary. We do this by trimming out the auto-indent initial
2236 # spaces, if the user's actual input started itself with whitespace.
2234 # spaces, if the user's actual input started itself with whitespace.
2237 #debugx('self.buffer[-1]')
2235 #debugx('self.buffer[-1]')
2238
2236
2239 if self.autoindent:
2237 if self.autoindent:
2240 if num_ini_spaces(line) > self.indent_current_nsp:
2238 if num_ini_spaces(line) > self.indent_current_nsp:
2241 line = line[self.indent_current_nsp:]
2239 line = line[self.indent_current_nsp:]
2242 self.indent_current_nsp = 0
2240 self.indent_current_nsp = 0
2243
2241
2244 # store the unfiltered input before the user has any chance to modify
2242 # store the unfiltered input before the user has any chance to modify
2245 # it.
2243 # it.
2246 if line.strip():
2244 if line.strip():
2247 if continue_prompt:
2245 if continue_prompt:
2248 self.input_hist_raw[-1] += '%s\n' % line
2246 self.input_hist_raw[-1] += '%s\n' % line
2249 if self.has_readline and self.readline_use:
2247 if self.has_readline and self.readline_use:
2250 try:
2248 try:
2251 histlen = self.readline.get_current_history_length()
2249 histlen = self.readline.get_current_history_length()
2252 if histlen > 1:
2250 if histlen > 1:
2253 newhist = self.input_hist_raw[-1].rstrip()
2251 newhist = self.input_hist_raw[-1].rstrip()
2254 self.readline.remove_history_item(histlen-1)
2252 self.readline.remove_history_item(histlen-1)
2255 self.readline.replace_history_item(histlen-2,
2253 self.readline.replace_history_item(histlen-2,
2256 newhist.encode(self.stdin_encoding))
2254 newhist.encode(self.stdin_encoding))
2257 except AttributeError:
2255 except AttributeError:
2258 pass # re{move,place}_history_item are new in 2.4.
2256 pass # re{move,place}_history_item are new in 2.4.
2259 else:
2257 else:
2260 self.input_hist_raw.append('%s\n' % line)
2258 self.input_hist_raw.append('%s\n' % line)
2261 # only entries starting at first column go to shadow history
2259 # only entries starting at first column go to shadow history
2262 if line.lstrip() == line:
2260 if line.lstrip() == line:
2263 self.shadowhist.add(line.strip())
2261 self.shadowhist.add(line.strip())
2264 elif not continue_prompt:
2262 elif not continue_prompt:
2265 self.input_hist_raw.append('\n')
2263 self.input_hist_raw.append('\n')
2266 try:
2264 try:
2267 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
2265 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
2268 except:
2266 except:
2269 # blanket except, in case a user-defined prefilter crashes, so it
2267 # blanket except, in case a user-defined prefilter crashes, so it
2270 # can't take all of ipython with it.
2268 # can't take all of ipython with it.
2271 self.showtraceback()
2269 self.showtraceback()
2272 return ''
2270 return ''
2273 else:
2271 else:
2274 return lineout
2272 return lineout
2275
2273
2276 #-------------------------------------------------------------------------
2274 #-------------------------------------------------------------------------
2275 # Working with components
2276 #-------------------------------------------------------------------------
2277
2278 def get_component(self, name=None, klass=None):
2279 """Fetch a component by name and klass in my tree."""
2280 c = Component.get_instances(root=self, name=name, klass=klass)
2281 if len(c) == 1:
2282 return c[0]
2283 else:
2284 return c
2285
2286 #-------------------------------------------------------------------------
2277 # IPython extensions
2287 # IPython extensions
2278 #-------------------------------------------------------------------------
2288 #-------------------------------------------------------------------------
2279
2289
2280 def load_extension(self, module_str):
2290 def load_extension(self, module_str):
2281 """Load an IPython extension.
2291 """Load an IPython extension by its module name.
2282
2292
2283 An IPython extension is an importable Python module that has
2293 An IPython extension is an importable Python module that has
2284 a function with the signature::
2294 a function with the signature::
2285
2295
2286 def load_in_ipython(ipython):
2296 def load_ipython_extension(ipython):
2287 # Do things with ipython
2297 # Do things with ipython
2288
2298
2289 This function is called after your extension is imported and the
2299 This function is called after your extension is imported and the
2290 currently active :class:`InteractiveShell` instance is passed as
2300 currently active :class:`InteractiveShell` instance is passed as
2291 the only argument. You can do anything you want with IPython at
2301 the only argument. You can do anything you want with IPython at
2292 that point, including defining new magic and aliases, adding new
2302 that point, including defining new magic and aliases, adding new
2293 components, etc.
2303 components, etc.
2294
2304
2305 The :func:`load_ipython_extension` will be called again is you
2306 load or reload the extension again. It is up to the extension
2307 author to add code to manage that.
2308
2295 You can put your extension modules anywhere you want, as long as
2309 You can put your extension modules anywhere you want, as long as
2296 they can be imported by Python's standard import mechanism. However,
2310 they can be imported by Python's standard import mechanism. However,
2297 to make it easy to write extensions, you can also put your extensions
2311 to make it easy to write extensions, you can also put your extensions
2298 in ``os.path.join(self.ipythondir, 'extensions')``. This directory
2312 in ``os.path.join(self.ipythondir, 'extensions')``. This directory
2299 is added to ``sys.path`` automatically.
2313 is added to ``sys.path`` automatically.
2300 """
2314 """
2301 from IPython.utils.syspathcontext import prepended_to_syspath
2315 from IPython.utils.syspathcontext import prepended_to_syspath
2302
2316
2303 if module_str in sys.modules:
2317 if module_str not in sys.modules:
2304 return
2305
2306 with prepended_to_syspath(self.ipython_extension_dir):
2318 with prepended_to_syspath(self.ipython_extension_dir):
2307 __import__(module_str)
2319 __import__(module_str)
2308 mod = sys.modules[module_str]
2320 mod = sys.modules[module_str]
2309 self._call_load_in_ipython(mod)
2321 self._call_load_ipython_extension(mod)
2322
2323 def unload_extension(self, module_str):
2324 """Unload an IPython extension by its module name.
2325
2326 This function looks up the extension's name in ``sys.modules`` and
2327 simply calls ``mod.unload_ipython_extension(self)``.
2328 """
2329 if module_str in sys.modules:
2330 mod = sys.modules[module_str]
2331 self._call_unload_ipython_extension(mod)
2310
2332
2311 def reload_extension(self, module_str):
2333 def reload_extension(self, module_str):
2312 """Reload an IPython extension by doing reload."""
2334 """Reload an IPython extension by calling reload.
2335
2336 If the module has not been loaded before,
2337 :meth:`InteractiveShell.load_extension` is called. Otherwise
2338 :func:`reload` is called and then the :func:`load_ipython_extension`
2339 function of the module, if it exists is called.
2340 """
2313 from IPython.utils.syspathcontext import prepended_to_syspath
2341 from IPython.utils.syspathcontext import prepended_to_syspath
2314
2342
2315 with prepended_to_syspath(self.ipython_extension_dir):
2343 with prepended_to_syspath(self.ipython_extension_dir):
2316 if module_str in sys.modules:
2344 if module_str in sys.modules:
2317 mod = sys.modules[module_str]
2345 mod = sys.modules[module_str]
2318 reload(mod)
2346 reload(mod)
2319 self._call_load_in_ipython(mod)
2347 self._call_load_ipython_extension(mod)
2320 else:
2348 else:
2321 self.load_extension(self, module_str)
2349 self.load_extension(module_str)
2350
2351 def _call_load_ipython_extension(self, mod):
2352 if hasattr(mod, 'load_ipython_extension'):
2353 mod.load_ipython_extension(self)
2322
2354
2323 def _call_load_in_ipython(self, mod):
2355 def _call_unload_ipython_extension(self, mod):
2324 if hasattr(mod, 'load_in_ipython'):
2356 if hasattr(mod, 'unload_ipython_extension'):
2325 mod.load_in_ipython(self)
2357 mod.unload_ipython_extension(self)
2326
2358
2327 #-------------------------------------------------------------------------
2359 #-------------------------------------------------------------------------
2328 # Things related to the prefilter
2360 # Things related to the prefilter
2329 #-------------------------------------------------------------------------
2361 #-------------------------------------------------------------------------
2330
2362
2331 def init_prefilter(self):
2363 def init_prefilter(self):
2332 self.prefilter_manager = PrefilterManager(self, config=self.config)
2364 self.prefilter_manager = PrefilterManager(self, config=self.config)
2333
2365
2334 #-------------------------------------------------------------------------
2366 #-------------------------------------------------------------------------
2335 # Utilities
2367 # Utilities
2336 #-------------------------------------------------------------------------
2368 #-------------------------------------------------------------------------
2337
2369
2338 def getoutput(self, cmd):
2370 def getoutput(self, cmd):
2339 return getoutput(self.var_expand(cmd,depth=2),
2371 return getoutput(self.var_expand(cmd,depth=2),
2340 header=self.system_header,
2372 header=self.system_header,
2341 verbose=self.system_verbose)
2373 verbose=self.system_verbose)
2342
2374
2343 def getoutputerror(self, cmd):
2375 def getoutputerror(self, cmd):
2344 return getoutputerror(self.var_expand(cmd,depth=2),
2376 return getoutputerror(self.var_expand(cmd,depth=2),
2345 header=self.system_header,
2377 header=self.system_header,
2346 verbose=self.system_verbose)
2378 verbose=self.system_verbose)
2347
2379
2348 def var_expand(self,cmd,depth=0):
2380 def var_expand(self,cmd,depth=0):
2349 """Expand python variables in a string.
2381 """Expand python variables in a string.
2350
2382
2351 The depth argument indicates how many frames above the caller should
2383 The depth argument indicates how many frames above the caller should
2352 be walked to look for the local namespace where to expand variables.
2384 be walked to look for the local namespace where to expand variables.
2353
2385
2354 The global namespace for expansion is always the user's interactive
2386 The global namespace for expansion is always the user's interactive
2355 namespace.
2387 namespace.
2356 """
2388 """
2357
2389
2358 return str(ItplNS(cmd,
2390 return str(ItplNS(cmd,
2359 self.user_ns, # globals
2391 self.user_ns, # globals
2360 # Skip our own frame in searching for locals:
2392 # Skip our own frame in searching for locals:
2361 sys._getframe(depth+1).f_locals # locals
2393 sys._getframe(depth+1).f_locals # locals
2362 ))
2394 ))
2363
2395
2364 def mktempfile(self,data=None):
2396 def mktempfile(self,data=None):
2365 """Make a new tempfile and return its filename.
2397 """Make a new tempfile and return its filename.
2366
2398
2367 This makes a call to tempfile.mktemp, but it registers the created
2399 This makes a call to tempfile.mktemp, but it registers the created
2368 filename internally so ipython cleans it up at exit time.
2400 filename internally so ipython cleans it up at exit time.
2369
2401
2370 Optional inputs:
2402 Optional inputs:
2371
2403
2372 - data(None): if data is given, it gets written out to the temp file
2404 - data(None): if data is given, it gets written out to the temp file
2373 immediately, and the file is closed again."""
2405 immediately, and the file is closed again."""
2374
2406
2375 filename = tempfile.mktemp('.py','ipython_edit_')
2407 filename = tempfile.mktemp('.py','ipython_edit_')
2376 self.tempfiles.append(filename)
2408 self.tempfiles.append(filename)
2377
2409
2378 if data:
2410 if data:
2379 tmp_file = open(filename,'w')
2411 tmp_file = open(filename,'w')
2380 tmp_file.write(data)
2412 tmp_file.write(data)
2381 tmp_file.close()
2413 tmp_file.close()
2382 return filename
2414 return filename
2383
2415
2384 def write(self,data):
2416 def write(self,data):
2385 """Write a string to the default output"""
2417 """Write a string to the default output"""
2386 Term.cout.write(data)
2418 Term.cout.write(data)
2387
2419
2388 def write_err(self,data):
2420 def write_err(self,data):
2389 """Write a string to the default error output"""
2421 """Write a string to the default error output"""
2390 Term.cerr.write(data)
2422 Term.cerr.write(data)
2391
2423
2392 def ask_yes_no(self,prompt,default=True):
2424 def ask_yes_no(self,prompt,default=True):
2393 if self.quiet:
2425 if self.quiet:
2394 return True
2426 return True
2395 return ask_yes_no(prompt,default)
2427 return ask_yes_no(prompt,default)
2396
2428
2397 #-------------------------------------------------------------------------
2429 #-------------------------------------------------------------------------
2398 # Things related to IPython exiting
2430 # Things related to IPython exiting
2399 #-------------------------------------------------------------------------
2431 #-------------------------------------------------------------------------
2400
2432
2401 def ask_exit(self):
2433 def ask_exit(self):
2402 """ Call for exiting. Can be overiden and used as a callback. """
2434 """ Call for exiting. Can be overiden and used as a callback. """
2403 self.exit_now = True
2435 self.exit_now = True
2404
2436
2405 def exit(self):
2437 def exit(self):
2406 """Handle interactive exit.
2438 """Handle interactive exit.
2407
2439
2408 This method calls the ask_exit callback."""
2440 This method calls the ask_exit callback."""
2409 if self.confirm_exit:
2441 if self.confirm_exit:
2410 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2442 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2411 self.ask_exit()
2443 self.ask_exit()
2412 else:
2444 else:
2413 self.ask_exit()
2445 self.ask_exit()
2414
2446
2415 def atexit_operations(self):
2447 def atexit_operations(self):
2416 """This will be executed at the time of exit.
2448 """This will be executed at the time of exit.
2417
2449
2418 Saving of persistent data should be performed here.
2450 Saving of persistent data should be performed here.
2419 """
2451 """
2420 self.savehist()
2452 self.savehist()
2421
2453
2422 # Cleanup all tempfiles left around
2454 # Cleanup all tempfiles left around
2423 for tfile in self.tempfiles:
2455 for tfile in self.tempfiles:
2424 try:
2456 try:
2425 os.unlink(tfile)
2457 os.unlink(tfile)
2426 except OSError:
2458 except OSError:
2427 pass
2459 pass
2428
2460
2429 # Clear all user namespaces to release all references cleanly.
2461 # Clear all user namespaces to release all references cleanly.
2430 self.reset()
2462 self.reset()
2431
2463
2432 # Run user hooks
2464 # Run user hooks
2433 self.hooks.shutdown_hook()
2465 self.hooks.shutdown_hook()
2434
2466
2435 def cleanup(self):
2467 def cleanup(self):
2436 self.restore_sys_module_state()
2468 self.restore_sys_module_state()
2437
2469
2438
2470
@@ -1,3541 +1,3552 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3 """
3 """
4
4
5 #*****************************************************************************
5 #*****************************************************************************
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
7 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #*****************************************************************************
11 #*****************************************************************************
12
12
13 #****************************************************************************
13 #****************************************************************************
14 # Modules and globals
14 # Modules and globals
15
15
16 # Python standard modules
16 # Python standard modules
17 import __builtin__
17 import __builtin__
18 import bdb
18 import bdb
19 import inspect
19 import inspect
20 import os
20 import os
21 import pdb
21 import pdb
22 import pydoc
22 import pydoc
23 import sys
23 import sys
24 import re
24 import re
25 import tempfile
25 import tempfile
26 import time
26 import time
27 import cPickle as pickle
27 import cPickle as pickle
28 import textwrap
28 import textwrap
29 from cStringIO import StringIO
29 from cStringIO import StringIO
30 from getopt import getopt,GetoptError
30 from getopt import getopt,GetoptError
31 from pprint import pprint, pformat
31 from pprint import pprint, pformat
32
32
33 # cProfile was added in Python2.5
33 # cProfile was added in Python2.5
34 try:
34 try:
35 import cProfile as profile
35 import cProfile as profile
36 import pstats
36 import pstats
37 except ImportError:
37 except ImportError:
38 # profile isn't bundled by default in Debian for license reasons
38 # profile isn't bundled by default in Debian for license reasons
39 try:
39 try:
40 import profile,pstats
40 import profile,pstats
41 except ImportError:
41 except ImportError:
42 profile = pstats = None
42 profile = pstats = None
43
43
44 # Homebrewed
44 # Homebrewed
45 import IPython
45 import IPython
46 from IPython.utils import wildcard
46 from IPython.utils import wildcard
47 from IPython.core import debugger, oinspect
47 from IPython.core import debugger, oinspect
48 from IPython.core.error import TryNext
48 from IPython.core.error import TryNext
49 from IPython.core.fakemodule import FakeModule
49 from IPython.core.fakemodule import FakeModule
50 from IPython.core.prefilter import ESC_MAGIC
50 from IPython.core.prefilter import ESC_MAGIC
51 from IPython.external.Itpl import Itpl, itpl, printpl,itplns
51 from IPython.external.Itpl import Itpl, itpl, printpl,itplns
52 from IPython.utils.PyColorize import Parser
52 from IPython.utils.PyColorize import Parser
53 from IPython.utils.ipstruct import Struct
53 from IPython.utils.ipstruct import Struct
54 from IPython.core.macro import Macro
54 from IPython.core.macro import Macro
55 from IPython.utils.genutils import *
55 from IPython.utils.genutils import *
56 from IPython.core.page import page
56 from IPython.core.page import page
57 from IPython.utils import platutils
57 from IPython.utils import platutils
58 import IPython.utils.generics
58 import IPython.utils.generics
59 from IPython.core.error import UsageError
59 from IPython.core.error import UsageError
60 from IPython.testing import decorators as testdec
60 from IPython.testing import decorators as testdec
61
61
62 #***************************************************************************
62 #***************************************************************************
63 # Utility functions
63 # Utility functions
64 def on_off(tag):
64 def on_off(tag):
65 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
65 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
66 return ['OFF','ON'][tag]
66 return ['OFF','ON'][tag]
67
67
68 class Bunch: pass
68 class Bunch: pass
69
69
70 def compress_dhist(dh):
70 def compress_dhist(dh):
71 head, tail = dh[:-10], dh[-10:]
71 head, tail = dh[:-10], dh[-10:]
72
72
73 newhead = []
73 newhead = []
74 done = set()
74 done = set()
75 for h in head:
75 for h in head:
76 if h in done:
76 if h in done:
77 continue
77 continue
78 newhead.append(h)
78 newhead.append(h)
79 done.add(h)
79 done.add(h)
80
80
81 return newhead + tail
81 return newhead + tail
82
82
83
83
84 #***************************************************************************
84 #***************************************************************************
85 # Main class implementing Magic functionality
85 # Main class implementing Magic functionality
86 class Magic:
86 class Magic:
87 """Magic functions for InteractiveShell.
87 """Magic functions for InteractiveShell.
88
88
89 Shell functions which can be reached as %function_name. All magic
89 Shell functions which can be reached as %function_name. All magic
90 functions should accept a string, which they can parse for their own
90 functions should accept a string, which they can parse for their own
91 needs. This can make some functions easier to type, eg `%cd ../`
91 needs. This can make some functions easier to type, eg `%cd ../`
92 vs. `%cd("../")`
92 vs. `%cd("../")`
93
93
94 ALL definitions MUST begin with the prefix magic_. The user won't need it
94 ALL definitions MUST begin with the prefix magic_. The user won't need it
95 at the command line, but it is is needed in the definition. """
95 at the command line, but it is is needed in the definition. """
96
96
97 # class globals
97 # class globals
98 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
98 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
99 'Automagic is ON, % prefix NOT needed for magic functions.']
99 'Automagic is ON, % prefix NOT needed for magic functions.']
100
100
101 #......................................................................
101 #......................................................................
102 # some utility functions
102 # some utility functions
103
103
104 def __init__(self,shell):
104 def __init__(self,shell):
105
105
106 self.options_table = {}
106 self.options_table = {}
107 if profile is None:
107 if profile is None:
108 self.magic_prun = self.profile_missing_notice
108 self.magic_prun = self.profile_missing_notice
109 self.shell = shell
109 self.shell = shell
110
110
111 # namespace for holding state we may need
111 # namespace for holding state we may need
112 self._magic_state = Bunch()
112 self._magic_state = Bunch()
113
113
114 def profile_missing_notice(self, *args, **kwargs):
114 def profile_missing_notice(self, *args, **kwargs):
115 error("""\
115 error("""\
116 The profile module could not be found. It has been removed from the standard
116 The profile module could not be found. It has been removed from the standard
117 python packages because of its non-free license. To use profiling, install the
117 python packages because of its non-free license. To use profiling, install the
118 python-profiler package from non-free.""")
118 python-profiler package from non-free.""")
119
119
120 def default_option(self,fn,optstr):
120 def default_option(self,fn,optstr):
121 """Make an entry in the options_table for fn, with value optstr"""
121 """Make an entry in the options_table for fn, with value optstr"""
122
122
123 if fn not in self.lsmagic():
123 if fn not in self.lsmagic():
124 error("%s is not a magic function" % fn)
124 error("%s is not a magic function" % fn)
125 self.options_table[fn] = optstr
125 self.options_table[fn] = optstr
126
126
127 def lsmagic(self):
127 def lsmagic(self):
128 """Return a list of currently available magic functions.
128 """Return a list of currently available magic functions.
129
129
130 Gives a list of the bare names after mangling (['ls','cd', ...], not
130 Gives a list of the bare names after mangling (['ls','cd', ...], not
131 ['magic_ls','magic_cd',...]"""
131 ['magic_ls','magic_cd',...]"""
132
132
133 # FIXME. This needs a cleanup, in the way the magics list is built.
133 # FIXME. This needs a cleanup, in the way the magics list is built.
134
134
135 # magics in class definition
135 # magics in class definition
136 class_magic = lambda fn: fn.startswith('magic_') and \
136 class_magic = lambda fn: fn.startswith('magic_') and \
137 callable(Magic.__dict__[fn])
137 callable(Magic.__dict__[fn])
138 # in instance namespace (run-time user additions)
138 # in instance namespace (run-time user additions)
139 inst_magic = lambda fn: fn.startswith('magic_') and \
139 inst_magic = lambda fn: fn.startswith('magic_') and \
140 callable(self.__dict__[fn])
140 callable(self.__dict__[fn])
141 # and bound magics by user (so they can access self):
141 # and bound magics by user (so they can access self):
142 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
142 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
143 callable(self.__class__.__dict__[fn])
143 callable(self.__class__.__dict__[fn])
144 magics = filter(class_magic,Magic.__dict__.keys()) + \
144 magics = filter(class_magic,Magic.__dict__.keys()) + \
145 filter(inst_magic,self.__dict__.keys()) + \
145 filter(inst_magic,self.__dict__.keys()) + \
146 filter(inst_bound_magic,self.__class__.__dict__.keys())
146 filter(inst_bound_magic,self.__class__.__dict__.keys())
147 out = []
147 out = []
148 for fn in set(magics):
148 for fn in set(magics):
149 out.append(fn.replace('magic_','',1))
149 out.append(fn.replace('magic_','',1))
150 out.sort()
150 out.sort()
151 return out
151 return out
152
152
153 def extract_input_slices(self,slices,raw=False):
153 def extract_input_slices(self,slices,raw=False):
154 """Return as a string a set of input history slices.
154 """Return as a string a set of input history slices.
155
155
156 Inputs:
156 Inputs:
157
157
158 - slices: the set of slices is given as a list of strings (like
158 - slices: the set of slices is given as a list of strings (like
159 ['1','4:8','9'], since this function is for use by magic functions
159 ['1','4:8','9'], since this function is for use by magic functions
160 which get their arguments as strings.
160 which get their arguments as strings.
161
161
162 Optional inputs:
162 Optional inputs:
163
163
164 - raw(False): by default, the processed input is used. If this is
164 - raw(False): by default, the processed input is used. If this is
165 true, the raw input history is used instead.
165 true, the raw input history is used instead.
166
166
167 Note that slices can be called with two notations:
167 Note that slices can be called with two notations:
168
168
169 N:M -> standard python form, means including items N...(M-1).
169 N:M -> standard python form, means including items N...(M-1).
170
170
171 N-M -> include items N..M (closed endpoint)."""
171 N-M -> include items N..M (closed endpoint)."""
172
172
173 if raw:
173 if raw:
174 hist = self.shell.input_hist_raw
174 hist = self.shell.input_hist_raw
175 else:
175 else:
176 hist = self.shell.input_hist
176 hist = self.shell.input_hist
177
177
178 cmds = []
178 cmds = []
179 for chunk in slices:
179 for chunk in slices:
180 if ':' in chunk:
180 if ':' in chunk:
181 ini,fin = map(int,chunk.split(':'))
181 ini,fin = map(int,chunk.split(':'))
182 elif '-' in chunk:
182 elif '-' in chunk:
183 ini,fin = map(int,chunk.split('-'))
183 ini,fin = map(int,chunk.split('-'))
184 fin += 1
184 fin += 1
185 else:
185 else:
186 ini = int(chunk)
186 ini = int(chunk)
187 fin = ini+1
187 fin = ini+1
188 cmds.append(hist[ini:fin])
188 cmds.append(hist[ini:fin])
189 return cmds
189 return cmds
190
190
191 def _ofind(self, oname, namespaces=None):
191 def _ofind(self, oname, namespaces=None):
192 """Find an object in the available namespaces.
192 """Find an object in the available namespaces.
193
193
194 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
194 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
195
195
196 Has special code to detect magic functions.
196 Has special code to detect magic functions.
197 """
197 """
198
198
199 oname = oname.strip()
199 oname = oname.strip()
200
200
201 alias_ns = None
201 alias_ns = None
202 if namespaces is None:
202 if namespaces is None:
203 # Namespaces to search in:
203 # Namespaces to search in:
204 # Put them in a list. The order is important so that we
204 # Put them in a list. The order is important so that we
205 # find things in the same order that Python finds them.
205 # find things in the same order that Python finds them.
206 namespaces = [ ('Interactive', self.shell.user_ns),
206 namespaces = [ ('Interactive', self.shell.user_ns),
207 ('IPython internal', self.shell.internal_ns),
207 ('IPython internal', self.shell.internal_ns),
208 ('Python builtin', __builtin__.__dict__),
208 ('Python builtin', __builtin__.__dict__),
209 ('Alias', self.shell.alias_manager.alias_table),
209 ('Alias', self.shell.alias_manager.alias_table),
210 ]
210 ]
211 alias_ns = self.shell.alias_manager.alias_table
211 alias_ns = self.shell.alias_manager.alias_table
212
212
213 # initialize results to 'null'
213 # initialize results to 'null'
214 found = 0; obj = None; ospace = None; ds = None;
214 found = 0; obj = None; ospace = None; ds = None;
215 ismagic = 0; isalias = 0; parent = None
215 ismagic = 0; isalias = 0; parent = None
216
216
217 # Look for the given name by splitting it in parts. If the head is
217 # Look for the given name by splitting it in parts. If the head is
218 # found, then we look for all the remaining parts as members, and only
218 # found, then we look for all the remaining parts as members, and only
219 # declare success if we can find them all.
219 # declare success if we can find them all.
220 oname_parts = oname.split('.')
220 oname_parts = oname.split('.')
221 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
221 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
222 for nsname,ns in namespaces:
222 for nsname,ns in namespaces:
223 try:
223 try:
224 obj = ns[oname_head]
224 obj = ns[oname_head]
225 except KeyError:
225 except KeyError:
226 continue
226 continue
227 else:
227 else:
228 #print 'oname_rest:', oname_rest # dbg
228 #print 'oname_rest:', oname_rest # dbg
229 for part in oname_rest:
229 for part in oname_rest:
230 try:
230 try:
231 parent = obj
231 parent = obj
232 obj = getattr(obj,part)
232 obj = getattr(obj,part)
233 except:
233 except:
234 # Blanket except b/c some badly implemented objects
234 # Blanket except b/c some badly implemented objects
235 # allow __getattr__ to raise exceptions other than
235 # allow __getattr__ to raise exceptions other than
236 # AttributeError, which then crashes IPython.
236 # AttributeError, which then crashes IPython.
237 break
237 break
238 else:
238 else:
239 # If we finish the for loop (no break), we got all members
239 # If we finish the for loop (no break), we got all members
240 found = 1
240 found = 1
241 ospace = nsname
241 ospace = nsname
242 if ns == alias_ns:
242 if ns == alias_ns:
243 isalias = 1
243 isalias = 1
244 break # namespace loop
244 break # namespace loop
245
245
246 # Try to see if it's magic
246 # Try to see if it's magic
247 if not found:
247 if not found:
248 if oname.startswith(ESC_MAGIC):
248 if oname.startswith(ESC_MAGIC):
249 oname = oname[1:]
249 oname = oname[1:]
250 obj = getattr(self,'magic_'+oname,None)
250 obj = getattr(self,'magic_'+oname,None)
251 if obj is not None:
251 if obj is not None:
252 found = 1
252 found = 1
253 ospace = 'IPython internal'
253 ospace = 'IPython internal'
254 ismagic = 1
254 ismagic = 1
255
255
256 # Last try: special-case some literals like '', [], {}, etc:
256 # Last try: special-case some literals like '', [], {}, etc:
257 if not found and oname_head in ["''",'""','[]','{}','()']:
257 if not found and oname_head in ["''",'""','[]','{}','()']:
258 obj = eval(oname_head)
258 obj = eval(oname_head)
259 found = 1
259 found = 1
260 ospace = 'Interactive'
260 ospace = 'Interactive'
261
261
262 return {'found':found, 'obj':obj, 'namespace':ospace,
262 return {'found':found, 'obj':obj, 'namespace':ospace,
263 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
263 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
264
264
265 def arg_err(self,func):
265 def arg_err(self,func):
266 """Print docstring if incorrect arguments were passed"""
266 """Print docstring if incorrect arguments were passed"""
267 print 'Error in arguments:'
267 print 'Error in arguments:'
268 print OInspect.getdoc(func)
268 print OInspect.getdoc(func)
269
269
270 def format_latex(self,strng):
270 def format_latex(self,strng):
271 """Format a string for latex inclusion."""
271 """Format a string for latex inclusion."""
272
272
273 # Characters that need to be escaped for latex:
273 # Characters that need to be escaped for latex:
274 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
274 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
275 # Magic command names as headers:
275 # Magic command names as headers:
276 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
276 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
277 re.MULTILINE)
277 re.MULTILINE)
278 # Magic commands
278 # Magic commands
279 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
279 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
280 re.MULTILINE)
280 re.MULTILINE)
281 # Paragraph continue
281 # Paragraph continue
282 par_re = re.compile(r'\\$',re.MULTILINE)
282 par_re = re.compile(r'\\$',re.MULTILINE)
283
283
284 # The "\n" symbol
284 # The "\n" symbol
285 newline_re = re.compile(r'\\n')
285 newline_re = re.compile(r'\\n')
286
286
287 # Now build the string for output:
287 # Now build the string for output:
288 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
288 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
289 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
289 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
290 strng)
290 strng)
291 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
291 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
292 strng = par_re.sub(r'\\\\',strng)
292 strng = par_re.sub(r'\\\\',strng)
293 strng = escape_re.sub(r'\\\1',strng)
293 strng = escape_re.sub(r'\\\1',strng)
294 strng = newline_re.sub(r'\\textbackslash{}n',strng)
294 strng = newline_re.sub(r'\\textbackslash{}n',strng)
295 return strng
295 return strng
296
296
297 def format_screen(self,strng):
297 def format_screen(self,strng):
298 """Format a string for screen printing.
298 """Format a string for screen printing.
299
299
300 This removes some latex-type format codes."""
300 This removes some latex-type format codes."""
301 # Paragraph continue
301 # Paragraph continue
302 par_re = re.compile(r'\\$',re.MULTILINE)
302 par_re = re.compile(r'\\$',re.MULTILINE)
303 strng = par_re.sub('',strng)
303 strng = par_re.sub('',strng)
304 return strng
304 return strng
305
305
306 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
306 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
307 """Parse options passed to an argument string.
307 """Parse options passed to an argument string.
308
308
309 The interface is similar to that of getopt(), but it returns back a
309 The interface is similar to that of getopt(), but it returns back a
310 Struct with the options as keys and the stripped argument string still
310 Struct with the options as keys and the stripped argument string still
311 as a string.
311 as a string.
312
312
313 arg_str is quoted as a true sys.argv vector by using shlex.split.
313 arg_str is quoted as a true sys.argv vector by using shlex.split.
314 This allows us to easily expand variables, glob files, quote
314 This allows us to easily expand variables, glob files, quote
315 arguments, etc.
315 arguments, etc.
316
316
317 Options:
317 Options:
318 -mode: default 'string'. If given as 'list', the argument string is
318 -mode: default 'string'. If given as 'list', the argument string is
319 returned as a list (split on whitespace) instead of a string.
319 returned as a list (split on whitespace) instead of a string.
320
320
321 -list_all: put all option values in lists. Normally only options
321 -list_all: put all option values in lists. Normally only options
322 appearing more than once are put in a list.
322 appearing more than once are put in a list.
323
323
324 -posix (True): whether to split the input line in POSIX mode or not,
324 -posix (True): whether to split the input line in POSIX mode or not,
325 as per the conventions outlined in the shlex module from the
325 as per the conventions outlined in the shlex module from the
326 standard library."""
326 standard library."""
327
327
328 # inject default options at the beginning of the input line
328 # inject default options at the beginning of the input line
329 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
329 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
330 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
330 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
331
331
332 mode = kw.get('mode','string')
332 mode = kw.get('mode','string')
333 if mode not in ['string','list']:
333 if mode not in ['string','list']:
334 raise ValueError,'incorrect mode given: %s' % mode
334 raise ValueError,'incorrect mode given: %s' % mode
335 # Get options
335 # Get options
336 list_all = kw.get('list_all',0)
336 list_all = kw.get('list_all',0)
337 posix = kw.get('posix',True)
337 posix = kw.get('posix',True)
338
338
339 # Check if we have more than one argument to warrant extra processing:
339 # Check if we have more than one argument to warrant extra processing:
340 odict = {} # Dictionary with options
340 odict = {} # Dictionary with options
341 args = arg_str.split()
341 args = arg_str.split()
342 if len(args) >= 1:
342 if len(args) >= 1:
343 # If the list of inputs only has 0 or 1 thing in it, there's no
343 # If the list of inputs only has 0 or 1 thing in it, there's no
344 # need to look for options
344 # need to look for options
345 argv = arg_split(arg_str,posix)
345 argv = arg_split(arg_str,posix)
346 # Do regular option processing
346 # Do regular option processing
347 try:
347 try:
348 opts,args = getopt(argv,opt_str,*long_opts)
348 opts,args = getopt(argv,opt_str,*long_opts)
349 except GetoptError,e:
349 except GetoptError,e:
350 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
350 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
351 " ".join(long_opts)))
351 " ".join(long_opts)))
352 for o,a in opts:
352 for o,a in opts:
353 if o.startswith('--'):
353 if o.startswith('--'):
354 o = o[2:]
354 o = o[2:]
355 else:
355 else:
356 o = o[1:]
356 o = o[1:]
357 try:
357 try:
358 odict[o].append(a)
358 odict[o].append(a)
359 except AttributeError:
359 except AttributeError:
360 odict[o] = [odict[o],a]
360 odict[o] = [odict[o],a]
361 except KeyError:
361 except KeyError:
362 if list_all:
362 if list_all:
363 odict[o] = [a]
363 odict[o] = [a]
364 else:
364 else:
365 odict[o] = a
365 odict[o] = a
366
366
367 # Prepare opts,args for return
367 # Prepare opts,args for return
368 opts = Struct(odict)
368 opts = Struct(odict)
369 if mode == 'string':
369 if mode == 'string':
370 args = ' '.join(args)
370 args = ' '.join(args)
371
371
372 return opts,args
372 return opts,args
373
373
374 #......................................................................
374 #......................................................................
375 # And now the actual magic functions
375 # And now the actual magic functions
376
376
377 # Functions for IPython shell work (vars,funcs, config, etc)
377 # Functions for IPython shell work (vars,funcs, config, etc)
378 def magic_lsmagic(self, parameter_s = ''):
378 def magic_lsmagic(self, parameter_s = ''):
379 """List currently available magic functions."""
379 """List currently available magic functions."""
380 mesc = ESC_MAGIC
380 mesc = ESC_MAGIC
381 print 'Available magic functions:\n'+mesc+\
381 print 'Available magic functions:\n'+mesc+\
382 (' '+mesc).join(self.lsmagic())
382 (' '+mesc).join(self.lsmagic())
383 print '\n' + Magic.auto_status[self.shell.automagic]
383 print '\n' + Magic.auto_status[self.shell.automagic]
384 return None
384 return None
385
385
386 def magic_magic(self, parameter_s = ''):
386 def magic_magic(self, parameter_s = ''):
387 """Print information about the magic function system.
387 """Print information about the magic function system.
388
388
389 Supported formats: -latex, -brief, -rest
389 Supported formats: -latex, -brief, -rest
390 """
390 """
391
391
392 mode = ''
392 mode = ''
393 try:
393 try:
394 if parameter_s.split()[0] == '-latex':
394 if parameter_s.split()[0] == '-latex':
395 mode = 'latex'
395 mode = 'latex'
396 if parameter_s.split()[0] == '-brief':
396 if parameter_s.split()[0] == '-brief':
397 mode = 'brief'
397 mode = 'brief'
398 if parameter_s.split()[0] == '-rest':
398 if parameter_s.split()[0] == '-rest':
399 mode = 'rest'
399 mode = 'rest'
400 rest_docs = []
400 rest_docs = []
401 except:
401 except:
402 pass
402 pass
403
403
404 magic_docs = []
404 magic_docs = []
405 for fname in self.lsmagic():
405 for fname in self.lsmagic():
406 mname = 'magic_' + fname
406 mname = 'magic_' + fname
407 for space in (Magic,self,self.__class__):
407 for space in (Magic,self,self.__class__):
408 try:
408 try:
409 fn = space.__dict__[mname]
409 fn = space.__dict__[mname]
410 except KeyError:
410 except KeyError:
411 pass
411 pass
412 else:
412 else:
413 break
413 break
414 if mode == 'brief':
414 if mode == 'brief':
415 # only first line
415 # only first line
416 if fn.__doc__:
416 if fn.__doc__:
417 fndoc = fn.__doc__.split('\n',1)[0]
417 fndoc = fn.__doc__.split('\n',1)[0]
418 else:
418 else:
419 fndoc = 'No documentation'
419 fndoc = 'No documentation'
420 else:
420 else:
421 if fn.__doc__:
421 if fn.__doc__:
422 fndoc = fn.__doc__.rstrip()
422 fndoc = fn.__doc__.rstrip()
423 else:
423 else:
424 fndoc = 'No documentation'
424 fndoc = 'No documentation'
425
425
426
426
427 if mode == 'rest':
427 if mode == 'rest':
428 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
428 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
429 fname,fndoc))
429 fname,fndoc))
430
430
431 else:
431 else:
432 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
432 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
433 fname,fndoc))
433 fname,fndoc))
434
434
435 magic_docs = ''.join(magic_docs)
435 magic_docs = ''.join(magic_docs)
436
436
437 if mode == 'rest':
437 if mode == 'rest':
438 return "".join(rest_docs)
438 return "".join(rest_docs)
439
439
440 if mode == 'latex':
440 if mode == 'latex':
441 print self.format_latex(magic_docs)
441 print self.format_latex(magic_docs)
442 return
442 return
443 else:
443 else:
444 magic_docs = self.format_screen(magic_docs)
444 magic_docs = self.format_screen(magic_docs)
445 if mode == 'brief':
445 if mode == 'brief':
446 return magic_docs
446 return magic_docs
447
447
448 outmsg = """
448 outmsg = """
449 IPython's 'magic' functions
449 IPython's 'magic' functions
450 ===========================
450 ===========================
451
451
452 The magic function system provides a series of functions which allow you to
452 The magic function system provides a series of functions which allow you to
453 control the behavior of IPython itself, plus a lot of system-type
453 control the behavior of IPython itself, plus a lot of system-type
454 features. All these functions are prefixed with a % character, but parameters
454 features. All these functions are prefixed with a % character, but parameters
455 are given without parentheses or quotes.
455 are given without parentheses or quotes.
456
456
457 NOTE: If you have 'automagic' enabled (via the command line option or with the
457 NOTE: If you have 'automagic' enabled (via the command line option or with the
458 %automagic function), you don't need to type in the % explicitly. By default,
458 %automagic function), you don't need to type in the % explicitly. By default,
459 IPython ships with automagic on, so you should only rarely need the % escape.
459 IPython ships with automagic on, so you should only rarely need the % escape.
460
460
461 Example: typing '%cd mydir' (without the quotes) changes you working directory
461 Example: typing '%cd mydir' (without the quotes) changes you working directory
462 to 'mydir', if it exists.
462 to 'mydir', if it exists.
463
463
464 You can define your own magic functions to extend the system. See the supplied
464 You can define your own magic functions to extend the system. See the supplied
465 ipythonrc and example-magic.py files for details (in your ipython
465 ipythonrc and example-magic.py files for details (in your ipython
466 configuration directory, typically $HOME/.ipython/).
466 configuration directory, typically $HOME/.ipython/).
467
467
468 You can also define your own aliased names for magic functions. In your
468 You can also define your own aliased names for magic functions. In your
469 ipythonrc file, placing a line like:
469 ipythonrc file, placing a line like:
470
470
471 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
471 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
472
472
473 will define %pf as a new name for %profile.
473 will define %pf as a new name for %profile.
474
474
475 You can also call magics in code using the magic() function, which IPython
475 You can also call magics in code using the magic() function, which IPython
476 automatically adds to the builtin namespace. Type 'magic?' for details.
476 automatically adds to the builtin namespace. Type 'magic?' for details.
477
477
478 For a list of the available magic functions, use %lsmagic. For a description
478 For a list of the available magic functions, use %lsmagic. For a description
479 of any of them, type %magic_name?, e.g. '%cd?'.
479 of any of them, type %magic_name?, e.g. '%cd?'.
480
480
481 Currently the magic system has the following functions:\n"""
481 Currently the magic system has the following functions:\n"""
482
482
483 mesc = ESC_MAGIC
483 mesc = ESC_MAGIC
484 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
484 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
485 "\n\n%s%s\n\n%s" % (outmsg,
485 "\n\n%s%s\n\n%s" % (outmsg,
486 magic_docs,mesc,mesc,
486 magic_docs,mesc,mesc,
487 (' '+mesc).join(self.lsmagic()),
487 (' '+mesc).join(self.lsmagic()),
488 Magic.auto_status[self.shell.automagic] ) )
488 Magic.auto_status[self.shell.automagic] ) )
489
489
490 page(outmsg,screen_lines=self.shell.usable_screen_length)
490 page(outmsg,screen_lines=self.shell.usable_screen_length)
491
491
492
492
493 def magic_autoindent(self, parameter_s = ''):
493 def magic_autoindent(self, parameter_s = ''):
494 """Toggle autoindent on/off (if available)."""
494 """Toggle autoindent on/off (if available)."""
495
495
496 self.shell.set_autoindent()
496 self.shell.set_autoindent()
497 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
497 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
498
498
499
499
500 def magic_automagic(self, parameter_s = ''):
500 def magic_automagic(self, parameter_s = ''):
501 """Make magic functions callable without having to type the initial %.
501 """Make magic functions callable without having to type the initial %.
502
502
503 Without argumentsl toggles on/off (when off, you must call it as
503 Without argumentsl toggles on/off (when off, you must call it as
504 %automagic, of course). With arguments it sets the value, and you can
504 %automagic, of course). With arguments it sets the value, and you can
505 use any of (case insensitive):
505 use any of (case insensitive):
506
506
507 - on,1,True: to activate
507 - on,1,True: to activate
508
508
509 - off,0,False: to deactivate.
509 - off,0,False: to deactivate.
510
510
511 Note that magic functions have lowest priority, so if there's a
511 Note that magic functions have lowest priority, so if there's a
512 variable whose name collides with that of a magic fn, automagic won't
512 variable whose name collides with that of a magic fn, automagic won't
513 work for that function (you get the variable instead). However, if you
513 work for that function (you get the variable instead). However, if you
514 delete the variable (del var), the previously shadowed magic function
514 delete the variable (del var), the previously shadowed magic function
515 becomes visible to automagic again."""
515 becomes visible to automagic again."""
516
516
517 arg = parameter_s.lower()
517 arg = parameter_s.lower()
518 if parameter_s in ('on','1','true'):
518 if parameter_s in ('on','1','true'):
519 self.shell.automagic = True
519 self.shell.automagic = True
520 elif parameter_s in ('off','0','false'):
520 elif parameter_s in ('off','0','false'):
521 self.shell.automagic = False
521 self.shell.automagic = False
522 else:
522 else:
523 self.shell.automagic = not self.shell.automagic
523 self.shell.automagic = not self.shell.automagic
524 print '\n' + Magic.auto_status[self.shell.automagic]
524 print '\n' + Magic.auto_status[self.shell.automagic]
525
525
526 @testdec.skip_doctest
526 @testdec.skip_doctest
527 def magic_autocall(self, parameter_s = ''):
527 def magic_autocall(self, parameter_s = ''):
528 """Make functions callable without having to type parentheses.
528 """Make functions callable without having to type parentheses.
529
529
530 Usage:
530 Usage:
531
531
532 %autocall [mode]
532 %autocall [mode]
533
533
534 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
534 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
535 value is toggled on and off (remembering the previous state).
535 value is toggled on and off (remembering the previous state).
536
536
537 In more detail, these values mean:
537 In more detail, these values mean:
538
538
539 0 -> fully disabled
539 0 -> fully disabled
540
540
541 1 -> active, but do not apply if there are no arguments on the line.
541 1 -> active, but do not apply if there are no arguments on the line.
542
542
543 In this mode, you get:
543 In this mode, you get:
544
544
545 In [1]: callable
545 In [1]: callable
546 Out[1]: <built-in function callable>
546 Out[1]: <built-in function callable>
547
547
548 In [2]: callable 'hello'
548 In [2]: callable 'hello'
549 ------> callable('hello')
549 ------> callable('hello')
550 Out[2]: False
550 Out[2]: False
551
551
552 2 -> Active always. Even if no arguments are present, the callable
552 2 -> Active always. Even if no arguments are present, the callable
553 object is called:
553 object is called:
554
554
555 In [2]: float
555 In [2]: float
556 ------> float()
556 ------> float()
557 Out[2]: 0.0
557 Out[2]: 0.0
558
558
559 Note that even with autocall off, you can still use '/' at the start of
559 Note that even with autocall off, you can still use '/' at the start of
560 a line to treat the first argument on the command line as a function
560 a line to treat the first argument on the command line as a function
561 and add parentheses to it:
561 and add parentheses to it:
562
562
563 In [8]: /str 43
563 In [8]: /str 43
564 ------> str(43)
564 ------> str(43)
565 Out[8]: '43'
565 Out[8]: '43'
566
566
567 # all-random (note for auto-testing)
567 # all-random (note for auto-testing)
568 """
568 """
569
569
570 if parameter_s:
570 if parameter_s:
571 arg = int(parameter_s)
571 arg = int(parameter_s)
572 else:
572 else:
573 arg = 'toggle'
573 arg = 'toggle'
574
574
575 if not arg in (0,1,2,'toggle'):
575 if not arg in (0,1,2,'toggle'):
576 error('Valid modes: (0->Off, 1->Smart, 2->Full')
576 error('Valid modes: (0->Off, 1->Smart, 2->Full')
577 return
577 return
578
578
579 if arg in (0,1,2):
579 if arg in (0,1,2):
580 self.shell.autocall = arg
580 self.shell.autocall = arg
581 else: # toggle
581 else: # toggle
582 if self.shell.autocall:
582 if self.shell.autocall:
583 self._magic_state.autocall_save = self.shell.autocall
583 self._magic_state.autocall_save = self.shell.autocall
584 self.shell.autocall = 0
584 self.shell.autocall = 0
585 else:
585 else:
586 try:
586 try:
587 self.shell.autocall = self._magic_state.autocall_save
587 self.shell.autocall = self._magic_state.autocall_save
588 except AttributeError:
588 except AttributeError:
589 self.shell.autocall = self._magic_state.autocall_save = 1
589 self.shell.autocall = self._magic_state.autocall_save = 1
590
590
591 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
591 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
592
592
593 def magic_system_verbose(self, parameter_s = ''):
593 def magic_system_verbose(self, parameter_s = ''):
594 """Set verbose printing of system calls.
594 """Set verbose printing of system calls.
595
595
596 If called without an argument, act as a toggle"""
596 If called without an argument, act as a toggle"""
597
597
598 if parameter_s:
598 if parameter_s:
599 val = bool(eval(parameter_s))
599 val = bool(eval(parameter_s))
600 else:
600 else:
601 val = None
601 val = None
602
602
603 if self.shell.system_verbose:
603 if self.shell.system_verbose:
604 self.shell.system_verbose = False
604 self.shell.system_verbose = False
605 else:
605 else:
606 self.shell.system_verbose = True
606 self.shell.system_verbose = True
607 print "System verbose printing is:",\
607 print "System verbose printing is:",\
608 ['OFF','ON'][self.shell.system_verbose]
608 ['OFF','ON'][self.shell.system_verbose]
609
609
610
610
611 def magic_page(self, parameter_s=''):
611 def magic_page(self, parameter_s=''):
612 """Pretty print the object and display it through a pager.
612 """Pretty print the object and display it through a pager.
613
613
614 %page [options] OBJECT
614 %page [options] OBJECT
615
615
616 If no object is given, use _ (last output).
616 If no object is given, use _ (last output).
617
617
618 Options:
618 Options:
619
619
620 -r: page str(object), don't pretty-print it."""
620 -r: page str(object), don't pretty-print it."""
621
621
622 # After a function contributed by Olivier Aubert, slightly modified.
622 # After a function contributed by Olivier Aubert, slightly modified.
623
623
624 # Process options/args
624 # Process options/args
625 opts,args = self.parse_options(parameter_s,'r')
625 opts,args = self.parse_options(parameter_s,'r')
626 raw = 'r' in opts
626 raw = 'r' in opts
627
627
628 oname = args and args or '_'
628 oname = args and args or '_'
629 info = self._ofind(oname)
629 info = self._ofind(oname)
630 if info['found']:
630 if info['found']:
631 txt = (raw and str or pformat)( info['obj'] )
631 txt = (raw and str or pformat)( info['obj'] )
632 page(txt)
632 page(txt)
633 else:
633 else:
634 print 'Object `%s` not found' % oname
634 print 'Object `%s` not found' % oname
635
635
636 def magic_profile(self, parameter_s=''):
636 def magic_profile(self, parameter_s=''):
637 """Print your currently active IPyhton profile."""
637 """Print your currently active IPyhton profile."""
638 if self.shell.profile:
638 if self.shell.profile:
639 printpl('Current IPython profile: $self.shell.profile.')
639 printpl('Current IPython profile: $self.shell.profile.')
640 else:
640 else:
641 print 'No profile active.'
641 print 'No profile active.'
642
642
643 def magic_pinfo(self, parameter_s='', namespaces=None):
643 def magic_pinfo(self, parameter_s='', namespaces=None):
644 """Provide detailed information about an object.
644 """Provide detailed information about an object.
645
645
646 '%pinfo object' is just a synonym for object? or ?object."""
646 '%pinfo object' is just a synonym for object? or ?object."""
647
647
648 #print 'pinfo par: <%s>' % parameter_s # dbg
648 #print 'pinfo par: <%s>' % parameter_s # dbg
649
649
650
650
651 # detail_level: 0 -> obj? , 1 -> obj??
651 # detail_level: 0 -> obj? , 1 -> obj??
652 detail_level = 0
652 detail_level = 0
653 # We need to detect if we got called as 'pinfo pinfo foo', which can
653 # We need to detect if we got called as 'pinfo pinfo foo', which can
654 # happen if the user types 'pinfo foo?' at the cmd line.
654 # happen if the user types 'pinfo foo?' at the cmd line.
655 pinfo,qmark1,oname,qmark2 = \
655 pinfo,qmark1,oname,qmark2 = \
656 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
656 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
657 if pinfo or qmark1 or qmark2:
657 if pinfo or qmark1 or qmark2:
658 detail_level = 1
658 detail_level = 1
659 if "*" in oname:
659 if "*" in oname:
660 self.magic_psearch(oname)
660 self.magic_psearch(oname)
661 else:
661 else:
662 self._inspect('pinfo', oname, detail_level=detail_level,
662 self._inspect('pinfo', oname, detail_level=detail_level,
663 namespaces=namespaces)
663 namespaces=namespaces)
664
664
665 def magic_pdef(self, parameter_s='', namespaces=None):
665 def magic_pdef(self, parameter_s='', namespaces=None):
666 """Print the definition header for any callable object.
666 """Print the definition header for any callable object.
667
667
668 If the object is a class, print the constructor information."""
668 If the object is a class, print the constructor information."""
669 self._inspect('pdef',parameter_s, namespaces)
669 self._inspect('pdef',parameter_s, namespaces)
670
670
671 def magic_pdoc(self, parameter_s='', namespaces=None):
671 def magic_pdoc(self, parameter_s='', namespaces=None):
672 """Print the docstring for an object.
672 """Print the docstring for an object.
673
673
674 If the given object is a class, it will print both the class and the
674 If the given object is a class, it will print both the class and the
675 constructor docstrings."""
675 constructor docstrings."""
676 self._inspect('pdoc',parameter_s, namespaces)
676 self._inspect('pdoc',parameter_s, namespaces)
677
677
678 def magic_psource(self, parameter_s='', namespaces=None):
678 def magic_psource(self, parameter_s='', namespaces=None):
679 """Print (or run through pager) the source code for an object."""
679 """Print (or run through pager) the source code for an object."""
680 self._inspect('psource',parameter_s, namespaces)
680 self._inspect('psource',parameter_s, namespaces)
681
681
682 def magic_pfile(self, parameter_s=''):
682 def magic_pfile(self, parameter_s=''):
683 """Print (or run through pager) the file where an object is defined.
683 """Print (or run through pager) the file where an object is defined.
684
684
685 The file opens at the line where the object definition begins. IPython
685 The file opens at the line where the object definition begins. IPython
686 will honor the environment variable PAGER if set, and otherwise will
686 will honor the environment variable PAGER if set, and otherwise will
687 do its best to print the file in a convenient form.
687 do its best to print the file in a convenient form.
688
688
689 If the given argument is not an object currently defined, IPython will
689 If the given argument is not an object currently defined, IPython will
690 try to interpret it as a filename (automatically adding a .py extension
690 try to interpret it as a filename (automatically adding a .py extension
691 if needed). You can thus use %pfile as a syntax highlighting code
691 if needed). You can thus use %pfile as a syntax highlighting code
692 viewer."""
692 viewer."""
693
693
694 # first interpret argument as an object name
694 # first interpret argument as an object name
695 out = self._inspect('pfile',parameter_s)
695 out = self._inspect('pfile',parameter_s)
696 # if not, try the input as a filename
696 # if not, try the input as a filename
697 if out == 'not found':
697 if out == 'not found':
698 try:
698 try:
699 filename = get_py_filename(parameter_s)
699 filename = get_py_filename(parameter_s)
700 except IOError,msg:
700 except IOError,msg:
701 print msg
701 print msg
702 return
702 return
703 page(self.shell.inspector.format(file(filename).read()))
703 page(self.shell.inspector.format(file(filename).read()))
704
704
705 def _inspect(self,meth,oname,namespaces=None,**kw):
705 def _inspect(self,meth,oname,namespaces=None,**kw):
706 """Generic interface to the inspector system.
706 """Generic interface to the inspector system.
707
707
708 This function is meant to be called by pdef, pdoc & friends."""
708 This function is meant to be called by pdef, pdoc & friends."""
709
709
710 #oname = oname.strip()
710 #oname = oname.strip()
711 #print '1- oname: <%r>' % oname # dbg
711 #print '1- oname: <%r>' % oname # dbg
712 try:
712 try:
713 oname = oname.strip().encode('ascii')
713 oname = oname.strip().encode('ascii')
714 #print '2- oname: <%r>' % oname # dbg
714 #print '2- oname: <%r>' % oname # dbg
715 except UnicodeEncodeError:
715 except UnicodeEncodeError:
716 print 'Python identifiers can only contain ascii characters.'
716 print 'Python identifiers can only contain ascii characters.'
717 return 'not found'
717 return 'not found'
718
718
719 info = Struct(self._ofind(oname, namespaces))
719 info = Struct(self._ofind(oname, namespaces))
720
720
721 if info.found:
721 if info.found:
722 try:
722 try:
723 IPython.utils.generics.inspect_object(info.obj)
723 IPython.utils.generics.inspect_object(info.obj)
724 return
724 return
725 except TryNext:
725 except TryNext:
726 pass
726 pass
727 # Get the docstring of the class property if it exists.
727 # Get the docstring of the class property if it exists.
728 path = oname.split('.')
728 path = oname.split('.')
729 root = '.'.join(path[:-1])
729 root = '.'.join(path[:-1])
730 if info.parent is not None:
730 if info.parent is not None:
731 try:
731 try:
732 target = getattr(info.parent, '__class__')
732 target = getattr(info.parent, '__class__')
733 # The object belongs to a class instance.
733 # The object belongs to a class instance.
734 try:
734 try:
735 target = getattr(target, path[-1])
735 target = getattr(target, path[-1])
736 # The class defines the object.
736 # The class defines the object.
737 if isinstance(target, property):
737 if isinstance(target, property):
738 oname = root + '.__class__.' + path[-1]
738 oname = root + '.__class__.' + path[-1]
739 info = Struct(self._ofind(oname))
739 info = Struct(self._ofind(oname))
740 except AttributeError: pass
740 except AttributeError: pass
741 except AttributeError: pass
741 except AttributeError: pass
742
742
743 pmethod = getattr(self.shell.inspector,meth)
743 pmethod = getattr(self.shell.inspector,meth)
744 formatter = info.ismagic and self.format_screen or None
744 formatter = info.ismagic and self.format_screen or None
745 if meth == 'pdoc':
745 if meth == 'pdoc':
746 pmethod(info.obj,oname,formatter)
746 pmethod(info.obj,oname,formatter)
747 elif meth == 'pinfo':
747 elif meth == 'pinfo':
748 pmethod(info.obj,oname,formatter,info,**kw)
748 pmethod(info.obj,oname,formatter,info,**kw)
749 else:
749 else:
750 pmethod(info.obj,oname)
750 pmethod(info.obj,oname)
751 else:
751 else:
752 print 'Object `%s` not found.' % oname
752 print 'Object `%s` not found.' % oname
753 return 'not found' # so callers can take other action
753 return 'not found' # so callers can take other action
754
754
755 def magic_psearch(self, parameter_s=''):
755 def magic_psearch(self, parameter_s=''):
756 """Search for object in namespaces by wildcard.
756 """Search for object in namespaces by wildcard.
757
757
758 %psearch [options] PATTERN [OBJECT TYPE]
758 %psearch [options] PATTERN [OBJECT TYPE]
759
759
760 Note: ? can be used as a synonym for %psearch, at the beginning or at
760 Note: ? can be used as a synonym for %psearch, at the beginning or at
761 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
761 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
762 rest of the command line must be unchanged (options come first), so
762 rest of the command line must be unchanged (options come first), so
763 for example the following forms are equivalent
763 for example the following forms are equivalent
764
764
765 %psearch -i a* function
765 %psearch -i a* function
766 -i a* function?
766 -i a* function?
767 ?-i a* function
767 ?-i a* function
768
768
769 Arguments:
769 Arguments:
770
770
771 PATTERN
771 PATTERN
772
772
773 where PATTERN is a string containing * as a wildcard similar to its
773 where PATTERN is a string containing * as a wildcard similar to its
774 use in a shell. The pattern is matched in all namespaces on the
774 use in a shell. The pattern is matched in all namespaces on the
775 search path. By default objects starting with a single _ are not
775 search path. By default objects starting with a single _ are not
776 matched, many IPython generated objects have a single
776 matched, many IPython generated objects have a single
777 underscore. The default is case insensitive matching. Matching is
777 underscore. The default is case insensitive matching. Matching is
778 also done on the attributes of objects and not only on the objects
778 also done on the attributes of objects and not only on the objects
779 in a module.
779 in a module.
780
780
781 [OBJECT TYPE]
781 [OBJECT TYPE]
782
782
783 Is the name of a python type from the types module. The name is
783 Is the name of a python type from the types module. The name is
784 given in lowercase without the ending type, ex. StringType is
784 given in lowercase without the ending type, ex. StringType is
785 written string. By adding a type here only objects matching the
785 written string. By adding a type here only objects matching the
786 given type are matched. Using all here makes the pattern match all
786 given type are matched. Using all here makes the pattern match all
787 types (this is the default).
787 types (this is the default).
788
788
789 Options:
789 Options:
790
790
791 -a: makes the pattern match even objects whose names start with a
791 -a: makes the pattern match even objects whose names start with a
792 single underscore. These names are normally ommitted from the
792 single underscore. These names are normally ommitted from the
793 search.
793 search.
794
794
795 -i/-c: make the pattern case insensitive/sensitive. If neither of
795 -i/-c: make the pattern case insensitive/sensitive. If neither of
796 these options is given, the default is read from your ipythonrc
796 these options is given, the default is read from your ipythonrc
797 file. The option name which sets this value is
797 file. The option name which sets this value is
798 'wildcards_case_sensitive'. If this option is not specified in your
798 'wildcards_case_sensitive'. If this option is not specified in your
799 ipythonrc file, IPython's internal default is to do a case sensitive
799 ipythonrc file, IPython's internal default is to do a case sensitive
800 search.
800 search.
801
801
802 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
802 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
803 specifiy can be searched in any of the following namespaces:
803 specifiy can be searched in any of the following namespaces:
804 'builtin', 'user', 'user_global','internal', 'alias', where
804 'builtin', 'user', 'user_global','internal', 'alias', where
805 'builtin' and 'user' are the search defaults. Note that you should
805 'builtin' and 'user' are the search defaults. Note that you should
806 not use quotes when specifying namespaces.
806 not use quotes when specifying namespaces.
807
807
808 'Builtin' contains the python module builtin, 'user' contains all
808 'Builtin' contains the python module builtin, 'user' contains all
809 user data, 'alias' only contain the shell aliases and no python
809 user data, 'alias' only contain the shell aliases and no python
810 objects, 'internal' contains objects used by IPython. The
810 objects, 'internal' contains objects used by IPython. The
811 'user_global' namespace is only used by embedded IPython instances,
811 'user_global' namespace is only used by embedded IPython instances,
812 and it contains module-level globals. You can add namespaces to the
812 and it contains module-level globals. You can add namespaces to the
813 search with -s or exclude them with -e (these options can be given
813 search with -s or exclude them with -e (these options can be given
814 more than once).
814 more than once).
815
815
816 Examples:
816 Examples:
817
817
818 %psearch a* -> objects beginning with an a
818 %psearch a* -> objects beginning with an a
819 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
819 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
820 %psearch a* function -> all functions beginning with an a
820 %psearch a* function -> all functions beginning with an a
821 %psearch re.e* -> objects beginning with an e in module re
821 %psearch re.e* -> objects beginning with an e in module re
822 %psearch r*.e* -> objects that start with e in modules starting in r
822 %psearch r*.e* -> objects that start with e in modules starting in r
823 %psearch r*.* string -> all strings in modules beginning with r
823 %psearch r*.* string -> all strings in modules beginning with r
824
824
825 Case sensitve search:
825 Case sensitve search:
826
826
827 %psearch -c a* list all object beginning with lower case a
827 %psearch -c a* list all object beginning with lower case a
828
828
829 Show objects beginning with a single _:
829 Show objects beginning with a single _:
830
830
831 %psearch -a _* list objects beginning with a single underscore"""
831 %psearch -a _* list objects beginning with a single underscore"""
832 try:
832 try:
833 parameter_s = parameter_s.encode('ascii')
833 parameter_s = parameter_s.encode('ascii')
834 except UnicodeEncodeError:
834 except UnicodeEncodeError:
835 print 'Python identifiers can only contain ascii characters.'
835 print 'Python identifiers can only contain ascii characters.'
836 return
836 return
837
837
838 # default namespaces to be searched
838 # default namespaces to be searched
839 def_search = ['user','builtin']
839 def_search = ['user','builtin']
840
840
841 # Process options/args
841 # Process options/args
842 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
842 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
843 opt = opts.get
843 opt = opts.get
844 shell = self.shell
844 shell = self.shell
845 psearch = shell.inspector.psearch
845 psearch = shell.inspector.psearch
846
846
847 # select case options
847 # select case options
848 if opts.has_key('i'):
848 if opts.has_key('i'):
849 ignore_case = True
849 ignore_case = True
850 elif opts.has_key('c'):
850 elif opts.has_key('c'):
851 ignore_case = False
851 ignore_case = False
852 else:
852 else:
853 ignore_case = not shell.wildcards_case_sensitive
853 ignore_case = not shell.wildcards_case_sensitive
854
854
855 # Build list of namespaces to search from user options
855 # Build list of namespaces to search from user options
856 def_search.extend(opt('s',[]))
856 def_search.extend(opt('s',[]))
857 ns_exclude = ns_exclude=opt('e',[])
857 ns_exclude = ns_exclude=opt('e',[])
858 ns_search = [nm for nm in def_search if nm not in ns_exclude]
858 ns_search = [nm for nm in def_search if nm not in ns_exclude]
859
859
860 # Call the actual search
860 # Call the actual search
861 try:
861 try:
862 psearch(args,shell.ns_table,ns_search,
862 psearch(args,shell.ns_table,ns_search,
863 show_all=opt('a'),ignore_case=ignore_case)
863 show_all=opt('a'),ignore_case=ignore_case)
864 except:
864 except:
865 shell.showtraceback()
865 shell.showtraceback()
866
866
867 def magic_who_ls(self, parameter_s=''):
867 def magic_who_ls(self, parameter_s=''):
868 """Return a sorted list of all interactive variables.
868 """Return a sorted list of all interactive variables.
869
869
870 If arguments are given, only variables of types matching these
870 If arguments are given, only variables of types matching these
871 arguments are returned."""
871 arguments are returned."""
872
872
873 user_ns = self.shell.user_ns
873 user_ns = self.shell.user_ns
874 internal_ns = self.shell.internal_ns
874 internal_ns = self.shell.internal_ns
875 user_config_ns = self.shell.user_config_ns
875 user_config_ns = self.shell.user_config_ns
876 out = []
876 out = []
877 typelist = parameter_s.split()
877 typelist = parameter_s.split()
878
878
879 for i in user_ns:
879 for i in user_ns:
880 if not (i.startswith('_') or i.startswith('_i')) \
880 if not (i.startswith('_') or i.startswith('_i')) \
881 and not (i in internal_ns or i in user_config_ns):
881 and not (i in internal_ns or i in user_config_ns):
882 if typelist:
882 if typelist:
883 if type(user_ns[i]).__name__ in typelist:
883 if type(user_ns[i]).__name__ in typelist:
884 out.append(i)
884 out.append(i)
885 else:
885 else:
886 out.append(i)
886 out.append(i)
887 out.sort()
887 out.sort()
888 return out
888 return out
889
889
890 def magic_who(self, parameter_s=''):
890 def magic_who(self, parameter_s=''):
891 """Print all interactive variables, with some minimal formatting.
891 """Print all interactive variables, with some minimal formatting.
892
892
893 If any arguments are given, only variables whose type matches one of
893 If any arguments are given, only variables whose type matches one of
894 these are printed. For example:
894 these are printed. For example:
895
895
896 %who function str
896 %who function str
897
897
898 will only list functions and strings, excluding all other types of
898 will only list functions and strings, excluding all other types of
899 variables. To find the proper type names, simply use type(var) at a
899 variables. To find the proper type names, simply use type(var) at a
900 command line to see how python prints type names. For example:
900 command line to see how python prints type names. For example:
901
901
902 In [1]: type('hello')\\
902 In [1]: type('hello')\\
903 Out[1]: <type 'str'>
903 Out[1]: <type 'str'>
904
904
905 indicates that the type name for strings is 'str'.
905 indicates that the type name for strings is 'str'.
906
906
907 %who always excludes executed names loaded through your configuration
907 %who always excludes executed names loaded through your configuration
908 file and things which are internal to IPython.
908 file and things which are internal to IPython.
909
909
910 This is deliberate, as typically you may load many modules and the
910 This is deliberate, as typically you may load many modules and the
911 purpose of %who is to show you only what you've manually defined."""
911 purpose of %who is to show you only what you've manually defined."""
912
912
913 varlist = self.magic_who_ls(parameter_s)
913 varlist = self.magic_who_ls(parameter_s)
914 if not varlist:
914 if not varlist:
915 if parameter_s:
915 if parameter_s:
916 print 'No variables match your requested type.'
916 print 'No variables match your requested type.'
917 else:
917 else:
918 print 'Interactive namespace is empty.'
918 print 'Interactive namespace is empty.'
919 return
919 return
920
920
921 # if we have variables, move on...
921 # if we have variables, move on...
922 count = 0
922 count = 0
923 for i in varlist:
923 for i in varlist:
924 print i+'\t',
924 print i+'\t',
925 count += 1
925 count += 1
926 if count > 8:
926 if count > 8:
927 count = 0
927 count = 0
928 print
928 print
929 print
929 print
930
930
931 def magic_whos(self, parameter_s=''):
931 def magic_whos(self, parameter_s=''):
932 """Like %who, but gives some extra information about each variable.
932 """Like %who, but gives some extra information about each variable.
933
933
934 The same type filtering of %who can be applied here.
934 The same type filtering of %who can be applied here.
935
935
936 For all variables, the type is printed. Additionally it prints:
936 For all variables, the type is printed. Additionally it prints:
937
937
938 - For {},[],(): their length.
938 - For {},[],(): their length.
939
939
940 - For numpy and Numeric arrays, a summary with shape, number of
940 - For numpy and Numeric arrays, a summary with shape, number of
941 elements, typecode and size in memory.
941 elements, typecode and size in memory.
942
942
943 - Everything else: a string representation, snipping their middle if
943 - Everything else: a string representation, snipping their middle if
944 too long."""
944 too long."""
945
945
946 varnames = self.magic_who_ls(parameter_s)
946 varnames = self.magic_who_ls(parameter_s)
947 if not varnames:
947 if not varnames:
948 if parameter_s:
948 if parameter_s:
949 print 'No variables match your requested type.'
949 print 'No variables match your requested type.'
950 else:
950 else:
951 print 'Interactive namespace is empty.'
951 print 'Interactive namespace is empty.'
952 return
952 return
953
953
954 # if we have variables, move on...
954 # if we have variables, move on...
955
955
956 # for these types, show len() instead of data:
956 # for these types, show len() instead of data:
957 seq_types = [types.DictType,types.ListType,types.TupleType]
957 seq_types = [types.DictType,types.ListType,types.TupleType]
958
958
959 # for numpy/Numeric arrays, display summary info
959 # for numpy/Numeric arrays, display summary info
960 try:
960 try:
961 import numpy
961 import numpy
962 except ImportError:
962 except ImportError:
963 ndarray_type = None
963 ndarray_type = None
964 else:
964 else:
965 ndarray_type = numpy.ndarray.__name__
965 ndarray_type = numpy.ndarray.__name__
966 try:
966 try:
967 import Numeric
967 import Numeric
968 except ImportError:
968 except ImportError:
969 array_type = None
969 array_type = None
970 else:
970 else:
971 array_type = Numeric.ArrayType.__name__
971 array_type = Numeric.ArrayType.__name__
972
972
973 # Find all variable names and types so we can figure out column sizes
973 # Find all variable names and types so we can figure out column sizes
974 def get_vars(i):
974 def get_vars(i):
975 return self.shell.user_ns[i]
975 return self.shell.user_ns[i]
976
976
977 # some types are well known and can be shorter
977 # some types are well known and can be shorter
978 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
978 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
979 def type_name(v):
979 def type_name(v):
980 tn = type(v).__name__
980 tn = type(v).__name__
981 return abbrevs.get(tn,tn)
981 return abbrevs.get(tn,tn)
982
982
983 varlist = map(get_vars,varnames)
983 varlist = map(get_vars,varnames)
984
984
985 typelist = []
985 typelist = []
986 for vv in varlist:
986 for vv in varlist:
987 tt = type_name(vv)
987 tt = type_name(vv)
988
988
989 if tt=='instance':
989 if tt=='instance':
990 typelist.append( abbrevs.get(str(vv.__class__),
990 typelist.append( abbrevs.get(str(vv.__class__),
991 str(vv.__class__)))
991 str(vv.__class__)))
992 else:
992 else:
993 typelist.append(tt)
993 typelist.append(tt)
994
994
995 # column labels and # of spaces as separator
995 # column labels and # of spaces as separator
996 varlabel = 'Variable'
996 varlabel = 'Variable'
997 typelabel = 'Type'
997 typelabel = 'Type'
998 datalabel = 'Data/Info'
998 datalabel = 'Data/Info'
999 colsep = 3
999 colsep = 3
1000 # variable format strings
1000 # variable format strings
1001 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1001 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1002 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1002 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1003 aformat = "%s: %s elems, type `%s`, %s bytes"
1003 aformat = "%s: %s elems, type `%s`, %s bytes"
1004 # find the size of the columns to format the output nicely
1004 # find the size of the columns to format the output nicely
1005 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1005 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1006 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1006 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1007 # table header
1007 # table header
1008 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1008 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1009 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1009 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1010 # and the table itself
1010 # and the table itself
1011 kb = 1024
1011 kb = 1024
1012 Mb = 1048576 # kb**2
1012 Mb = 1048576 # kb**2
1013 for vname,var,vtype in zip(varnames,varlist,typelist):
1013 for vname,var,vtype in zip(varnames,varlist,typelist):
1014 print itpl(vformat),
1014 print itpl(vformat),
1015 if vtype in seq_types:
1015 if vtype in seq_types:
1016 print len(var)
1016 print len(var)
1017 elif vtype in [array_type,ndarray_type]:
1017 elif vtype in [array_type,ndarray_type]:
1018 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1018 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1019 if vtype==ndarray_type:
1019 if vtype==ndarray_type:
1020 # numpy
1020 # numpy
1021 vsize = var.size
1021 vsize = var.size
1022 vbytes = vsize*var.itemsize
1022 vbytes = vsize*var.itemsize
1023 vdtype = var.dtype
1023 vdtype = var.dtype
1024 else:
1024 else:
1025 # Numeric
1025 # Numeric
1026 vsize = Numeric.size(var)
1026 vsize = Numeric.size(var)
1027 vbytes = vsize*var.itemsize()
1027 vbytes = vsize*var.itemsize()
1028 vdtype = var.typecode()
1028 vdtype = var.typecode()
1029
1029
1030 if vbytes < 100000:
1030 if vbytes < 100000:
1031 print aformat % (vshape,vsize,vdtype,vbytes)
1031 print aformat % (vshape,vsize,vdtype,vbytes)
1032 else:
1032 else:
1033 print aformat % (vshape,vsize,vdtype,vbytes),
1033 print aformat % (vshape,vsize,vdtype,vbytes),
1034 if vbytes < Mb:
1034 if vbytes < Mb:
1035 print '(%s kb)' % (vbytes/kb,)
1035 print '(%s kb)' % (vbytes/kb,)
1036 else:
1036 else:
1037 print '(%s Mb)' % (vbytes/Mb,)
1037 print '(%s Mb)' % (vbytes/Mb,)
1038 else:
1038 else:
1039 try:
1039 try:
1040 vstr = str(var)
1040 vstr = str(var)
1041 except UnicodeEncodeError:
1041 except UnicodeEncodeError:
1042 vstr = unicode(var).encode(sys.getdefaultencoding(),
1042 vstr = unicode(var).encode(sys.getdefaultencoding(),
1043 'backslashreplace')
1043 'backslashreplace')
1044 vstr = vstr.replace('\n','\\n')
1044 vstr = vstr.replace('\n','\\n')
1045 if len(vstr) < 50:
1045 if len(vstr) < 50:
1046 print vstr
1046 print vstr
1047 else:
1047 else:
1048 printpl(vfmt_short)
1048 printpl(vfmt_short)
1049
1049
1050 def magic_reset(self, parameter_s=''):
1050 def magic_reset(self, parameter_s=''):
1051 """Resets the namespace by removing all names defined by the user.
1051 """Resets the namespace by removing all names defined by the user.
1052
1052
1053 Input/Output history are left around in case you need them.
1053 Input/Output history are left around in case you need them.
1054
1054
1055 Parameters
1055 Parameters
1056 ----------
1056 ----------
1057 -y : force reset without asking for confirmation.
1057 -y : force reset without asking for confirmation.
1058
1058
1059 Examples
1059 Examples
1060 --------
1060 --------
1061 In [6]: a = 1
1061 In [6]: a = 1
1062
1062
1063 In [7]: a
1063 In [7]: a
1064 Out[7]: 1
1064 Out[7]: 1
1065
1065
1066 In [8]: 'a' in _ip.user_ns
1066 In [8]: 'a' in _ip.user_ns
1067 Out[8]: True
1067 Out[8]: True
1068
1068
1069 In [9]: %reset -f
1069 In [9]: %reset -f
1070
1070
1071 In [10]: 'a' in _ip.user_ns
1071 In [10]: 'a' in _ip.user_ns
1072 Out[10]: False
1072 Out[10]: False
1073 """
1073 """
1074
1074
1075 if parameter_s == '-f':
1075 if parameter_s == '-f':
1076 ans = True
1076 ans = True
1077 else:
1077 else:
1078 ans = self.shell.ask_yes_no(
1078 ans = self.shell.ask_yes_no(
1079 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1079 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1080 if not ans:
1080 if not ans:
1081 print 'Nothing done.'
1081 print 'Nothing done.'
1082 return
1082 return
1083 user_ns = self.shell.user_ns
1083 user_ns = self.shell.user_ns
1084 for i in self.magic_who_ls():
1084 for i in self.magic_who_ls():
1085 del(user_ns[i])
1085 del(user_ns[i])
1086
1086
1087 # Also flush the private list of module references kept for script
1087 # Also flush the private list of module references kept for script
1088 # execution protection
1088 # execution protection
1089 self.shell.clear_main_mod_cache()
1089 self.shell.clear_main_mod_cache()
1090
1090
1091 def magic_logstart(self,parameter_s=''):
1091 def magic_logstart(self,parameter_s=''):
1092 """Start logging anywhere in a session.
1092 """Start logging anywhere in a session.
1093
1093
1094 %logstart [-o|-r|-t] [log_name [log_mode]]
1094 %logstart [-o|-r|-t] [log_name [log_mode]]
1095
1095
1096 If no name is given, it defaults to a file named 'ipython_log.py' in your
1096 If no name is given, it defaults to a file named 'ipython_log.py' in your
1097 current directory, in 'rotate' mode (see below).
1097 current directory, in 'rotate' mode (see below).
1098
1098
1099 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1099 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1100 history up to that point and then continues logging.
1100 history up to that point and then continues logging.
1101
1101
1102 %logstart takes a second optional parameter: logging mode. This can be one
1102 %logstart takes a second optional parameter: logging mode. This can be one
1103 of (note that the modes are given unquoted):\\
1103 of (note that the modes are given unquoted):\\
1104 append: well, that says it.\\
1104 append: well, that says it.\\
1105 backup: rename (if exists) to name~ and start name.\\
1105 backup: rename (if exists) to name~ and start name.\\
1106 global: single logfile in your home dir, appended to.\\
1106 global: single logfile in your home dir, appended to.\\
1107 over : overwrite existing log.\\
1107 over : overwrite existing log.\\
1108 rotate: create rotating logs name.1~, name.2~, etc.
1108 rotate: create rotating logs name.1~, name.2~, etc.
1109
1109
1110 Options:
1110 Options:
1111
1111
1112 -o: log also IPython's output. In this mode, all commands which
1112 -o: log also IPython's output. In this mode, all commands which
1113 generate an Out[NN] prompt are recorded to the logfile, right after
1113 generate an Out[NN] prompt are recorded to the logfile, right after
1114 their corresponding input line. The output lines are always
1114 their corresponding input line. The output lines are always
1115 prepended with a '#[Out]# ' marker, so that the log remains valid
1115 prepended with a '#[Out]# ' marker, so that the log remains valid
1116 Python code.
1116 Python code.
1117
1117
1118 Since this marker is always the same, filtering only the output from
1118 Since this marker is always the same, filtering only the output from
1119 a log is very easy, using for example a simple awk call:
1119 a log is very easy, using for example a simple awk call:
1120
1120
1121 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1121 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1122
1122
1123 -r: log 'raw' input. Normally, IPython's logs contain the processed
1123 -r: log 'raw' input. Normally, IPython's logs contain the processed
1124 input, so that user lines are logged in their final form, converted
1124 input, so that user lines are logged in their final form, converted
1125 into valid Python. For example, %Exit is logged as
1125 into valid Python. For example, %Exit is logged as
1126 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1126 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1127 exactly as typed, with no transformations applied.
1127 exactly as typed, with no transformations applied.
1128
1128
1129 -t: put timestamps before each input line logged (these are put in
1129 -t: put timestamps before each input line logged (these are put in
1130 comments)."""
1130 comments)."""
1131
1131
1132 opts,par = self.parse_options(parameter_s,'ort')
1132 opts,par = self.parse_options(parameter_s,'ort')
1133 log_output = 'o' in opts
1133 log_output = 'o' in opts
1134 log_raw_input = 'r' in opts
1134 log_raw_input = 'r' in opts
1135 timestamp = 't' in opts
1135 timestamp = 't' in opts
1136
1136
1137 logger = self.shell.logger
1137 logger = self.shell.logger
1138
1138
1139 # if no args are given, the defaults set in the logger constructor by
1139 # if no args are given, the defaults set in the logger constructor by
1140 # ipytohn remain valid
1140 # ipytohn remain valid
1141 if par:
1141 if par:
1142 try:
1142 try:
1143 logfname,logmode = par.split()
1143 logfname,logmode = par.split()
1144 except:
1144 except:
1145 logfname = par
1145 logfname = par
1146 logmode = 'backup'
1146 logmode = 'backup'
1147 else:
1147 else:
1148 logfname = logger.logfname
1148 logfname = logger.logfname
1149 logmode = logger.logmode
1149 logmode = logger.logmode
1150 # put logfname into rc struct as if it had been called on the command
1150 # put logfname into rc struct as if it had been called on the command
1151 # line, so it ends up saved in the log header Save it in case we need
1151 # line, so it ends up saved in the log header Save it in case we need
1152 # to restore it...
1152 # to restore it...
1153 old_logfile = self.shell.logfile
1153 old_logfile = self.shell.logfile
1154 if logfname:
1154 if logfname:
1155 logfname = os.path.expanduser(logfname)
1155 logfname = os.path.expanduser(logfname)
1156 self.shell.logfile = logfname
1156 self.shell.logfile = logfname
1157
1157
1158 loghead = '# IPython log file\n\n'
1158 loghead = '# IPython log file\n\n'
1159 try:
1159 try:
1160 started = logger.logstart(logfname,loghead,logmode,
1160 started = logger.logstart(logfname,loghead,logmode,
1161 log_output,timestamp,log_raw_input)
1161 log_output,timestamp,log_raw_input)
1162 except:
1162 except:
1163 rc.opts.logfile = old_logfile
1163 rc.opts.logfile = old_logfile
1164 warn("Couldn't start log: %s" % sys.exc_info()[1])
1164 warn("Couldn't start log: %s" % sys.exc_info()[1])
1165 else:
1165 else:
1166 # log input history up to this point, optionally interleaving
1166 # log input history up to this point, optionally interleaving
1167 # output if requested
1167 # output if requested
1168
1168
1169 if timestamp:
1169 if timestamp:
1170 # disable timestamping for the previous history, since we've
1170 # disable timestamping for the previous history, since we've
1171 # lost those already (no time machine here).
1171 # lost those already (no time machine here).
1172 logger.timestamp = False
1172 logger.timestamp = False
1173
1173
1174 if log_raw_input:
1174 if log_raw_input:
1175 input_hist = self.shell.input_hist_raw
1175 input_hist = self.shell.input_hist_raw
1176 else:
1176 else:
1177 input_hist = self.shell.input_hist
1177 input_hist = self.shell.input_hist
1178
1178
1179 if log_output:
1179 if log_output:
1180 log_write = logger.log_write
1180 log_write = logger.log_write
1181 output_hist = self.shell.output_hist
1181 output_hist = self.shell.output_hist
1182 for n in range(1,len(input_hist)-1):
1182 for n in range(1,len(input_hist)-1):
1183 log_write(input_hist[n].rstrip())
1183 log_write(input_hist[n].rstrip())
1184 if n in output_hist:
1184 if n in output_hist:
1185 log_write(repr(output_hist[n]),'output')
1185 log_write(repr(output_hist[n]),'output')
1186 else:
1186 else:
1187 logger.log_write(input_hist[1:])
1187 logger.log_write(input_hist[1:])
1188 if timestamp:
1188 if timestamp:
1189 # re-enable timestamping
1189 # re-enable timestamping
1190 logger.timestamp = True
1190 logger.timestamp = True
1191
1191
1192 print ('Activating auto-logging. '
1192 print ('Activating auto-logging. '
1193 'Current session state plus future input saved.')
1193 'Current session state plus future input saved.')
1194 logger.logstate()
1194 logger.logstate()
1195
1195
1196 def magic_logstop(self,parameter_s=''):
1196 def magic_logstop(self,parameter_s=''):
1197 """Fully stop logging and close log file.
1197 """Fully stop logging and close log file.
1198
1198
1199 In order to start logging again, a new %logstart call needs to be made,
1199 In order to start logging again, a new %logstart call needs to be made,
1200 possibly (though not necessarily) with a new filename, mode and other
1200 possibly (though not necessarily) with a new filename, mode and other
1201 options."""
1201 options."""
1202 self.logger.logstop()
1202 self.logger.logstop()
1203
1203
1204 def magic_logoff(self,parameter_s=''):
1204 def magic_logoff(self,parameter_s=''):
1205 """Temporarily stop logging.
1205 """Temporarily stop logging.
1206
1206
1207 You must have previously started logging."""
1207 You must have previously started logging."""
1208 self.shell.logger.switch_log(0)
1208 self.shell.logger.switch_log(0)
1209
1209
1210 def magic_logon(self,parameter_s=''):
1210 def magic_logon(self,parameter_s=''):
1211 """Restart logging.
1211 """Restart logging.
1212
1212
1213 This function is for restarting logging which you've temporarily
1213 This function is for restarting logging which you've temporarily
1214 stopped with %logoff. For starting logging for the first time, you
1214 stopped with %logoff. For starting logging for the first time, you
1215 must use the %logstart function, which allows you to specify an
1215 must use the %logstart function, which allows you to specify an
1216 optional log filename."""
1216 optional log filename."""
1217
1217
1218 self.shell.logger.switch_log(1)
1218 self.shell.logger.switch_log(1)
1219
1219
1220 def magic_logstate(self,parameter_s=''):
1220 def magic_logstate(self,parameter_s=''):
1221 """Print the status of the logging system."""
1221 """Print the status of the logging system."""
1222
1222
1223 self.shell.logger.logstate()
1223 self.shell.logger.logstate()
1224
1224
1225 def magic_pdb(self, parameter_s=''):
1225 def magic_pdb(self, parameter_s=''):
1226 """Control the automatic calling of the pdb interactive debugger.
1226 """Control the automatic calling of the pdb interactive debugger.
1227
1227
1228 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1228 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1229 argument it works as a toggle.
1229 argument it works as a toggle.
1230
1230
1231 When an exception is triggered, IPython can optionally call the
1231 When an exception is triggered, IPython can optionally call the
1232 interactive pdb debugger after the traceback printout. %pdb toggles
1232 interactive pdb debugger after the traceback printout. %pdb toggles
1233 this feature on and off.
1233 this feature on and off.
1234
1234
1235 The initial state of this feature is set in your ipythonrc
1235 The initial state of this feature is set in your ipythonrc
1236 configuration file (the variable is called 'pdb').
1236 configuration file (the variable is called 'pdb').
1237
1237
1238 If you want to just activate the debugger AFTER an exception has fired,
1238 If you want to just activate the debugger AFTER an exception has fired,
1239 without having to type '%pdb on' and rerunning your code, you can use
1239 without having to type '%pdb on' and rerunning your code, you can use
1240 the %debug magic."""
1240 the %debug magic."""
1241
1241
1242 par = parameter_s.strip().lower()
1242 par = parameter_s.strip().lower()
1243
1243
1244 if par:
1244 if par:
1245 try:
1245 try:
1246 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1246 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1247 except KeyError:
1247 except KeyError:
1248 print ('Incorrect argument. Use on/1, off/0, '
1248 print ('Incorrect argument. Use on/1, off/0, '
1249 'or nothing for a toggle.')
1249 'or nothing for a toggle.')
1250 return
1250 return
1251 else:
1251 else:
1252 # toggle
1252 # toggle
1253 new_pdb = not self.shell.call_pdb
1253 new_pdb = not self.shell.call_pdb
1254
1254
1255 # set on the shell
1255 # set on the shell
1256 self.shell.call_pdb = new_pdb
1256 self.shell.call_pdb = new_pdb
1257 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1257 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1258
1258
1259 def magic_debug(self, parameter_s=''):
1259 def magic_debug(self, parameter_s=''):
1260 """Activate the interactive debugger in post-mortem mode.
1260 """Activate the interactive debugger in post-mortem mode.
1261
1261
1262 If an exception has just occurred, this lets you inspect its stack
1262 If an exception has just occurred, this lets you inspect its stack
1263 frames interactively. Note that this will always work only on the last
1263 frames interactively. Note that this will always work only on the last
1264 traceback that occurred, so you must call this quickly after an
1264 traceback that occurred, so you must call this quickly after an
1265 exception that you wish to inspect has fired, because if another one
1265 exception that you wish to inspect has fired, because if another one
1266 occurs, it clobbers the previous one.
1266 occurs, it clobbers the previous one.
1267
1267
1268 If you want IPython to automatically do this on every exception, see
1268 If you want IPython to automatically do this on every exception, see
1269 the %pdb magic for more details.
1269 the %pdb magic for more details.
1270 """
1270 """
1271 self.shell.debugger(force=True)
1271 self.shell.debugger(force=True)
1272
1272
1273 @testdec.skip_doctest
1273 @testdec.skip_doctest
1274 def magic_prun(self, parameter_s ='',user_mode=1,
1274 def magic_prun(self, parameter_s ='',user_mode=1,
1275 opts=None,arg_lst=None,prog_ns=None):
1275 opts=None,arg_lst=None,prog_ns=None):
1276
1276
1277 """Run a statement through the python code profiler.
1277 """Run a statement through the python code profiler.
1278
1278
1279 Usage:
1279 Usage:
1280 %prun [options] statement
1280 %prun [options] statement
1281
1281
1282 The given statement (which doesn't require quote marks) is run via the
1282 The given statement (which doesn't require quote marks) is run via the
1283 python profiler in a manner similar to the profile.run() function.
1283 python profiler in a manner similar to the profile.run() function.
1284 Namespaces are internally managed to work correctly; profile.run
1284 Namespaces are internally managed to work correctly; profile.run
1285 cannot be used in IPython because it makes certain assumptions about
1285 cannot be used in IPython because it makes certain assumptions about
1286 namespaces which do not hold under IPython.
1286 namespaces which do not hold under IPython.
1287
1287
1288 Options:
1288 Options:
1289
1289
1290 -l <limit>: you can place restrictions on what or how much of the
1290 -l <limit>: you can place restrictions on what or how much of the
1291 profile gets printed. The limit value can be:
1291 profile gets printed. The limit value can be:
1292
1292
1293 * A string: only information for function names containing this string
1293 * A string: only information for function names containing this string
1294 is printed.
1294 is printed.
1295
1295
1296 * An integer: only these many lines are printed.
1296 * An integer: only these many lines are printed.
1297
1297
1298 * A float (between 0 and 1): this fraction of the report is printed
1298 * A float (between 0 and 1): this fraction of the report is printed
1299 (for example, use a limit of 0.4 to see the topmost 40% only).
1299 (for example, use a limit of 0.4 to see the topmost 40% only).
1300
1300
1301 You can combine several limits with repeated use of the option. For
1301 You can combine several limits with repeated use of the option. For
1302 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1302 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1303 information about class constructors.
1303 information about class constructors.
1304
1304
1305 -r: return the pstats.Stats object generated by the profiling. This
1305 -r: return the pstats.Stats object generated by the profiling. This
1306 object has all the information about the profile in it, and you can
1306 object has all the information about the profile in it, and you can
1307 later use it for further analysis or in other functions.
1307 later use it for further analysis or in other functions.
1308
1308
1309 -s <key>: sort profile by given key. You can provide more than one key
1309 -s <key>: sort profile by given key. You can provide more than one key
1310 by using the option several times: '-s key1 -s key2 -s key3...'. The
1310 by using the option several times: '-s key1 -s key2 -s key3...'. The
1311 default sorting key is 'time'.
1311 default sorting key is 'time'.
1312
1312
1313 The following is copied verbatim from the profile documentation
1313 The following is copied verbatim from the profile documentation
1314 referenced below:
1314 referenced below:
1315
1315
1316 When more than one key is provided, additional keys are used as
1316 When more than one key is provided, additional keys are used as
1317 secondary criteria when the there is equality in all keys selected
1317 secondary criteria when the there is equality in all keys selected
1318 before them.
1318 before them.
1319
1319
1320 Abbreviations can be used for any key names, as long as the
1320 Abbreviations can be used for any key names, as long as the
1321 abbreviation is unambiguous. The following are the keys currently
1321 abbreviation is unambiguous. The following are the keys currently
1322 defined:
1322 defined:
1323
1323
1324 Valid Arg Meaning
1324 Valid Arg Meaning
1325 "calls" call count
1325 "calls" call count
1326 "cumulative" cumulative time
1326 "cumulative" cumulative time
1327 "file" file name
1327 "file" file name
1328 "module" file name
1328 "module" file name
1329 "pcalls" primitive call count
1329 "pcalls" primitive call count
1330 "line" line number
1330 "line" line number
1331 "name" function name
1331 "name" function name
1332 "nfl" name/file/line
1332 "nfl" name/file/line
1333 "stdname" standard name
1333 "stdname" standard name
1334 "time" internal time
1334 "time" internal time
1335
1335
1336 Note that all sorts on statistics are in descending order (placing
1336 Note that all sorts on statistics are in descending order (placing
1337 most time consuming items first), where as name, file, and line number
1337 most time consuming items first), where as name, file, and line number
1338 searches are in ascending order (i.e., alphabetical). The subtle
1338 searches are in ascending order (i.e., alphabetical). The subtle
1339 distinction between "nfl" and "stdname" is that the standard name is a
1339 distinction between "nfl" and "stdname" is that the standard name is a
1340 sort of the name as printed, which means that the embedded line
1340 sort of the name as printed, which means that the embedded line
1341 numbers get compared in an odd way. For example, lines 3, 20, and 40
1341 numbers get compared in an odd way. For example, lines 3, 20, and 40
1342 would (if the file names were the same) appear in the string order
1342 would (if the file names were the same) appear in the string order
1343 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1343 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1344 line numbers. In fact, sort_stats("nfl") is the same as
1344 line numbers. In fact, sort_stats("nfl") is the same as
1345 sort_stats("name", "file", "line").
1345 sort_stats("name", "file", "line").
1346
1346
1347 -T <filename>: save profile results as shown on screen to a text
1347 -T <filename>: save profile results as shown on screen to a text
1348 file. The profile is still shown on screen.
1348 file. The profile is still shown on screen.
1349
1349
1350 -D <filename>: save (via dump_stats) profile statistics to given
1350 -D <filename>: save (via dump_stats) profile statistics to given
1351 filename. This data is in a format understod by the pstats module, and
1351 filename. This data is in a format understod by the pstats module, and
1352 is generated by a call to the dump_stats() method of profile
1352 is generated by a call to the dump_stats() method of profile
1353 objects. The profile is still shown on screen.
1353 objects. The profile is still shown on screen.
1354
1354
1355 If you want to run complete programs under the profiler's control, use
1355 If you want to run complete programs under the profiler's control, use
1356 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1356 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1357 contains profiler specific options as described here.
1357 contains profiler specific options as described here.
1358
1358
1359 You can read the complete documentation for the profile module with::
1359 You can read the complete documentation for the profile module with::
1360
1360
1361 In [1]: import profile; profile.help()
1361 In [1]: import profile; profile.help()
1362 """
1362 """
1363
1363
1364 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1364 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1365 # protect user quote marks
1365 # protect user quote marks
1366 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1366 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1367
1367
1368 if user_mode: # regular user call
1368 if user_mode: # regular user call
1369 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1369 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1370 list_all=1)
1370 list_all=1)
1371 namespace = self.shell.user_ns
1371 namespace = self.shell.user_ns
1372 else: # called to run a program by %run -p
1372 else: # called to run a program by %run -p
1373 try:
1373 try:
1374 filename = get_py_filename(arg_lst[0])
1374 filename = get_py_filename(arg_lst[0])
1375 except IOError,msg:
1375 except IOError,msg:
1376 error(msg)
1376 error(msg)
1377 return
1377 return
1378
1378
1379 arg_str = 'execfile(filename,prog_ns)'
1379 arg_str = 'execfile(filename,prog_ns)'
1380 namespace = locals()
1380 namespace = locals()
1381
1381
1382 opts.merge(opts_def)
1382 opts.merge(opts_def)
1383
1383
1384 prof = profile.Profile()
1384 prof = profile.Profile()
1385 try:
1385 try:
1386 prof = prof.runctx(arg_str,namespace,namespace)
1386 prof = prof.runctx(arg_str,namespace,namespace)
1387 sys_exit = ''
1387 sys_exit = ''
1388 except SystemExit:
1388 except SystemExit:
1389 sys_exit = """*** SystemExit exception caught in code being profiled."""
1389 sys_exit = """*** SystemExit exception caught in code being profiled."""
1390
1390
1391 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1391 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1392
1392
1393 lims = opts.l
1393 lims = opts.l
1394 if lims:
1394 if lims:
1395 lims = [] # rebuild lims with ints/floats/strings
1395 lims = [] # rebuild lims with ints/floats/strings
1396 for lim in opts.l:
1396 for lim in opts.l:
1397 try:
1397 try:
1398 lims.append(int(lim))
1398 lims.append(int(lim))
1399 except ValueError:
1399 except ValueError:
1400 try:
1400 try:
1401 lims.append(float(lim))
1401 lims.append(float(lim))
1402 except ValueError:
1402 except ValueError:
1403 lims.append(lim)
1403 lims.append(lim)
1404
1404
1405 # Trap output.
1405 # Trap output.
1406 stdout_trap = StringIO()
1406 stdout_trap = StringIO()
1407
1407
1408 if hasattr(stats,'stream'):
1408 if hasattr(stats,'stream'):
1409 # In newer versions of python, the stats object has a 'stream'
1409 # In newer versions of python, the stats object has a 'stream'
1410 # attribute to write into.
1410 # attribute to write into.
1411 stats.stream = stdout_trap
1411 stats.stream = stdout_trap
1412 stats.print_stats(*lims)
1412 stats.print_stats(*lims)
1413 else:
1413 else:
1414 # For older versions, we manually redirect stdout during printing
1414 # For older versions, we manually redirect stdout during printing
1415 sys_stdout = sys.stdout
1415 sys_stdout = sys.stdout
1416 try:
1416 try:
1417 sys.stdout = stdout_trap
1417 sys.stdout = stdout_trap
1418 stats.print_stats(*lims)
1418 stats.print_stats(*lims)
1419 finally:
1419 finally:
1420 sys.stdout = sys_stdout
1420 sys.stdout = sys_stdout
1421
1421
1422 output = stdout_trap.getvalue()
1422 output = stdout_trap.getvalue()
1423 output = output.rstrip()
1423 output = output.rstrip()
1424
1424
1425 page(output,screen_lines=self.shell.usable_screen_length)
1425 page(output,screen_lines=self.shell.usable_screen_length)
1426 print sys_exit,
1426 print sys_exit,
1427
1427
1428 dump_file = opts.D[0]
1428 dump_file = opts.D[0]
1429 text_file = opts.T[0]
1429 text_file = opts.T[0]
1430 if dump_file:
1430 if dump_file:
1431 prof.dump_stats(dump_file)
1431 prof.dump_stats(dump_file)
1432 print '\n*** Profile stats marshalled to file',\
1432 print '\n*** Profile stats marshalled to file',\
1433 `dump_file`+'.',sys_exit
1433 `dump_file`+'.',sys_exit
1434 if text_file:
1434 if text_file:
1435 pfile = file(text_file,'w')
1435 pfile = file(text_file,'w')
1436 pfile.write(output)
1436 pfile.write(output)
1437 pfile.close()
1437 pfile.close()
1438 print '\n*** Profile printout saved to text file',\
1438 print '\n*** Profile printout saved to text file',\
1439 `text_file`+'.',sys_exit
1439 `text_file`+'.',sys_exit
1440
1440
1441 if opts.has_key('r'):
1441 if opts.has_key('r'):
1442 return stats
1442 return stats
1443 else:
1443 else:
1444 return None
1444 return None
1445
1445
1446 @testdec.skip_doctest
1446 @testdec.skip_doctest
1447 def magic_run(self, parameter_s ='',runner=None,
1447 def magic_run(self, parameter_s ='',runner=None,
1448 file_finder=get_py_filename):
1448 file_finder=get_py_filename):
1449 """Run the named file inside IPython as a program.
1449 """Run the named file inside IPython as a program.
1450
1450
1451 Usage:\\
1451 Usage:\\
1452 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1452 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1453
1453
1454 Parameters after the filename are passed as command-line arguments to
1454 Parameters after the filename are passed as command-line arguments to
1455 the program (put in sys.argv). Then, control returns to IPython's
1455 the program (put in sys.argv). Then, control returns to IPython's
1456 prompt.
1456 prompt.
1457
1457
1458 This is similar to running at a system prompt:\\
1458 This is similar to running at a system prompt:\\
1459 $ python file args\\
1459 $ python file args\\
1460 but with the advantage of giving you IPython's tracebacks, and of
1460 but with the advantage of giving you IPython's tracebacks, and of
1461 loading all variables into your interactive namespace for further use
1461 loading all variables into your interactive namespace for further use
1462 (unless -p is used, see below).
1462 (unless -p is used, see below).
1463
1463
1464 The file is executed in a namespace initially consisting only of
1464 The file is executed in a namespace initially consisting only of
1465 __name__=='__main__' and sys.argv constructed as indicated. It thus
1465 __name__=='__main__' and sys.argv constructed as indicated. It thus
1466 sees its environment as if it were being run as a stand-alone program
1466 sees its environment as if it were being run as a stand-alone program
1467 (except for sharing global objects such as previously imported
1467 (except for sharing global objects such as previously imported
1468 modules). But after execution, the IPython interactive namespace gets
1468 modules). But after execution, the IPython interactive namespace gets
1469 updated with all variables defined in the program (except for __name__
1469 updated with all variables defined in the program (except for __name__
1470 and sys.argv). This allows for very convenient loading of code for
1470 and sys.argv). This allows for very convenient loading of code for
1471 interactive work, while giving each program a 'clean sheet' to run in.
1471 interactive work, while giving each program a 'clean sheet' to run in.
1472
1472
1473 Options:
1473 Options:
1474
1474
1475 -n: __name__ is NOT set to '__main__', but to the running file's name
1475 -n: __name__ is NOT set to '__main__', but to the running file's name
1476 without extension (as python does under import). This allows running
1476 without extension (as python does under import). This allows running
1477 scripts and reloading the definitions in them without calling code
1477 scripts and reloading the definitions in them without calling code
1478 protected by an ' if __name__ == "__main__" ' clause.
1478 protected by an ' if __name__ == "__main__" ' clause.
1479
1479
1480 -i: run the file in IPython's namespace instead of an empty one. This
1480 -i: run the file in IPython's namespace instead of an empty one. This
1481 is useful if you are experimenting with code written in a text editor
1481 is useful if you are experimenting with code written in a text editor
1482 which depends on variables defined interactively.
1482 which depends on variables defined interactively.
1483
1483
1484 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1484 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1485 being run. This is particularly useful if IPython is being used to
1485 being run. This is particularly useful if IPython is being used to
1486 run unittests, which always exit with a sys.exit() call. In such
1486 run unittests, which always exit with a sys.exit() call. In such
1487 cases you are interested in the output of the test results, not in
1487 cases you are interested in the output of the test results, not in
1488 seeing a traceback of the unittest module.
1488 seeing a traceback of the unittest module.
1489
1489
1490 -t: print timing information at the end of the run. IPython will give
1490 -t: print timing information at the end of the run. IPython will give
1491 you an estimated CPU time consumption for your script, which under
1491 you an estimated CPU time consumption for your script, which under
1492 Unix uses the resource module to avoid the wraparound problems of
1492 Unix uses the resource module to avoid the wraparound problems of
1493 time.clock(). Under Unix, an estimate of time spent on system tasks
1493 time.clock(). Under Unix, an estimate of time spent on system tasks
1494 is also given (for Windows platforms this is reported as 0.0).
1494 is also given (for Windows platforms this is reported as 0.0).
1495
1495
1496 If -t is given, an additional -N<N> option can be given, where <N>
1496 If -t is given, an additional -N<N> option can be given, where <N>
1497 must be an integer indicating how many times you want the script to
1497 must be an integer indicating how many times you want the script to
1498 run. The final timing report will include total and per run results.
1498 run. The final timing report will include total and per run results.
1499
1499
1500 For example (testing the script uniq_stable.py):
1500 For example (testing the script uniq_stable.py):
1501
1501
1502 In [1]: run -t uniq_stable
1502 In [1]: run -t uniq_stable
1503
1503
1504 IPython CPU timings (estimated):\\
1504 IPython CPU timings (estimated):\\
1505 User : 0.19597 s.\\
1505 User : 0.19597 s.\\
1506 System: 0.0 s.\\
1506 System: 0.0 s.\\
1507
1507
1508 In [2]: run -t -N5 uniq_stable
1508 In [2]: run -t -N5 uniq_stable
1509
1509
1510 IPython CPU timings (estimated):\\
1510 IPython CPU timings (estimated):\\
1511 Total runs performed: 5\\
1511 Total runs performed: 5\\
1512 Times : Total Per run\\
1512 Times : Total Per run\\
1513 User : 0.910862 s, 0.1821724 s.\\
1513 User : 0.910862 s, 0.1821724 s.\\
1514 System: 0.0 s, 0.0 s.
1514 System: 0.0 s, 0.0 s.
1515
1515
1516 -d: run your program under the control of pdb, the Python debugger.
1516 -d: run your program under the control of pdb, the Python debugger.
1517 This allows you to execute your program step by step, watch variables,
1517 This allows you to execute your program step by step, watch variables,
1518 etc. Internally, what IPython does is similar to calling:
1518 etc. Internally, what IPython does is similar to calling:
1519
1519
1520 pdb.run('execfile("YOURFILENAME")')
1520 pdb.run('execfile("YOURFILENAME")')
1521
1521
1522 with a breakpoint set on line 1 of your file. You can change the line
1522 with a breakpoint set on line 1 of your file. You can change the line
1523 number for this automatic breakpoint to be <N> by using the -bN option
1523 number for this automatic breakpoint to be <N> by using the -bN option
1524 (where N must be an integer). For example:
1524 (where N must be an integer). For example:
1525
1525
1526 %run -d -b40 myscript
1526 %run -d -b40 myscript
1527
1527
1528 will set the first breakpoint at line 40 in myscript.py. Note that
1528 will set the first breakpoint at line 40 in myscript.py. Note that
1529 the first breakpoint must be set on a line which actually does
1529 the first breakpoint must be set on a line which actually does
1530 something (not a comment or docstring) for it to stop execution.
1530 something (not a comment or docstring) for it to stop execution.
1531
1531
1532 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1532 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1533 first enter 'c' (without qoutes) to start execution up to the first
1533 first enter 'c' (without qoutes) to start execution up to the first
1534 breakpoint.
1534 breakpoint.
1535
1535
1536 Entering 'help' gives information about the use of the debugger. You
1536 Entering 'help' gives information about the use of the debugger. You
1537 can easily see pdb's full documentation with "import pdb;pdb.help()"
1537 can easily see pdb's full documentation with "import pdb;pdb.help()"
1538 at a prompt.
1538 at a prompt.
1539
1539
1540 -p: run program under the control of the Python profiler module (which
1540 -p: run program under the control of the Python profiler module (which
1541 prints a detailed report of execution times, function calls, etc).
1541 prints a detailed report of execution times, function calls, etc).
1542
1542
1543 You can pass other options after -p which affect the behavior of the
1543 You can pass other options after -p which affect the behavior of the
1544 profiler itself. See the docs for %prun for details.
1544 profiler itself. See the docs for %prun for details.
1545
1545
1546 In this mode, the program's variables do NOT propagate back to the
1546 In this mode, the program's variables do NOT propagate back to the
1547 IPython interactive namespace (because they remain in the namespace
1547 IPython interactive namespace (because they remain in the namespace
1548 where the profiler executes them).
1548 where the profiler executes them).
1549
1549
1550 Internally this triggers a call to %prun, see its documentation for
1550 Internally this triggers a call to %prun, see its documentation for
1551 details on the options available specifically for profiling.
1551 details on the options available specifically for profiling.
1552
1552
1553 There is one special usage for which the text above doesn't apply:
1553 There is one special usage for which the text above doesn't apply:
1554 if the filename ends with .ipy, the file is run as ipython script,
1554 if the filename ends with .ipy, the file is run as ipython script,
1555 just as if the commands were written on IPython prompt.
1555 just as if the commands were written on IPython prompt.
1556 """
1556 """
1557
1557
1558 # get arguments and set sys.argv for program to be run.
1558 # get arguments and set sys.argv for program to be run.
1559 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1559 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1560 mode='list',list_all=1)
1560 mode='list',list_all=1)
1561
1561
1562 try:
1562 try:
1563 filename = file_finder(arg_lst[0])
1563 filename = file_finder(arg_lst[0])
1564 except IndexError:
1564 except IndexError:
1565 warn('you must provide at least a filename.')
1565 warn('you must provide at least a filename.')
1566 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1566 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1567 return
1567 return
1568 except IOError,msg:
1568 except IOError,msg:
1569 error(msg)
1569 error(msg)
1570 return
1570 return
1571
1571
1572 if filename.lower().endswith('.ipy'):
1572 if filename.lower().endswith('.ipy'):
1573 self.safe_execfile_ipy(filename)
1573 self.safe_execfile_ipy(filename)
1574 return
1574 return
1575
1575
1576 # Control the response to exit() calls made by the script being run
1576 # Control the response to exit() calls made by the script being run
1577 exit_ignore = opts.has_key('e')
1577 exit_ignore = opts.has_key('e')
1578
1578
1579 # Make sure that the running script gets a proper sys.argv as if it
1579 # Make sure that the running script gets a proper sys.argv as if it
1580 # were run from a system shell.
1580 # were run from a system shell.
1581 save_argv = sys.argv # save it for later restoring
1581 save_argv = sys.argv # save it for later restoring
1582 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1582 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1583
1583
1584 if opts.has_key('i'):
1584 if opts.has_key('i'):
1585 # Run in user's interactive namespace
1585 # Run in user's interactive namespace
1586 prog_ns = self.shell.user_ns
1586 prog_ns = self.shell.user_ns
1587 __name__save = self.shell.user_ns['__name__']
1587 __name__save = self.shell.user_ns['__name__']
1588 prog_ns['__name__'] = '__main__'
1588 prog_ns['__name__'] = '__main__'
1589 main_mod = self.shell.new_main_mod(prog_ns)
1589 main_mod = self.shell.new_main_mod(prog_ns)
1590 else:
1590 else:
1591 # Run in a fresh, empty namespace
1591 # Run in a fresh, empty namespace
1592 if opts.has_key('n'):
1592 if opts.has_key('n'):
1593 name = os.path.splitext(os.path.basename(filename))[0]
1593 name = os.path.splitext(os.path.basename(filename))[0]
1594 else:
1594 else:
1595 name = '__main__'
1595 name = '__main__'
1596
1596
1597 main_mod = self.shell.new_main_mod()
1597 main_mod = self.shell.new_main_mod()
1598 prog_ns = main_mod.__dict__
1598 prog_ns = main_mod.__dict__
1599 prog_ns['__name__'] = name
1599 prog_ns['__name__'] = name
1600
1600
1601 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1601 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1602 # set the __file__ global in the script's namespace
1602 # set the __file__ global in the script's namespace
1603 prog_ns['__file__'] = filename
1603 prog_ns['__file__'] = filename
1604
1604
1605 # pickle fix. See iplib for an explanation. But we need to make sure
1605 # pickle fix. See iplib for an explanation. But we need to make sure
1606 # that, if we overwrite __main__, we replace it at the end
1606 # that, if we overwrite __main__, we replace it at the end
1607 main_mod_name = prog_ns['__name__']
1607 main_mod_name = prog_ns['__name__']
1608
1608
1609 if main_mod_name == '__main__':
1609 if main_mod_name == '__main__':
1610 restore_main = sys.modules['__main__']
1610 restore_main = sys.modules['__main__']
1611 else:
1611 else:
1612 restore_main = False
1612 restore_main = False
1613
1613
1614 # This needs to be undone at the end to prevent holding references to
1614 # This needs to be undone at the end to prevent holding references to
1615 # every single object ever created.
1615 # every single object ever created.
1616 sys.modules[main_mod_name] = main_mod
1616 sys.modules[main_mod_name] = main_mod
1617
1617
1618 stats = None
1618 stats = None
1619 try:
1619 try:
1620 self.shell.savehist()
1620 self.shell.savehist()
1621
1621
1622 if opts.has_key('p'):
1622 if opts.has_key('p'):
1623 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1623 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1624 else:
1624 else:
1625 if opts.has_key('d'):
1625 if opts.has_key('d'):
1626 deb = debugger.Pdb(self.shell.colors)
1626 deb = debugger.Pdb(self.shell.colors)
1627 # reset Breakpoint state, which is moronically kept
1627 # reset Breakpoint state, which is moronically kept
1628 # in a class
1628 # in a class
1629 bdb.Breakpoint.next = 1
1629 bdb.Breakpoint.next = 1
1630 bdb.Breakpoint.bplist = {}
1630 bdb.Breakpoint.bplist = {}
1631 bdb.Breakpoint.bpbynumber = [None]
1631 bdb.Breakpoint.bpbynumber = [None]
1632 # Set an initial breakpoint to stop execution
1632 # Set an initial breakpoint to stop execution
1633 maxtries = 10
1633 maxtries = 10
1634 bp = int(opts.get('b',[1])[0])
1634 bp = int(opts.get('b',[1])[0])
1635 checkline = deb.checkline(filename,bp)
1635 checkline = deb.checkline(filename,bp)
1636 if not checkline:
1636 if not checkline:
1637 for bp in range(bp+1,bp+maxtries+1):
1637 for bp in range(bp+1,bp+maxtries+1):
1638 if deb.checkline(filename,bp):
1638 if deb.checkline(filename,bp):
1639 break
1639 break
1640 else:
1640 else:
1641 msg = ("\nI failed to find a valid line to set "
1641 msg = ("\nI failed to find a valid line to set "
1642 "a breakpoint\n"
1642 "a breakpoint\n"
1643 "after trying up to line: %s.\n"
1643 "after trying up to line: %s.\n"
1644 "Please set a valid breakpoint manually "
1644 "Please set a valid breakpoint manually "
1645 "with the -b option." % bp)
1645 "with the -b option." % bp)
1646 error(msg)
1646 error(msg)
1647 return
1647 return
1648 # if we find a good linenumber, set the breakpoint
1648 # if we find a good linenumber, set the breakpoint
1649 deb.do_break('%s:%s' % (filename,bp))
1649 deb.do_break('%s:%s' % (filename,bp))
1650 # Start file run
1650 # Start file run
1651 print "NOTE: Enter 'c' at the",
1651 print "NOTE: Enter 'c' at the",
1652 print "%s prompt to start your script." % deb.prompt
1652 print "%s prompt to start your script." % deb.prompt
1653 try:
1653 try:
1654 deb.run('execfile("%s")' % filename,prog_ns)
1654 deb.run('execfile("%s")' % filename,prog_ns)
1655
1655
1656 except:
1656 except:
1657 etype, value, tb = sys.exc_info()
1657 etype, value, tb = sys.exc_info()
1658 # Skip three frames in the traceback: the %run one,
1658 # Skip three frames in the traceback: the %run one,
1659 # one inside bdb.py, and the command-line typed by the
1659 # one inside bdb.py, and the command-line typed by the
1660 # user (run by exec in pdb itself).
1660 # user (run by exec in pdb itself).
1661 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1661 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1662 else:
1662 else:
1663 if runner is None:
1663 if runner is None:
1664 runner = self.shell.safe_execfile
1664 runner = self.shell.safe_execfile
1665 if opts.has_key('t'):
1665 if opts.has_key('t'):
1666 # timed execution
1666 # timed execution
1667 try:
1667 try:
1668 nruns = int(opts['N'][0])
1668 nruns = int(opts['N'][0])
1669 if nruns < 1:
1669 if nruns < 1:
1670 error('Number of runs must be >=1')
1670 error('Number of runs must be >=1')
1671 return
1671 return
1672 except (KeyError):
1672 except (KeyError):
1673 nruns = 1
1673 nruns = 1
1674 if nruns == 1:
1674 if nruns == 1:
1675 t0 = clock2()
1675 t0 = clock2()
1676 runner(filename,prog_ns,prog_ns,
1676 runner(filename,prog_ns,prog_ns,
1677 exit_ignore=exit_ignore)
1677 exit_ignore=exit_ignore)
1678 t1 = clock2()
1678 t1 = clock2()
1679 t_usr = t1[0]-t0[0]
1679 t_usr = t1[0]-t0[0]
1680 t_sys = t1[1]-t0[1]
1680 t_sys = t1[1]-t0[1]
1681 print "\nIPython CPU timings (estimated):"
1681 print "\nIPython CPU timings (estimated):"
1682 print " User : %10s s." % t_usr
1682 print " User : %10s s." % t_usr
1683 print " System: %10s s." % t_sys
1683 print " System: %10s s." % t_sys
1684 else:
1684 else:
1685 runs = range(nruns)
1685 runs = range(nruns)
1686 t0 = clock2()
1686 t0 = clock2()
1687 for nr in runs:
1687 for nr in runs:
1688 runner(filename,prog_ns,prog_ns,
1688 runner(filename,prog_ns,prog_ns,
1689 exit_ignore=exit_ignore)
1689 exit_ignore=exit_ignore)
1690 t1 = clock2()
1690 t1 = clock2()
1691 t_usr = t1[0]-t0[0]
1691 t_usr = t1[0]-t0[0]
1692 t_sys = t1[1]-t0[1]
1692 t_sys = t1[1]-t0[1]
1693 print "\nIPython CPU timings (estimated):"
1693 print "\nIPython CPU timings (estimated):"
1694 print "Total runs performed:",nruns
1694 print "Total runs performed:",nruns
1695 print " Times : %10s %10s" % ('Total','Per run')
1695 print " Times : %10s %10s" % ('Total','Per run')
1696 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1696 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1697 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1697 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1698
1698
1699 else:
1699 else:
1700 # regular execution
1700 # regular execution
1701 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1701 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1702
1702
1703 if opts.has_key('i'):
1703 if opts.has_key('i'):
1704 self.shell.user_ns['__name__'] = __name__save
1704 self.shell.user_ns['__name__'] = __name__save
1705 else:
1705 else:
1706 # The shell MUST hold a reference to prog_ns so after %run
1706 # The shell MUST hold a reference to prog_ns so after %run
1707 # exits, the python deletion mechanism doesn't zero it out
1707 # exits, the python deletion mechanism doesn't zero it out
1708 # (leaving dangling references).
1708 # (leaving dangling references).
1709 self.shell.cache_main_mod(prog_ns,filename)
1709 self.shell.cache_main_mod(prog_ns,filename)
1710 # update IPython interactive namespace
1710 # update IPython interactive namespace
1711
1711
1712 # Some forms of read errors on the file may mean the
1712 # Some forms of read errors on the file may mean the
1713 # __name__ key was never set; using pop we don't have to
1713 # __name__ key was never set; using pop we don't have to
1714 # worry about a possible KeyError.
1714 # worry about a possible KeyError.
1715 prog_ns.pop('__name__', None)
1715 prog_ns.pop('__name__', None)
1716
1716
1717 self.shell.user_ns.update(prog_ns)
1717 self.shell.user_ns.update(prog_ns)
1718 finally:
1718 finally:
1719 # It's a bit of a mystery why, but __builtins__ can change from
1719 # It's a bit of a mystery why, but __builtins__ can change from
1720 # being a module to becoming a dict missing some key data after
1720 # being a module to becoming a dict missing some key data after
1721 # %run. As best I can see, this is NOT something IPython is doing
1721 # %run. As best I can see, this is NOT something IPython is doing
1722 # at all, and similar problems have been reported before:
1722 # at all, and similar problems have been reported before:
1723 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1723 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1724 # Since this seems to be done by the interpreter itself, the best
1724 # Since this seems to be done by the interpreter itself, the best
1725 # we can do is to at least restore __builtins__ for the user on
1725 # we can do is to at least restore __builtins__ for the user on
1726 # exit.
1726 # exit.
1727 self.shell.user_ns['__builtins__'] = __builtin__
1727 self.shell.user_ns['__builtins__'] = __builtin__
1728
1728
1729 # Ensure key global structures are restored
1729 # Ensure key global structures are restored
1730 sys.argv = save_argv
1730 sys.argv = save_argv
1731 if restore_main:
1731 if restore_main:
1732 sys.modules['__main__'] = restore_main
1732 sys.modules['__main__'] = restore_main
1733 else:
1733 else:
1734 # Remove from sys.modules the reference to main_mod we'd
1734 # Remove from sys.modules the reference to main_mod we'd
1735 # added. Otherwise it will trap references to objects
1735 # added. Otherwise it will trap references to objects
1736 # contained therein.
1736 # contained therein.
1737 del sys.modules[main_mod_name]
1737 del sys.modules[main_mod_name]
1738
1738
1739 self.shell.reloadhist()
1739 self.shell.reloadhist()
1740
1740
1741 return stats
1741 return stats
1742
1742
1743 @testdec.skip_doctest
1743 @testdec.skip_doctest
1744 def magic_timeit(self, parameter_s =''):
1744 def magic_timeit(self, parameter_s =''):
1745 """Time execution of a Python statement or expression
1745 """Time execution of a Python statement or expression
1746
1746
1747 Usage:\\
1747 Usage:\\
1748 %timeit [-n<N> -r<R> [-t|-c]] statement
1748 %timeit [-n<N> -r<R> [-t|-c]] statement
1749
1749
1750 Time execution of a Python statement or expression using the timeit
1750 Time execution of a Python statement or expression using the timeit
1751 module.
1751 module.
1752
1752
1753 Options:
1753 Options:
1754 -n<N>: execute the given statement <N> times in a loop. If this value
1754 -n<N>: execute the given statement <N> times in a loop. If this value
1755 is not given, a fitting value is chosen.
1755 is not given, a fitting value is chosen.
1756
1756
1757 -r<R>: repeat the loop iteration <R> times and take the best result.
1757 -r<R>: repeat the loop iteration <R> times and take the best result.
1758 Default: 3
1758 Default: 3
1759
1759
1760 -t: use time.time to measure the time, which is the default on Unix.
1760 -t: use time.time to measure the time, which is the default on Unix.
1761 This function measures wall time.
1761 This function measures wall time.
1762
1762
1763 -c: use time.clock to measure the time, which is the default on
1763 -c: use time.clock to measure the time, which is the default on
1764 Windows and measures wall time. On Unix, resource.getrusage is used
1764 Windows and measures wall time. On Unix, resource.getrusage is used
1765 instead and returns the CPU user time.
1765 instead and returns the CPU user time.
1766
1766
1767 -p<P>: use a precision of <P> digits to display the timing result.
1767 -p<P>: use a precision of <P> digits to display the timing result.
1768 Default: 3
1768 Default: 3
1769
1769
1770
1770
1771 Examples:
1771 Examples:
1772
1772
1773 In [1]: %timeit pass
1773 In [1]: %timeit pass
1774 10000000 loops, best of 3: 53.3 ns per loop
1774 10000000 loops, best of 3: 53.3 ns per loop
1775
1775
1776 In [2]: u = None
1776 In [2]: u = None
1777
1777
1778 In [3]: %timeit u is None
1778 In [3]: %timeit u is None
1779 10000000 loops, best of 3: 184 ns per loop
1779 10000000 loops, best of 3: 184 ns per loop
1780
1780
1781 In [4]: %timeit -r 4 u == None
1781 In [4]: %timeit -r 4 u == None
1782 1000000 loops, best of 4: 242 ns per loop
1782 1000000 loops, best of 4: 242 ns per loop
1783
1783
1784 In [5]: import time
1784 In [5]: import time
1785
1785
1786 In [6]: %timeit -n1 time.sleep(2)
1786 In [6]: %timeit -n1 time.sleep(2)
1787 1 loops, best of 3: 2 s per loop
1787 1 loops, best of 3: 2 s per loop
1788
1788
1789
1789
1790 The times reported by %timeit will be slightly higher than those
1790 The times reported by %timeit will be slightly higher than those
1791 reported by the timeit.py script when variables are accessed. This is
1791 reported by the timeit.py script when variables are accessed. This is
1792 due to the fact that %timeit executes the statement in the namespace
1792 due to the fact that %timeit executes the statement in the namespace
1793 of the shell, compared with timeit.py, which uses a single setup
1793 of the shell, compared with timeit.py, which uses a single setup
1794 statement to import function or create variables. Generally, the bias
1794 statement to import function or create variables. Generally, the bias
1795 does not matter as long as results from timeit.py are not mixed with
1795 does not matter as long as results from timeit.py are not mixed with
1796 those from %timeit."""
1796 those from %timeit."""
1797
1797
1798 import timeit
1798 import timeit
1799 import math
1799 import math
1800
1800
1801 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1801 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1802 # certain terminals. Until we figure out a robust way of
1802 # certain terminals. Until we figure out a robust way of
1803 # auto-detecting if the terminal can deal with it, use plain 'us' for
1803 # auto-detecting if the terminal can deal with it, use plain 'us' for
1804 # microseconds. I am really NOT happy about disabling the proper
1804 # microseconds. I am really NOT happy about disabling the proper
1805 # 'micro' prefix, but crashing is worse... If anyone knows what the
1805 # 'micro' prefix, but crashing is worse... If anyone knows what the
1806 # right solution for this is, I'm all ears...
1806 # right solution for this is, I'm all ears...
1807 #
1807 #
1808 # Note: using
1808 # Note: using
1809 #
1809 #
1810 # s = u'\xb5'
1810 # s = u'\xb5'
1811 # s.encode(sys.getdefaultencoding())
1811 # s.encode(sys.getdefaultencoding())
1812 #
1812 #
1813 # is not sufficient, as I've seen terminals where that fails but
1813 # is not sufficient, as I've seen terminals where that fails but
1814 # print s
1814 # print s
1815 #
1815 #
1816 # succeeds
1816 # succeeds
1817 #
1817 #
1818 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1818 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1819
1819
1820 #units = [u"s", u"ms",u'\xb5',"ns"]
1820 #units = [u"s", u"ms",u'\xb5',"ns"]
1821 units = [u"s", u"ms",u'us',"ns"]
1821 units = [u"s", u"ms",u'us',"ns"]
1822
1822
1823 scaling = [1, 1e3, 1e6, 1e9]
1823 scaling = [1, 1e3, 1e6, 1e9]
1824
1824
1825 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1825 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1826 posix=False)
1826 posix=False)
1827 if stmt == "":
1827 if stmt == "":
1828 return
1828 return
1829 timefunc = timeit.default_timer
1829 timefunc = timeit.default_timer
1830 number = int(getattr(opts, "n", 0))
1830 number = int(getattr(opts, "n", 0))
1831 repeat = int(getattr(opts, "r", timeit.default_repeat))
1831 repeat = int(getattr(opts, "r", timeit.default_repeat))
1832 precision = int(getattr(opts, "p", 3))
1832 precision = int(getattr(opts, "p", 3))
1833 if hasattr(opts, "t"):
1833 if hasattr(opts, "t"):
1834 timefunc = time.time
1834 timefunc = time.time
1835 if hasattr(opts, "c"):
1835 if hasattr(opts, "c"):
1836 timefunc = clock
1836 timefunc = clock
1837
1837
1838 timer = timeit.Timer(timer=timefunc)
1838 timer = timeit.Timer(timer=timefunc)
1839 # this code has tight coupling to the inner workings of timeit.Timer,
1839 # this code has tight coupling to the inner workings of timeit.Timer,
1840 # but is there a better way to achieve that the code stmt has access
1840 # but is there a better way to achieve that the code stmt has access
1841 # to the shell namespace?
1841 # to the shell namespace?
1842
1842
1843 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1843 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1844 'setup': "pass"}
1844 'setup': "pass"}
1845 # Track compilation time so it can be reported if too long
1845 # Track compilation time so it can be reported if too long
1846 # Minimum time above which compilation time will be reported
1846 # Minimum time above which compilation time will be reported
1847 tc_min = 0.1
1847 tc_min = 0.1
1848
1848
1849 t0 = clock()
1849 t0 = clock()
1850 code = compile(src, "<magic-timeit>", "exec")
1850 code = compile(src, "<magic-timeit>", "exec")
1851 tc = clock()-t0
1851 tc = clock()-t0
1852
1852
1853 ns = {}
1853 ns = {}
1854 exec code in self.shell.user_ns, ns
1854 exec code in self.shell.user_ns, ns
1855 timer.inner = ns["inner"]
1855 timer.inner = ns["inner"]
1856
1856
1857 if number == 0:
1857 if number == 0:
1858 # determine number so that 0.2 <= total time < 2.0
1858 # determine number so that 0.2 <= total time < 2.0
1859 number = 1
1859 number = 1
1860 for i in range(1, 10):
1860 for i in range(1, 10):
1861 if timer.timeit(number) >= 0.2:
1861 if timer.timeit(number) >= 0.2:
1862 break
1862 break
1863 number *= 10
1863 number *= 10
1864
1864
1865 best = min(timer.repeat(repeat, number)) / number
1865 best = min(timer.repeat(repeat, number)) / number
1866
1866
1867 if best > 0.0:
1867 if best > 0.0:
1868 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1868 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1869 else:
1869 else:
1870 order = 3
1870 order = 3
1871 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1871 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1872 precision,
1872 precision,
1873 best * scaling[order],
1873 best * scaling[order],
1874 units[order])
1874 units[order])
1875 if tc > tc_min:
1875 if tc > tc_min:
1876 print "Compiler time: %.2f s" % tc
1876 print "Compiler time: %.2f s" % tc
1877
1877
1878 @testdec.skip_doctest
1878 @testdec.skip_doctest
1879 def magic_time(self,parameter_s = ''):
1879 def magic_time(self,parameter_s = ''):
1880 """Time execution of a Python statement or expression.
1880 """Time execution of a Python statement or expression.
1881
1881
1882 The CPU and wall clock times are printed, and the value of the
1882 The CPU and wall clock times are printed, and the value of the
1883 expression (if any) is returned. Note that under Win32, system time
1883 expression (if any) is returned. Note that under Win32, system time
1884 is always reported as 0, since it can not be measured.
1884 is always reported as 0, since it can not be measured.
1885
1885
1886 This function provides very basic timing functionality. In Python
1886 This function provides very basic timing functionality. In Python
1887 2.3, the timeit module offers more control and sophistication, so this
1887 2.3, the timeit module offers more control and sophistication, so this
1888 could be rewritten to use it (patches welcome).
1888 could be rewritten to use it (patches welcome).
1889
1889
1890 Some examples:
1890 Some examples:
1891
1891
1892 In [1]: time 2**128
1892 In [1]: time 2**128
1893 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1893 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1894 Wall time: 0.00
1894 Wall time: 0.00
1895 Out[1]: 340282366920938463463374607431768211456L
1895 Out[1]: 340282366920938463463374607431768211456L
1896
1896
1897 In [2]: n = 1000000
1897 In [2]: n = 1000000
1898
1898
1899 In [3]: time sum(range(n))
1899 In [3]: time sum(range(n))
1900 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1900 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1901 Wall time: 1.37
1901 Wall time: 1.37
1902 Out[3]: 499999500000L
1902 Out[3]: 499999500000L
1903
1903
1904 In [4]: time print 'hello world'
1904 In [4]: time print 'hello world'
1905 hello world
1905 hello world
1906 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1906 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1907 Wall time: 0.00
1907 Wall time: 0.00
1908
1908
1909 Note that the time needed by Python to compile the given expression
1909 Note that the time needed by Python to compile the given expression
1910 will be reported if it is more than 0.1s. In this example, the
1910 will be reported if it is more than 0.1s. In this example, the
1911 actual exponentiation is done by Python at compilation time, so while
1911 actual exponentiation is done by Python at compilation time, so while
1912 the expression can take a noticeable amount of time to compute, that
1912 the expression can take a noticeable amount of time to compute, that
1913 time is purely due to the compilation:
1913 time is purely due to the compilation:
1914
1914
1915 In [5]: time 3**9999;
1915 In [5]: time 3**9999;
1916 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1916 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1917 Wall time: 0.00 s
1917 Wall time: 0.00 s
1918
1918
1919 In [6]: time 3**999999;
1919 In [6]: time 3**999999;
1920 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1920 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1921 Wall time: 0.00 s
1921 Wall time: 0.00 s
1922 Compiler : 0.78 s
1922 Compiler : 0.78 s
1923 """
1923 """
1924
1924
1925 # fail immediately if the given expression can't be compiled
1925 # fail immediately if the given expression can't be compiled
1926
1926
1927 expr = self.shell.prefilter(parameter_s,False)
1927 expr = self.shell.prefilter(parameter_s,False)
1928
1928
1929 # Minimum time above which compilation time will be reported
1929 # Minimum time above which compilation time will be reported
1930 tc_min = 0.1
1930 tc_min = 0.1
1931
1931
1932 try:
1932 try:
1933 mode = 'eval'
1933 mode = 'eval'
1934 t0 = clock()
1934 t0 = clock()
1935 code = compile(expr,'<timed eval>',mode)
1935 code = compile(expr,'<timed eval>',mode)
1936 tc = clock()-t0
1936 tc = clock()-t0
1937 except SyntaxError:
1937 except SyntaxError:
1938 mode = 'exec'
1938 mode = 'exec'
1939 t0 = clock()
1939 t0 = clock()
1940 code = compile(expr,'<timed exec>',mode)
1940 code = compile(expr,'<timed exec>',mode)
1941 tc = clock()-t0
1941 tc = clock()-t0
1942 # skew measurement as little as possible
1942 # skew measurement as little as possible
1943 glob = self.shell.user_ns
1943 glob = self.shell.user_ns
1944 clk = clock2
1944 clk = clock2
1945 wtime = time.time
1945 wtime = time.time
1946 # time execution
1946 # time execution
1947 wall_st = wtime()
1947 wall_st = wtime()
1948 if mode=='eval':
1948 if mode=='eval':
1949 st = clk()
1949 st = clk()
1950 out = eval(code,glob)
1950 out = eval(code,glob)
1951 end = clk()
1951 end = clk()
1952 else:
1952 else:
1953 st = clk()
1953 st = clk()
1954 exec code in glob
1954 exec code in glob
1955 end = clk()
1955 end = clk()
1956 out = None
1956 out = None
1957 wall_end = wtime()
1957 wall_end = wtime()
1958 # Compute actual times and report
1958 # Compute actual times and report
1959 wall_time = wall_end-wall_st
1959 wall_time = wall_end-wall_st
1960 cpu_user = end[0]-st[0]
1960 cpu_user = end[0]-st[0]
1961 cpu_sys = end[1]-st[1]
1961 cpu_sys = end[1]-st[1]
1962 cpu_tot = cpu_user+cpu_sys
1962 cpu_tot = cpu_user+cpu_sys
1963 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1963 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1964 (cpu_user,cpu_sys,cpu_tot)
1964 (cpu_user,cpu_sys,cpu_tot)
1965 print "Wall time: %.2f s" % wall_time
1965 print "Wall time: %.2f s" % wall_time
1966 if tc > tc_min:
1966 if tc > tc_min:
1967 print "Compiler : %.2f s" % tc
1967 print "Compiler : %.2f s" % tc
1968 return out
1968 return out
1969
1969
1970 @testdec.skip_doctest
1970 @testdec.skip_doctest
1971 def magic_macro(self,parameter_s = ''):
1971 def magic_macro(self,parameter_s = ''):
1972 """Define a set of input lines as a macro for future re-execution.
1972 """Define a set of input lines as a macro for future re-execution.
1973
1973
1974 Usage:\\
1974 Usage:\\
1975 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1975 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1976
1976
1977 Options:
1977 Options:
1978
1978
1979 -r: use 'raw' input. By default, the 'processed' history is used,
1979 -r: use 'raw' input. By default, the 'processed' history is used,
1980 so that magics are loaded in their transformed version to valid
1980 so that magics are loaded in their transformed version to valid
1981 Python. If this option is given, the raw input as typed as the
1981 Python. If this option is given, the raw input as typed as the
1982 command line is used instead.
1982 command line is used instead.
1983
1983
1984 This will define a global variable called `name` which is a string
1984 This will define a global variable called `name` which is a string
1985 made of joining the slices and lines you specify (n1,n2,... numbers
1985 made of joining the slices and lines you specify (n1,n2,... numbers
1986 above) from your input history into a single string. This variable
1986 above) from your input history into a single string. This variable
1987 acts like an automatic function which re-executes those lines as if
1987 acts like an automatic function which re-executes those lines as if
1988 you had typed them. You just type 'name' at the prompt and the code
1988 you had typed them. You just type 'name' at the prompt and the code
1989 executes.
1989 executes.
1990
1990
1991 The notation for indicating number ranges is: n1-n2 means 'use line
1991 The notation for indicating number ranges is: n1-n2 means 'use line
1992 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1992 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1993 using the lines numbered 5,6 and 7.
1993 using the lines numbered 5,6 and 7.
1994
1994
1995 Note: as a 'hidden' feature, you can also use traditional python slice
1995 Note: as a 'hidden' feature, you can also use traditional python slice
1996 notation, where N:M means numbers N through M-1.
1996 notation, where N:M means numbers N through M-1.
1997
1997
1998 For example, if your history contains (%hist prints it):
1998 For example, if your history contains (%hist prints it):
1999
1999
2000 44: x=1
2000 44: x=1
2001 45: y=3
2001 45: y=3
2002 46: z=x+y
2002 46: z=x+y
2003 47: print x
2003 47: print x
2004 48: a=5
2004 48: a=5
2005 49: print 'x',x,'y',y
2005 49: print 'x',x,'y',y
2006
2006
2007 you can create a macro with lines 44 through 47 (included) and line 49
2007 you can create a macro with lines 44 through 47 (included) and line 49
2008 called my_macro with:
2008 called my_macro with:
2009
2009
2010 In [55]: %macro my_macro 44-47 49
2010 In [55]: %macro my_macro 44-47 49
2011
2011
2012 Now, typing `my_macro` (without quotes) will re-execute all this code
2012 Now, typing `my_macro` (without quotes) will re-execute all this code
2013 in one pass.
2013 in one pass.
2014
2014
2015 You don't need to give the line-numbers in order, and any given line
2015 You don't need to give the line-numbers in order, and any given line
2016 number can appear multiple times. You can assemble macros with any
2016 number can appear multiple times. You can assemble macros with any
2017 lines from your input history in any order.
2017 lines from your input history in any order.
2018
2018
2019 The macro is a simple object which holds its value in an attribute,
2019 The macro is a simple object which holds its value in an attribute,
2020 but IPython's display system checks for macros and executes them as
2020 but IPython's display system checks for macros and executes them as
2021 code instead of printing them when you type their name.
2021 code instead of printing them when you type their name.
2022
2022
2023 You can view a macro's contents by explicitly printing it with:
2023 You can view a macro's contents by explicitly printing it with:
2024
2024
2025 'print macro_name'.
2025 'print macro_name'.
2026
2026
2027 For one-off cases which DON'T contain magic function calls in them you
2027 For one-off cases which DON'T contain magic function calls in them you
2028 can obtain similar results by explicitly executing slices from your
2028 can obtain similar results by explicitly executing slices from your
2029 input history with:
2029 input history with:
2030
2030
2031 In [60]: exec In[44:48]+In[49]"""
2031 In [60]: exec In[44:48]+In[49]"""
2032
2032
2033 opts,args = self.parse_options(parameter_s,'r',mode='list')
2033 opts,args = self.parse_options(parameter_s,'r',mode='list')
2034 if not args:
2034 if not args:
2035 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2035 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2036 macs.sort()
2036 macs.sort()
2037 return macs
2037 return macs
2038 if len(args) == 1:
2038 if len(args) == 1:
2039 raise UsageError(
2039 raise UsageError(
2040 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2040 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2041 name,ranges = args[0], args[1:]
2041 name,ranges = args[0], args[1:]
2042
2042
2043 #print 'rng',ranges # dbg
2043 #print 'rng',ranges # dbg
2044 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2044 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2045 macro = Macro(lines)
2045 macro = Macro(lines)
2046 self.shell.define_macro(name, macro)
2046 self.shell.define_macro(name, macro)
2047 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2047 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2048 print 'Macro contents:'
2048 print 'Macro contents:'
2049 print macro,
2049 print macro,
2050
2050
2051 def magic_save(self,parameter_s = ''):
2051 def magic_save(self,parameter_s = ''):
2052 """Save a set of lines to a given filename.
2052 """Save a set of lines to a given filename.
2053
2053
2054 Usage:\\
2054 Usage:\\
2055 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2055 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2056
2056
2057 Options:
2057 Options:
2058
2058
2059 -r: use 'raw' input. By default, the 'processed' history is used,
2059 -r: use 'raw' input. By default, the 'processed' history is used,
2060 so that magics are loaded in their transformed version to valid
2060 so that magics are loaded in their transformed version to valid
2061 Python. If this option is given, the raw input as typed as the
2061 Python. If this option is given, the raw input as typed as the
2062 command line is used instead.
2062 command line is used instead.
2063
2063
2064 This function uses the same syntax as %macro for line extraction, but
2064 This function uses the same syntax as %macro for line extraction, but
2065 instead of creating a macro it saves the resulting string to the
2065 instead of creating a macro it saves the resulting string to the
2066 filename you specify.
2066 filename you specify.
2067
2067
2068 It adds a '.py' extension to the file if you don't do so yourself, and
2068 It adds a '.py' extension to the file if you don't do so yourself, and
2069 it asks for confirmation before overwriting existing files."""
2069 it asks for confirmation before overwriting existing files."""
2070
2070
2071 opts,args = self.parse_options(parameter_s,'r',mode='list')
2071 opts,args = self.parse_options(parameter_s,'r',mode='list')
2072 fname,ranges = args[0], args[1:]
2072 fname,ranges = args[0], args[1:]
2073 if not fname.endswith('.py'):
2073 if not fname.endswith('.py'):
2074 fname += '.py'
2074 fname += '.py'
2075 if os.path.isfile(fname):
2075 if os.path.isfile(fname):
2076 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2076 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2077 if ans.lower() not in ['y','yes']:
2077 if ans.lower() not in ['y','yes']:
2078 print 'Operation cancelled.'
2078 print 'Operation cancelled.'
2079 return
2079 return
2080 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2080 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2081 f = file(fname,'w')
2081 f = file(fname,'w')
2082 f.write(cmds)
2082 f.write(cmds)
2083 f.close()
2083 f.close()
2084 print 'The following commands were written to file `%s`:' % fname
2084 print 'The following commands were written to file `%s`:' % fname
2085 print cmds
2085 print cmds
2086
2086
2087 def _edit_macro(self,mname,macro):
2087 def _edit_macro(self,mname,macro):
2088 """open an editor with the macro data in a file"""
2088 """open an editor with the macro data in a file"""
2089 filename = self.shell.mktempfile(macro.value)
2089 filename = self.shell.mktempfile(macro.value)
2090 self.shell.hooks.editor(filename)
2090 self.shell.hooks.editor(filename)
2091
2091
2092 # and make a new macro object, to replace the old one
2092 # and make a new macro object, to replace the old one
2093 mfile = open(filename)
2093 mfile = open(filename)
2094 mvalue = mfile.read()
2094 mvalue = mfile.read()
2095 mfile.close()
2095 mfile.close()
2096 self.shell.user_ns[mname] = Macro(mvalue)
2096 self.shell.user_ns[mname] = Macro(mvalue)
2097
2097
2098 def magic_ed(self,parameter_s=''):
2098 def magic_ed(self,parameter_s=''):
2099 """Alias to %edit."""
2099 """Alias to %edit."""
2100 return self.magic_edit(parameter_s)
2100 return self.magic_edit(parameter_s)
2101
2101
2102 @testdec.skip_doctest
2102 @testdec.skip_doctest
2103 def magic_edit(self,parameter_s='',last_call=['','']):
2103 def magic_edit(self,parameter_s='',last_call=['','']):
2104 """Bring up an editor and execute the resulting code.
2104 """Bring up an editor and execute the resulting code.
2105
2105
2106 Usage:
2106 Usage:
2107 %edit [options] [args]
2107 %edit [options] [args]
2108
2108
2109 %edit runs IPython's editor hook. The default version of this hook is
2109 %edit runs IPython's editor hook. The default version of this hook is
2110 set to call the __IPYTHON__.rc.editor command. This is read from your
2110 set to call the __IPYTHON__.rc.editor command. This is read from your
2111 environment variable $EDITOR. If this isn't found, it will default to
2111 environment variable $EDITOR. If this isn't found, it will default to
2112 vi under Linux/Unix and to notepad under Windows. See the end of this
2112 vi under Linux/Unix and to notepad under Windows. See the end of this
2113 docstring for how to change the editor hook.
2113 docstring for how to change the editor hook.
2114
2114
2115 You can also set the value of this editor via the command line option
2115 You can also set the value of this editor via the command line option
2116 '-editor' or in your ipythonrc file. This is useful if you wish to use
2116 '-editor' or in your ipythonrc file. This is useful if you wish to use
2117 specifically for IPython an editor different from your typical default
2117 specifically for IPython an editor different from your typical default
2118 (and for Windows users who typically don't set environment variables).
2118 (and for Windows users who typically don't set environment variables).
2119
2119
2120 This command allows you to conveniently edit multi-line code right in
2120 This command allows you to conveniently edit multi-line code right in
2121 your IPython session.
2121 your IPython session.
2122
2122
2123 If called without arguments, %edit opens up an empty editor with a
2123 If called without arguments, %edit opens up an empty editor with a
2124 temporary file and will execute the contents of this file when you
2124 temporary file and will execute the contents of this file when you
2125 close it (don't forget to save it!).
2125 close it (don't forget to save it!).
2126
2126
2127
2127
2128 Options:
2128 Options:
2129
2129
2130 -n <number>: open the editor at a specified line number. By default,
2130 -n <number>: open the editor at a specified line number. By default,
2131 the IPython editor hook uses the unix syntax 'editor +N filename', but
2131 the IPython editor hook uses the unix syntax 'editor +N filename', but
2132 you can configure this by providing your own modified hook if your
2132 you can configure this by providing your own modified hook if your
2133 favorite editor supports line-number specifications with a different
2133 favorite editor supports line-number specifications with a different
2134 syntax.
2134 syntax.
2135
2135
2136 -p: this will call the editor with the same data as the previous time
2136 -p: this will call the editor with the same data as the previous time
2137 it was used, regardless of how long ago (in your current session) it
2137 it was used, regardless of how long ago (in your current session) it
2138 was.
2138 was.
2139
2139
2140 -r: use 'raw' input. This option only applies to input taken from the
2140 -r: use 'raw' input. This option only applies to input taken from the
2141 user's history. By default, the 'processed' history is used, so that
2141 user's history. By default, the 'processed' history is used, so that
2142 magics are loaded in their transformed version to valid Python. If
2142 magics are loaded in their transformed version to valid Python. If
2143 this option is given, the raw input as typed as the command line is
2143 this option is given, the raw input as typed as the command line is
2144 used instead. When you exit the editor, it will be executed by
2144 used instead. When you exit the editor, it will be executed by
2145 IPython's own processor.
2145 IPython's own processor.
2146
2146
2147 -x: do not execute the edited code immediately upon exit. This is
2147 -x: do not execute the edited code immediately upon exit. This is
2148 mainly useful if you are editing programs which need to be called with
2148 mainly useful if you are editing programs which need to be called with
2149 command line arguments, which you can then do using %run.
2149 command line arguments, which you can then do using %run.
2150
2150
2151
2151
2152 Arguments:
2152 Arguments:
2153
2153
2154 If arguments are given, the following possibilites exist:
2154 If arguments are given, the following possibilites exist:
2155
2155
2156 - The arguments are numbers or pairs of colon-separated numbers (like
2156 - The arguments are numbers or pairs of colon-separated numbers (like
2157 1 4:8 9). These are interpreted as lines of previous input to be
2157 1 4:8 9). These are interpreted as lines of previous input to be
2158 loaded into the editor. The syntax is the same of the %macro command.
2158 loaded into the editor. The syntax is the same of the %macro command.
2159
2159
2160 - If the argument doesn't start with a number, it is evaluated as a
2160 - If the argument doesn't start with a number, it is evaluated as a
2161 variable and its contents loaded into the editor. You can thus edit
2161 variable and its contents loaded into the editor. You can thus edit
2162 any string which contains python code (including the result of
2162 any string which contains python code (including the result of
2163 previous edits).
2163 previous edits).
2164
2164
2165 - If the argument is the name of an object (other than a string),
2165 - If the argument is the name of an object (other than a string),
2166 IPython will try to locate the file where it was defined and open the
2166 IPython will try to locate the file where it was defined and open the
2167 editor at the point where it is defined. You can use `%edit function`
2167 editor at the point where it is defined. You can use `%edit function`
2168 to load an editor exactly at the point where 'function' is defined,
2168 to load an editor exactly at the point where 'function' is defined,
2169 edit it and have the file be executed automatically.
2169 edit it and have the file be executed automatically.
2170
2170
2171 If the object is a macro (see %macro for details), this opens up your
2171 If the object is a macro (see %macro for details), this opens up your
2172 specified editor with a temporary file containing the macro's data.
2172 specified editor with a temporary file containing the macro's data.
2173 Upon exit, the macro is reloaded with the contents of the file.
2173 Upon exit, the macro is reloaded with the contents of the file.
2174
2174
2175 Note: opening at an exact line is only supported under Unix, and some
2175 Note: opening at an exact line is only supported under Unix, and some
2176 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2176 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2177 '+NUMBER' parameter necessary for this feature. Good editors like
2177 '+NUMBER' parameter necessary for this feature. Good editors like
2178 (X)Emacs, vi, jed, pico and joe all do.
2178 (X)Emacs, vi, jed, pico and joe all do.
2179
2179
2180 - If the argument is not found as a variable, IPython will look for a
2180 - If the argument is not found as a variable, IPython will look for a
2181 file with that name (adding .py if necessary) and load it into the
2181 file with that name (adding .py if necessary) and load it into the
2182 editor. It will execute its contents with execfile() when you exit,
2182 editor. It will execute its contents with execfile() when you exit,
2183 loading any code in the file into your interactive namespace.
2183 loading any code in the file into your interactive namespace.
2184
2184
2185 After executing your code, %edit will return as output the code you
2185 After executing your code, %edit will return as output the code you
2186 typed in the editor (except when it was an existing file). This way
2186 typed in the editor (except when it was an existing file). This way
2187 you can reload the code in further invocations of %edit as a variable,
2187 you can reload the code in further invocations of %edit as a variable,
2188 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2188 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2189 the output.
2189 the output.
2190
2190
2191 Note that %edit is also available through the alias %ed.
2191 Note that %edit is also available through the alias %ed.
2192
2192
2193 This is an example of creating a simple function inside the editor and
2193 This is an example of creating a simple function inside the editor and
2194 then modifying it. First, start up the editor:
2194 then modifying it. First, start up the editor:
2195
2195
2196 In [1]: ed
2196 In [1]: ed
2197 Editing... done. Executing edited code...
2197 Editing... done. Executing edited code...
2198 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2198 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2199
2199
2200 We can then call the function foo():
2200 We can then call the function foo():
2201
2201
2202 In [2]: foo()
2202 In [2]: foo()
2203 foo() was defined in an editing session
2203 foo() was defined in an editing session
2204
2204
2205 Now we edit foo. IPython automatically loads the editor with the
2205 Now we edit foo. IPython automatically loads the editor with the
2206 (temporary) file where foo() was previously defined:
2206 (temporary) file where foo() was previously defined:
2207
2207
2208 In [3]: ed foo
2208 In [3]: ed foo
2209 Editing... done. Executing edited code...
2209 Editing... done. Executing edited code...
2210
2210
2211 And if we call foo() again we get the modified version:
2211 And if we call foo() again we get the modified version:
2212
2212
2213 In [4]: foo()
2213 In [4]: foo()
2214 foo() has now been changed!
2214 foo() has now been changed!
2215
2215
2216 Here is an example of how to edit a code snippet successive
2216 Here is an example of how to edit a code snippet successive
2217 times. First we call the editor:
2217 times. First we call the editor:
2218
2218
2219 In [5]: ed
2219 In [5]: ed
2220 Editing... done. Executing edited code...
2220 Editing... done. Executing edited code...
2221 hello
2221 hello
2222 Out[5]: "print 'hello'n"
2222 Out[5]: "print 'hello'n"
2223
2223
2224 Now we call it again with the previous output (stored in _):
2224 Now we call it again with the previous output (stored in _):
2225
2225
2226 In [6]: ed _
2226 In [6]: ed _
2227 Editing... done. Executing edited code...
2227 Editing... done. Executing edited code...
2228 hello world
2228 hello world
2229 Out[6]: "print 'hello world'n"
2229 Out[6]: "print 'hello world'n"
2230
2230
2231 Now we call it with the output #8 (stored in _8, also as Out[8]):
2231 Now we call it with the output #8 (stored in _8, also as Out[8]):
2232
2232
2233 In [7]: ed _8
2233 In [7]: ed _8
2234 Editing... done. Executing edited code...
2234 Editing... done. Executing edited code...
2235 hello again
2235 hello again
2236 Out[7]: "print 'hello again'n"
2236 Out[7]: "print 'hello again'n"
2237
2237
2238
2238
2239 Changing the default editor hook:
2239 Changing the default editor hook:
2240
2240
2241 If you wish to write your own editor hook, you can put it in a
2241 If you wish to write your own editor hook, you can put it in a
2242 configuration file which you load at startup time. The default hook
2242 configuration file which you load at startup time. The default hook
2243 is defined in the IPython.core.hooks module, and you can use that as a
2243 is defined in the IPython.core.hooks module, and you can use that as a
2244 starting example for further modifications. That file also has
2244 starting example for further modifications. That file also has
2245 general instructions on how to set a new hook for use once you've
2245 general instructions on how to set a new hook for use once you've
2246 defined it."""
2246 defined it."""
2247
2247
2248 # FIXME: This function has become a convoluted mess. It needs a
2248 # FIXME: This function has become a convoluted mess. It needs a
2249 # ground-up rewrite with clean, simple logic.
2249 # ground-up rewrite with clean, simple logic.
2250
2250
2251 def make_filename(arg):
2251 def make_filename(arg):
2252 "Make a filename from the given args"
2252 "Make a filename from the given args"
2253 try:
2253 try:
2254 filename = get_py_filename(arg)
2254 filename = get_py_filename(arg)
2255 except IOError:
2255 except IOError:
2256 if args.endswith('.py'):
2256 if args.endswith('.py'):
2257 filename = arg
2257 filename = arg
2258 else:
2258 else:
2259 filename = None
2259 filename = None
2260 return filename
2260 return filename
2261
2261
2262 # custom exceptions
2262 # custom exceptions
2263 class DataIsObject(Exception): pass
2263 class DataIsObject(Exception): pass
2264
2264
2265 opts,args = self.parse_options(parameter_s,'prxn:')
2265 opts,args = self.parse_options(parameter_s,'prxn:')
2266 # Set a few locals from the options for convenience:
2266 # Set a few locals from the options for convenience:
2267 opts_p = opts.has_key('p')
2267 opts_p = opts.has_key('p')
2268 opts_r = opts.has_key('r')
2268 opts_r = opts.has_key('r')
2269
2269
2270 # Default line number value
2270 # Default line number value
2271 lineno = opts.get('n',None)
2271 lineno = opts.get('n',None)
2272
2272
2273 if opts_p:
2273 if opts_p:
2274 args = '_%s' % last_call[0]
2274 args = '_%s' % last_call[0]
2275 if not self.shell.user_ns.has_key(args):
2275 if not self.shell.user_ns.has_key(args):
2276 args = last_call[1]
2276 args = last_call[1]
2277
2277
2278 # use last_call to remember the state of the previous call, but don't
2278 # use last_call to remember the state of the previous call, but don't
2279 # let it be clobbered by successive '-p' calls.
2279 # let it be clobbered by successive '-p' calls.
2280 try:
2280 try:
2281 last_call[0] = self.shell.outputcache.prompt_count
2281 last_call[0] = self.shell.outputcache.prompt_count
2282 if not opts_p:
2282 if not opts_p:
2283 last_call[1] = parameter_s
2283 last_call[1] = parameter_s
2284 except:
2284 except:
2285 pass
2285 pass
2286
2286
2287 # by default this is done with temp files, except when the given
2287 # by default this is done with temp files, except when the given
2288 # arg is a filename
2288 # arg is a filename
2289 use_temp = 1
2289 use_temp = 1
2290
2290
2291 if re.match(r'\d',args):
2291 if re.match(r'\d',args):
2292 # Mode where user specifies ranges of lines, like in %macro.
2292 # Mode where user specifies ranges of lines, like in %macro.
2293 # This means that you can't edit files whose names begin with
2293 # This means that you can't edit files whose names begin with
2294 # numbers this way. Tough.
2294 # numbers this way. Tough.
2295 ranges = args.split()
2295 ranges = args.split()
2296 data = ''.join(self.extract_input_slices(ranges,opts_r))
2296 data = ''.join(self.extract_input_slices(ranges,opts_r))
2297 elif args.endswith('.py'):
2297 elif args.endswith('.py'):
2298 filename = make_filename(args)
2298 filename = make_filename(args)
2299 data = ''
2299 data = ''
2300 use_temp = 0
2300 use_temp = 0
2301 elif args:
2301 elif args:
2302 try:
2302 try:
2303 # Load the parameter given as a variable. If not a string,
2303 # Load the parameter given as a variable. If not a string,
2304 # process it as an object instead (below)
2304 # process it as an object instead (below)
2305
2305
2306 #print '*** args',args,'type',type(args) # dbg
2306 #print '*** args',args,'type',type(args) # dbg
2307 data = eval(args,self.shell.user_ns)
2307 data = eval(args,self.shell.user_ns)
2308 if not type(data) in StringTypes:
2308 if not type(data) in StringTypes:
2309 raise DataIsObject
2309 raise DataIsObject
2310
2310
2311 except (NameError,SyntaxError):
2311 except (NameError,SyntaxError):
2312 # given argument is not a variable, try as a filename
2312 # given argument is not a variable, try as a filename
2313 filename = make_filename(args)
2313 filename = make_filename(args)
2314 if filename is None:
2314 if filename is None:
2315 warn("Argument given (%s) can't be found as a variable "
2315 warn("Argument given (%s) can't be found as a variable "
2316 "or as a filename." % args)
2316 "or as a filename." % args)
2317 return
2317 return
2318
2318
2319 data = ''
2319 data = ''
2320 use_temp = 0
2320 use_temp = 0
2321 except DataIsObject:
2321 except DataIsObject:
2322
2322
2323 # macros have a special edit function
2323 # macros have a special edit function
2324 if isinstance(data,Macro):
2324 if isinstance(data,Macro):
2325 self._edit_macro(args,data)
2325 self._edit_macro(args,data)
2326 return
2326 return
2327
2327
2328 # For objects, try to edit the file where they are defined
2328 # For objects, try to edit the file where they are defined
2329 try:
2329 try:
2330 filename = inspect.getabsfile(data)
2330 filename = inspect.getabsfile(data)
2331 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2331 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2332 # class created by %edit? Try to find source
2332 # class created by %edit? Try to find source
2333 # by looking for method definitions instead, the
2333 # by looking for method definitions instead, the
2334 # __module__ in those classes is FakeModule.
2334 # __module__ in those classes is FakeModule.
2335 attrs = [getattr(data, aname) for aname in dir(data)]
2335 attrs = [getattr(data, aname) for aname in dir(data)]
2336 for attr in attrs:
2336 for attr in attrs:
2337 if not inspect.ismethod(attr):
2337 if not inspect.ismethod(attr):
2338 continue
2338 continue
2339 filename = inspect.getabsfile(attr)
2339 filename = inspect.getabsfile(attr)
2340 if filename and 'fakemodule' not in filename.lower():
2340 if filename and 'fakemodule' not in filename.lower():
2341 # change the attribute to be the edit target instead
2341 # change the attribute to be the edit target instead
2342 data = attr
2342 data = attr
2343 break
2343 break
2344
2344
2345 datafile = 1
2345 datafile = 1
2346 except TypeError:
2346 except TypeError:
2347 filename = make_filename(args)
2347 filename = make_filename(args)
2348 datafile = 1
2348 datafile = 1
2349 warn('Could not find file where `%s` is defined.\n'
2349 warn('Could not find file where `%s` is defined.\n'
2350 'Opening a file named `%s`' % (args,filename))
2350 'Opening a file named `%s`' % (args,filename))
2351 # Now, make sure we can actually read the source (if it was in
2351 # Now, make sure we can actually read the source (if it was in
2352 # a temp file it's gone by now).
2352 # a temp file it's gone by now).
2353 if datafile:
2353 if datafile:
2354 try:
2354 try:
2355 if lineno is None:
2355 if lineno is None:
2356 lineno = inspect.getsourcelines(data)[1]
2356 lineno = inspect.getsourcelines(data)[1]
2357 except IOError:
2357 except IOError:
2358 filename = make_filename(args)
2358 filename = make_filename(args)
2359 if filename is None:
2359 if filename is None:
2360 warn('The file `%s` where `%s` was defined cannot '
2360 warn('The file `%s` where `%s` was defined cannot '
2361 'be read.' % (filename,data))
2361 'be read.' % (filename,data))
2362 return
2362 return
2363 use_temp = 0
2363 use_temp = 0
2364 else:
2364 else:
2365 data = ''
2365 data = ''
2366
2366
2367 if use_temp:
2367 if use_temp:
2368 filename = self.shell.mktempfile(data)
2368 filename = self.shell.mktempfile(data)
2369 print 'IPython will make a temporary file named:',filename
2369 print 'IPython will make a temporary file named:',filename
2370
2370
2371 # do actual editing here
2371 # do actual editing here
2372 print 'Editing...',
2372 print 'Editing...',
2373 sys.stdout.flush()
2373 sys.stdout.flush()
2374 try:
2374 try:
2375 self.shell.hooks.editor(filename,lineno)
2375 self.shell.hooks.editor(filename,lineno)
2376 except TryNext:
2376 except TryNext:
2377 warn('Could not open editor')
2377 warn('Could not open editor')
2378 return
2378 return
2379
2379
2380 # XXX TODO: should this be generalized for all string vars?
2380 # XXX TODO: should this be generalized for all string vars?
2381 # For now, this is special-cased to blocks created by cpaste
2381 # For now, this is special-cased to blocks created by cpaste
2382 if args.strip() == 'pasted_block':
2382 if args.strip() == 'pasted_block':
2383 self.shell.user_ns['pasted_block'] = file_read(filename)
2383 self.shell.user_ns['pasted_block'] = file_read(filename)
2384
2384
2385 if opts.has_key('x'): # -x prevents actual execution
2385 if opts.has_key('x'): # -x prevents actual execution
2386 print
2386 print
2387 else:
2387 else:
2388 print 'done. Executing edited code...'
2388 print 'done. Executing edited code...'
2389 if opts_r:
2389 if opts_r:
2390 self.shell.runlines(file_read(filename))
2390 self.shell.runlines(file_read(filename))
2391 else:
2391 else:
2392 self.shell.safe_execfile(filename,self.shell.user_ns,
2392 self.shell.safe_execfile(filename,self.shell.user_ns,
2393 self.shell.user_ns)
2393 self.shell.user_ns)
2394
2394
2395
2395
2396 if use_temp:
2396 if use_temp:
2397 try:
2397 try:
2398 return open(filename).read()
2398 return open(filename).read()
2399 except IOError,msg:
2399 except IOError,msg:
2400 if msg.filename == filename:
2400 if msg.filename == filename:
2401 warn('File not found. Did you forget to save?')
2401 warn('File not found. Did you forget to save?')
2402 return
2402 return
2403 else:
2403 else:
2404 self.shell.showtraceback()
2404 self.shell.showtraceback()
2405
2405
2406 def magic_xmode(self,parameter_s = ''):
2406 def magic_xmode(self,parameter_s = ''):
2407 """Switch modes for the exception handlers.
2407 """Switch modes for the exception handlers.
2408
2408
2409 Valid modes: Plain, Context and Verbose.
2409 Valid modes: Plain, Context and Verbose.
2410
2410
2411 If called without arguments, acts as a toggle."""
2411 If called without arguments, acts as a toggle."""
2412
2412
2413 def xmode_switch_err(name):
2413 def xmode_switch_err(name):
2414 warn('Error changing %s exception modes.\n%s' %
2414 warn('Error changing %s exception modes.\n%s' %
2415 (name,sys.exc_info()[1]))
2415 (name,sys.exc_info()[1]))
2416
2416
2417 shell = self.shell
2417 shell = self.shell
2418 new_mode = parameter_s.strip().capitalize()
2418 new_mode = parameter_s.strip().capitalize()
2419 try:
2419 try:
2420 shell.InteractiveTB.set_mode(mode=new_mode)
2420 shell.InteractiveTB.set_mode(mode=new_mode)
2421 print 'Exception reporting mode:',shell.InteractiveTB.mode
2421 print 'Exception reporting mode:',shell.InteractiveTB.mode
2422 except:
2422 except:
2423 xmode_switch_err('user')
2423 xmode_switch_err('user')
2424
2424
2425 # threaded shells use a special handler in sys.excepthook
2425 # threaded shells use a special handler in sys.excepthook
2426 if shell.isthreaded:
2426 if shell.isthreaded:
2427 try:
2427 try:
2428 shell.sys_excepthook.set_mode(mode=new_mode)
2428 shell.sys_excepthook.set_mode(mode=new_mode)
2429 except:
2429 except:
2430 xmode_switch_err('threaded')
2430 xmode_switch_err('threaded')
2431
2431
2432 def magic_colors(self,parameter_s = ''):
2432 def magic_colors(self,parameter_s = ''):
2433 """Switch color scheme for prompts, info system and exception handlers.
2433 """Switch color scheme for prompts, info system and exception handlers.
2434
2434
2435 Currently implemented schemes: NoColor, Linux, LightBG.
2435 Currently implemented schemes: NoColor, Linux, LightBG.
2436
2436
2437 Color scheme names are not case-sensitive."""
2437 Color scheme names are not case-sensitive."""
2438
2438
2439 def color_switch_err(name):
2439 def color_switch_err(name):
2440 warn('Error changing %s color schemes.\n%s' %
2440 warn('Error changing %s color schemes.\n%s' %
2441 (name,sys.exc_info()[1]))
2441 (name,sys.exc_info()[1]))
2442
2442
2443
2443
2444 new_scheme = parameter_s.strip()
2444 new_scheme = parameter_s.strip()
2445 if not new_scheme:
2445 if not new_scheme:
2446 raise UsageError(
2446 raise UsageError(
2447 "%colors: you must specify a color scheme. See '%colors?'")
2447 "%colors: you must specify a color scheme. See '%colors?'")
2448 return
2448 return
2449 # local shortcut
2449 # local shortcut
2450 shell = self.shell
2450 shell = self.shell
2451
2451
2452 import IPython.utils.rlineimpl as readline
2452 import IPython.utils.rlineimpl as readline
2453
2453
2454 if not readline.have_readline and sys.platform == "win32":
2454 if not readline.have_readline and sys.platform == "win32":
2455 msg = """\
2455 msg = """\
2456 Proper color support under MS Windows requires the pyreadline library.
2456 Proper color support under MS Windows requires the pyreadline library.
2457 You can find it at:
2457 You can find it at:
2458 http://ipython.scipy.org/moin/PyReadline/Intro
2458 http://ipython.scipy.org/moin/PyReadline/Intro
2459 Gary's readline needs the ctypes module, from:
2459 Gary's readline needs the ctypes module, from:
2460 http://starship.python.net/crew/theller/ctypes
2460 http://starship.python.net/crew/theller/ctypes
2461 (Note that ctypes is already part of Python versions 2.5 and newer).
2461 (Note that ctypes is already part of Python versions 2.5 and newer).
2462
2462
2463 Defaulting color scheme to 'NoColor'"""
2463 Defaulting color scheme to 'NoColor'"""
2464 new_scheme = 'NoColor'
2464 new_scheme = 'NoColor'
2465 warn(msg)
2465 warn(msg)
2466
2466
2467 # readline option is 0
2467 # readline option is 0
2468 if not shell.has_readline:
2468 if not shell.has_readline:
2469 new_scheme = 'NoColor'
2469 new_scheme = 'NoColor'
2470
2470
2471 # Set prompt colors
2471 # Set prompt colors
2472 try:
2472 try:
2473 shell.outputcache.set_colors(new_scheme)
2473 shell.outputcache.set_colors(new_scheme)
2474 except:
2474 except:
2475 color_switch_err('prompt')
2475 color_switch_err('prompt')
2476 else:
2476 else:
2477 shell.colors = \
2477 shell.colors = \
2478 shell.outputcache.color_table.active_scheme_name
2478 shell.outputcache.color_table.active_scheme_name
2479 # Set exception colors
2479 # Set exception colors
2480 try:
2480 try:
2481 shell.InteractiveTB.set_colors(scheme = new_scheme)
2481 shell.InteractiveTB.set_colors(scheme = new_scheme)
2482 shell.SyntaxTB.set_colors(scheme = new_scheme)
2482 shell.SyntaxTB.set_colors(scheme = new_scheme)
2483 except:
2483 except:
2484 color_switch_err('exception')
2484 color_switch_err('exception')
2485
2485
2486 # threaded shells use a verbose traceback in sys.excepthook
2486 # threaded shells use a verbose traceback in sys.excepthook
2487 if shell.isthreaded:
2487 if shell.isthreaded:
2488 try:
2488 try:
2489 shell.sys_excepthook.set_colors(scheme=new_scheme)
2489 shell.sys_excepthook.set_colors(scheme=new_scheme)
2490 except:
2490 except:
2491 color_switch_err('system exception handler')
2491 color_switch_err('system exception handler')
2492
2492
2493 # Set info (for 'object?') colors
2493 # Set info (for 'object?') colors
2494 if shell.color_info:
2494 if shell.color_info:
2495 try:
2495 try:
2496 shell.inspector.set_active_scheme(new_scheme)
2496 shell.inspector.set_active_scheme(new_scheme)
2497 except:
2497 except:
2498 color_switch_err('object inspector')
2498 color_switch_err('object inspector')
2499 else:
2499 else:
2500 shell.inspector.set_active_scheme('NoColor')
2500 shell.inspector.set_active_scheme('NoColor')
2501
2501
2502 def magic_color_info(self,parameter_s = ''):
2502 def magic_color_info(self,parameter_s = ''):
2503 """Toggle color_info.
2503 """Toggle color_info.
2504
2504
2505 The color_info configuration parameter controls whether colors are
2505 The color_info configuration parameter controls whether colors are
2506 used for displaying object details (by things like %psource, %pfile or
2506 used for displaying object details (by things like %psource, %pfile or
2507 the '?' system). This function toggles this value with each call.
2507 the '?' system). This function toggles this value with each call.
2508
2508
2509 Note that unless you have a fairly recent pager (less works better
2509 Note that unless you have a fairly recent pager (less works better
2510 than more) in your system, using colored object information displays
2510 than more) in your system, using colored object information displays
2511 will not work properly. Test it and see."""
2511 will not work properly. Test it and see."""
2512
2512
2513 self.shell.color_info = not self.shell.color_info
2513 self.shell.color_info = not self.shell.color_info
2514 self.magic_colors(self.shell.colors)
2514 self.magic_colors(self.shell.colors)
2515 print 'Object introspection functions have now coloring:',
2515 print 'Object introspection functions have now coloring:',
2516 print ['OFF','ON'][int(self.shell.color_info)]
2516 print ['OFF','ON'][int(self.shell.color_info)]
2517
2517
2518 def magic_Pprint(self, parameter_s=''):
2518 def magic_Pprint(self, parameter_s=''):
2519 """Toggle pretty printing on/off."""
2519 """Toggle pretty printing on/off."""
2520
2520
2521 self.shell.pprint = 1 - self.shell.pprint
2521 self.shell.pprint = 1 - self.shell.pprint
2522 print 'Pretty printing has been turned', \
2522 print 'Pretty printing has been turned', \
2523 ['OFF','ON'][self.shell.pprint]
2523 ['OFF','ON'][self.shell.pprint]
2524
2524
2525 def magic_exit(self, parameter_s=''):
2525 def magic_exit(self, parameter_s=''):
2526 """Exit IPython, confirming if configured to do so.
2526 """Exit IPython, confirming if configured to do so.
2527
2527
2528 You can configure whether IPython asks for confirmation upon exit by
2528 You can configure whether IPython asks for confirmation upon exit by
2529 setting the confirm_exit flag in the ipythonrc file."""
2529 setting the confirm_exit flag in the ipythonrc file."""
2530
2530
2531 self.shell.exit()
2531 self.shell.exit()
2532
2532
2533 def magic_quit(self, parameter_s=''):
2533 def magic_quit(self, parameter_s=''):
2534 """Exit IPython, confirming if configured to do so (like %exit)"""
2534 """Exit IPython, confirming if configured to do so (like %exit)"""
2535
2535
2536 self.shell.exit()
2536 self.shell.exit()
2537
2537
2538 def magic_Exit(self, parameter_s=''):
2538 def magic_Exit(self, parameter_s=''):
2539 """Exit IPython without confirmation."""
2539 """Exit IPython without confirmation."""
2540
2540
2541 self.shell.ask_exit()
2541 self.shell.ask_exit()
2542
2542
2543 #......................................................................
2543 #......................................................................
2544 # Functions to implement unix shell-type things
2544 # Functions to implement unix shell-type things
2545
2545
2546 @testdec.skip_doctest
2546 @testdec.skip_doctest
2547 def magic_alias(self, parameter_s = ''):
2547 def magic_alias(self, parameter_s = ''):
2548 """Define an alias for a system command.
2548 """Define an alias for a system command.
2549
2549
2550 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2550 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2551
2551
2552 Then, typing 'alias_name params' will execute the system command 'cmd
2552 Then, typing 'alias_name params' will execute the system command 'cmd
2553 params' (from your underlying operating system).
2553 params' (from your underlying operating system).
2554
2554
2555 Aliases have lower precedence than magic functions and Python normal
2555 Aliases have lower precedence than magic functions and Python normal
2556 variables, so if 'foo' is both a Python variable and an alias, the
2556 variables, so if 'foo' is both a Python variable and an alias, the
2557 alias can not be executed until 'del foo' removes the Python variable.
2557 alias can not be executed until 'del foo' removes the Python variable.
2558
2558
2559 You can use the %l specifier in an alias definition to represent the
2559 You can use the %l specifier in an alias definition to represent the
2560 whole line when the alias is called. For example:
2560 whole line when the alias is called. For example:
2561
2561
2562 In [2]: alias all echo "Input in brackets: <%l>"
2562 In [2]: alias all echo "Input in brackets: <%l>"
2563 In [3]: all hello world
2563 In [3]: all hello world
2564 Input in brackets: <hello world>
2564 Input in brackets: <hello world>
2565
2565
2566 You can also define aliases with parameters using %s specifiers (one
2566 You can also define aliases with parameters using %s specifiers (one
2567 per parameter):
2567 per parameter):
2568
2568
2569 In [1]: alias parts echo first %s second %s
2569 In [1]: alias parts echo first %s second %s
2570 In [2]: %parts A B
2570 In [2]: %parts A B
2571 first A second B
2571 first A second B
2572 In [3]: %parts A
2572 In [3]: %parts A
2573 Incorrect number of arguments: 2 expected.
2573 Incorrect number of arguments: 2 expected.
2574 parts is an alias to: 'echo first %s second %s'
2574 parts is an alias to: 'echo first %s second %s'
2575
2575
2576 Note that %l and %s are mutually exclusive. You can only use one or
2576 Note that %l and %s are mutually exclusive. You can only use one or
2577 the other in your aliases.
2577 the other in your aliases.
2578
2578
2579 Aliases expand Python variables just like system calls using ! or !!
2579 Aliases expand Python variables just like system calls using ! or !!
2580 do: all expressions prefixed with '$' get expanded. For details of
2580 do: all expressions prefixed with '$' get expanded. For details of
2581 the semantic rules, see PEP-215:
2581 the semantic rules, see PEP-215:
2582 http://www.python.org/peps/pep-0215.html. This is the library used by
2582 http://www.python.org/peps/pep-0215.html. This is the library used by
2583 IPython for variable expansion. If you want to access a true shell
2583 IPython for variable expansion. If you want to access a true shell
2584 variable, an extra $ is necessary to prevent its expansion by IPython:
2584 variable, an extra $ is necessary to prevent its expansion by IPython:
2585
2585
2586 In [6]: alias show echo
2586 In [6]: alias show echo
2587 In [7]: PATH='A Python string'
2587 In [7]: PATH='A Python string'
2588 In [8]: show $PATH
2588 In [8]: show $PATH
2589 A Python string
2589 A Python string
2590 In [9]: show $$PATH
2590 In [9]: show $$PATH
2591 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2591 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2592
2592
2593 You can use the alias facility to acess all of $PATH. See the %rehash
2593 You can use the alias facility to acess all of $PATH. See the %rehash
2594 and %rehashx functions, which automatically create aliases for the
2594 and %rehashx functions, which automatically create aliases for the
2595 contents of your $PATH.
2595 contents of your $PATH.
2596
2596
2597 If called with no parameters, %alias prints the current alias table."""
2597 If called with no parameters, %alias prints the current alias table."""
2598
2598
2599 par = parameter_s.strip()
2599 par = parameter_s.strip()
2600 if not par:
2600 if not par:
2601 stored = self.db.get('stored_aliases', {} )
2601 stored = self.db.get('stored_aliases', {} )
2602 aliases = sorted(self.shell.alias_manager.aliases)
2602 aliases = sorted(self.shell.alias_manager.aliases)
2603 # for k, v in stored:
2603 # for k, v in stored:
2604 # atab.append(k, v[0])
2604 # atab.append(k, v[0])
2605
2605
2606 print "Total number of aliases:", len(aliases)
2606 print "Total number of aliases:", len(aliases)
2607 return aliases
2607 return aliases
2608
2608
2609 # Now try to define a new one
2609 # Now try to define a new one
2610 try:
2610 try:
2611 alias,cmd = par.split(None, 1)
2611 alias,cmd = par.split(None, 1)
2612 except:
2612 except:
2613 print oinspect.getdoc(self.magic_alias)
2613 print oinspect.getdoc(self.magic_alias)
2614 else:
2614 else:
2615 self.shell.alias_manager.soft_define_alias(alias, cmd)
2615 self.shell.alias_manager.soft_define_alias(alias, cmd)
2616 # end magic_alias
2616 # end magic_alias
2617
2617
2618 def magic_unalias(self, parameter_s = ''):
2618 def magic_unalias(self, parameter_s = ''):
2619 """Remove an alias"""
2619 """Remove an alias"""
2620
2620
2621 aname = parameter_s.strip()
2621 aname = parameter_s.strip()
2622 self.shell.alias_manager.undefine_alias(aname)
2622 self.shell.alias_manager.undefine_alias(aname)
2623 stored = self.db.get('stored_aliases', {} )
2623 stored = self.db.get('stored_aliases', {} )
2624 if aname in stored:
2624 if aname in stored:
2625 print "Removing %stored alias",aname
2625 print "Removing %stored alias",aname
2626 del stored[aname]
2626 del stored[aname]
2627 self.db['stored_aliases'] = stored
2627 self.db['stored_aliases'] = stored
2628
2628
2629
2629
2630 def magic_rehashx(self, parameter_s = ''):
2630 def magic_rehashx(self, parameter_s = ''):
2631 """Update the alias table with all executable files in $PATH.
2631 """Update the alias table with all executable files in $PATH.
2632
2632
2633 This version explicitly checks that every entry in $PATH is a file
2633 This version explicitly checks that every entry in $PATH is a file
2634 with execute access (os.X_OK), so it is much slower than %rehash.
2634 with execute access (os.X_OK), so it is much slower than %rehash.
2635
2635
2636 Under Windows, it checks executability as a match agains a
2636 Under Windows, it checks executability as a match agains a
2637 '|'-separated string of extensions, stored in the IPython config
2637 '|'-separated string of extensions, stored in the IPython config
2638 variable win_exec_ext. This defaults to 'exe|com|bat'.
2638 variable win_exec_ext. This defaults to 'exe|com|bat'.
2639
2639
2640 This function also resets the root module cache of module completer,
2640 This function also resets the root module cache of module completer,
2641 used on slow filesystems.
2641 used on slow filesystems.
2642 """
2642 """
2643 from IPython.core.alias import InvalidAliasError
2643 from IPython.core.alias import InvalidAliasError
2644
2644
2645 # for the benefit of module completer in ipy_completers.py
2645 # for the benefit of module completer in ipy_completers.py
2646 del self.db['rootmodules']
2646 del self.db['rootmodules']
2647
2647
2648 path = [os.path.abspath(os.path.expanduser(p)) for p in
2648 path = [os.path.abspath(os.path.expanduser(p)) for p in
2649 os.environ.get('PATH','').split(os.pathsep)]
2649 os.environ.get('PATH','').split(os.pathsep)]
2650 path = filter(os.path.isdir,path)
2650 path = filter(os.path.isdir,path)
2651
2651
2652 syscmdlist = []
2652 syscmdlist = []
2653 # Now define isexec in a cross platform manner.
2653 # Now define isexec in a cross platform manner.
2654 if os.name == 'posix':
2654 if os.name == 'posix':
2655 isexec = lambda fname:os.path.isfile(fname) and \
2655 isexec = lambda fname:os.path.isfile(fname) and \
2656 os.access(fname,os.X_OK)
2656 os.access(fname,os.X_OK)
2657 else:
2657 else:
2658 try:
2658 try:
2659 winext = os.environ['pathext'].replace(';','|').replace('.','')
2659 winext = os.environ['pathext'].replace(';','|').replace('.','')
2660 except KeyError:
2660 except KeyError:
2661 winext = 'exe|com|bat|py'
2661 winext = 'exe|com|bat|py'
2662 if 'py' not in winext:
2662 if 'py' not in winext:
2663 winext += '|py'
2663 winext += '|py'
2664 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2664 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2665 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2665 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2666 savedir = os.getcwd()
2666 savedir = os.getcwd()
2667
2667
2668 # Now walk the paths looking for executables to alias.
2668 # Now walk the paths looking for executables to alias.
2669 try:
2669 try:
2670 # write the whole loop for posix/Windows so we don't have an if in
2670 # write the whole loop for posix/Windows so we don't have an if in
2671 # the innermost part
2671 # the innermost part
2672 if os.name == 'posix':
2672 if os.name == 'posix':
2673 for pdir in path:
2673 for pdir in path:
2674 os.chdir(pdir)
2674 os.chdir(pdir)
2675 for ff in os.listdir(pdir):
2675 for ff in os.listdir(pdir):
2676 if isexec(ff):
2676 if isexec(ff):
2677 try:
2677 try:
2678 # Removes dots from the name since ipython
2678 # Removes dots from the name since ipython
2679 # will assume names with dots to be python.
2679 # will assume names with dots to be python.
2680 self.shell.alias_manager.define_alias(
2680 self.shell.alias_manager.define_alias(
2681 ff.replace('.',''), ff)
2681 ff.replace('.',''), ff)
2682 except InvalidAliasError:
2682 except InvalidAliasError:
2683 pass
2683 pass
2684 else:
2684 else:
2685 syscmdlist.append(ff)
2685 syscmdlist.append(ff)
2686 else:
2686 else:
2687 for pdir in path:
2687 for pdir in path:
2688 os.chdir(pdir)
2688 os.chdir(pdir)
2689 for ff in os.listdir(pdir):
2689 for ff in os.listdir(pdir):
2690 base, ext = os.path.splitext(ff)
2690 base, ext = os.path.splitext(ff)
2691 if isexec(ff) and base.lower() not in self.shell.no_alias:
2691 if isexec(ff) and base.lower() not in self.shell.no_alias:
2692 if ext.lower() == '.exe':
2692 if ext.lower() == '.exe':
2693 ff = base
2693 ff = base
2694 try:
2694 try:
2695 # Removes dots from the name since ipython
2695 # Removes dots from the name since ipython
2696 # will assume names with dots to be python.
2696 # will assume names with dots to be python.
2697 self.shell.alias_manager.define_alias(
2697 self.shell.alias_manager.define_alias(
2698 base.lower().replace('.',''), ff)
2698 base.lower().replace('.',''), ff)
2699 except InvalidAliasError:
2699 except InvalidAliasError:
2700 pass
2700 pass
2701 syscmdlist.append(ff)
2701 syscmdlist.append(ff)
2702 db = self.db
2702 db = self.db
2703 db['syscmdlist'] = syscmdlist
2703 db['syscmdlist'] = syscmdlist
2704 finally:
2704 finally:
2705 os.chdir(savedir)
2705 os.chdir(savedir)
2706
2706
2707 def magic_pwd(self, parameter_s = ''):
2707 def magic_pwd(self, parameter_s = ''):
2708 """Return the current working directory path."""
2708 """Return the current working directory path."""
2709 return os.getcwd()
2709 return os.getcwd()
2710
2710
2711 def magic_cd(self, parameter_s=''):
2711 def magic_cd(self, parameter_s=''):
2712 """Change the current working directory.
2712 """Change the current working directory.
2713
2713
2714 This command automatically maintains an internal list of directories
2714 This command automatically maintains an internal list of directories
2715 you visit during your IPython session, in the variable _dh. The
2715 you visit during your IPython session, in the variable _dh. The
2716 command %dhist shows this history nicely formatted. You can also
2716 command %dhist shows this history nicely formatted. You can also
2717 do 'cd -<tab>' to see directory history conveniently.
2717 do 'cd -<tab>' to see directory history conveniently.
2718
2718
2719 Usage:
2719 Usage:
2720
2720
2721 cd 'dir': changes to directory 'dir'.
2721 cd 'dir': changes to directory 'dir'.
2722
2722
2723 cd -: changes to the last visited directory.
2723 cd -: changes to the last visited directory.
2724
2724
2725 cd -<n>: changes to the n-th directory in the directory history.
2725 cd -<n>: changes to the n-th directory in the directory history.
2726
2726
2727 cd --foo: change to directory that matches 'foo' in history
2727 cd --foo: change to directory that matches 'foo' in history
2728
2728
2729 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2729 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2730 (note: cd <bookmark_name> is enough if there is no
2730 (note: cd <bookmark_name> is enough if there is no
2731 directory <bookmark_name>, but a bookmark with the name exists.)
2731 directory <bookmark_name>, but a bookmark with the name exists.)
2732 'cd -b <tab>' allows you to tab-complete bookmark names.
2732 'cd -b <tab>' allows you to tab-complete bookmark names.
2733
2733
2734 Options:
2734 Options:
2735
2735
2736 -q: quiet. Do not print the working directory after the cd command is
2736 -q: quiet. Do not print the working directory after the cd command is
2737 executed. By default IPython's cd command does print this directory,
2737 executed. By default IPython's cd command does print this directory,
2738 since the default prompts do not display path information.
2738 since the default prompts do not display path information.
2739
2739
2740 Note that !cd doesn't work for this purpose because the shell where
2740 Note that !cd doesn't work for this purpose because the shell where
2741 !command runs is immediately discarded after executing 'command'."""
2741 !command runs is immediately discarded after executing 'command'."""
2742
2742
2743 parameter_s = parameter_s.strip()
2743 parameter_s = parameter_s.strip()
2744 #bkms = self.shell.persist.get("bookmarks",{})
2744 #bkms = self.shell.persist.get("bookmarks",{})
2745
2745
2746 oldcwd = os.getcwd()
2746 oldcwd = os.getcwd()
2747 numcd = re.match(r'(-)(\d+)$',parameter_s)
2747 numcd = re.match(r'(-)(\d+)$',parameter_s)
2748 # jump in directory history by number
2748 # jump in directory history by number
2749 if numcd:
2749 if numcd:
2750 nn = int(numcd.group(2))
2750 nn = int(numcd.group(2))
2751 try:
2751 try:
2752 ps = self.shell.user_ns['_dh'][nn]
2752 ps = self.shell.user_ns['_dh'][nn]
2753 except IndexError:
2753 except IndexError:
2754 print 'The requested directory does not exist in history.'
2754 print 'The requested directory does not exist in history.'
2755 return
2755 return
2756 else:
2756 else:
2757 opts = {}
2757 opts = {}
2758 elif parameter_s.startswith('--'):
2758 elif parameter_s.startswith('--'):
2759 ps = None
2759 ps = None
2760 fallback = None
2760 fallback = None
2761 pat = parameter_s[2:]
2761 pat = parameter_s[2:]
2762 dh = self.shell.user_ns['_dh']
2762 dh = self.shell.user_ns['_dh']
2763 # first search only by basename (last component)
2763 # first search only by basename (last component)
2764 for ent in reversed(dh):
2764 for ent in reversed(dh):
2765 if pat in os.path.basename(ent) and os.path.isdir(ent):
2765 if pat in os.path.basename(ent) and os.path.isdir(ent):
2766 ps = ent
2766 ps = ent
2767 break
2767 break
2768
2768
2769 if fallback is None and pat in ent and os.path.isdir(ent):
2769 if fallback is None and pat in ent and os.path.isdir(ent):
2770 fallback = ent
2770 fallback = ent
2771
2771
2772 # if we have no last part match, pick the first full path match
2772 # if we have no last part match, pick the first full path match
2773 if ps is None:
2773 if ps is None:
2774 ps = fallback
2774 ps = fallback
2775
2775
2776 if ps is None:
2776 if ps is None:
2777 print "No matching entry in directory history"
2777 print "No matching entry in directory history"
2778 return
2778 return
2779 else:
2779 else:
2780 opts = {}
2780 opts = {}
2781
2781
2782
2782
2783 else:
2783 else:
2784 #turn all non-space-escaping backslashes to slashes,
2784 #turn all non-space-escaping backslashes to slashes,
2785 # for c:\windows\directory\names\
2785 # for c:\windows\directory\names\
2786 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2786 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2787 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2787 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2788 # jump to previous
2788 # jump to previous
2789 if ps == '-':
2789 if ps == '-':
2790 try:
2790 try:
2791 ps = self.shell.user_ns['_dh'][-2]
2791 ps = self.shell.user_ns['_dh'][-2]
2792 except IndexError:
2792 except IndexError:
2793 raise UsageError('%cd -: No previous directory to change to.')
2793 raise UsageError('%cd -: No previous directory to change to.')
2794 # jump to bookmark if needed
2794 # jump to bookmark if needed
2795 else:
2795 else:
2796 if not os.path.isdir(ps) or opts.has_key('b'):
2796 if not os.path.isdir(ps) or opts.has_key('b'):
2797 bkms = self.db.get('bookmarks', {})
2797 bkms = self.db.get('bookmarks', {})
2798
2798
2799 if bkms.has_key(ps):
2799 if bkms.has_key(ps):
2800 target = bkms[ps]
2800 target = bkms[ps]
2801 print '(bookmark:%s) -> %s' % (ps,target)
2801 print '(bookmark:%s) -> %s' % (ps,target)
2802 ps = target
2802 ps = target
2803 else:
2803 else:
2804 if opts.has_key('b'):
2804 if opts.has_key('b'):
2805 raise UsageError("Bookmark '%s' not found. "
2805 raise UsageError("Bookmark '%s' not found. "
2806 "Use '%%bookmark -l' to see your bookmarks." % ps)
2806 "Use '%%bookmark -l' to see your bookmarks." % ps)
2807
2807
2808 # at this point ps should point to the target dir
2808 # at this point ps should point to the target dir
2809 if ps:
2809 if ps:
2810 try:
2810 try:
2811 os.chdir(os.path.expanduser(ps))
2811 os.chdir(os.path.expanduser(ps))
2812 if self.shell.term_title:
2812 if self.shell.term_title:
2813 platutils.set_term_title('IPython: ' + abbrev_cwd())
2813 platutils.set_term_title('IPython: ' + abbrev_cwd())
2814 except OSError:
2814 except OSError:
2815 print sys.exc_info()[1]
2815 print sys.exc_info()[1]
2816 else:
2816 else:
2817 cwd = os.getcwd()
2817 cwd = os.getcwd()
2818 dhist = self.shell.user_ns['_dh']
2818 dhist = self.shell.user_ns['_dh']
2819 if oldcwd != cwd:
2819 if oldcwd != cwd:
2820 dhist.append(cwd)
2820 dhist.append(cwd)
2821 self.db['dhist'] = compress_dhist(dhist)[-100:]
2821 self.db['dhist'] = compress_dhist(dhist)[-100:]
2822
2822
2823 else:
2823 else:
2824 os.chdir(self.shell.home_dir)
2824 os.chdir(self.shell.home_dir)
2825 if self.shell.term_title:
2825 if self.shell.term_title:
2826 platutils.set_term_title('IPython: ' + '~')
2826 platutils.set_term_title('IPython: ' + '~')
2827 cwd = os.getcwd()
2827 cwd = os.getcwd()
2828 dhist = self.shell.user_ns['_dh']
2828 dhist = self.shell.user_ns['_dh']
2829
2829
2830 if oldcwd != cwd:
2830 if oldcwd != cwd:
2831 dhist.append(cwd)
2831 dhist.append(cwd)
2832 self.db['dhist'] = compress_dhist(dhist)[-100:]
2832 self.db['dhist'] = compress_dhist(dhist)[-100:]
2833 if not 'q' in opts and self.shell.user_ns['_dh']:
2833 if not 'q' in opts and self.shell.user_ns['_dh']:
2834 print self.shell.user_ns['_dh'][-1]
2834 print self.shell.user_ns['_dh'][-1]
2835
2835
2836
2836
2837 def magic_env(self, parameter_s=''):
2837 def magic_env(self, parameter_s=''):
2838 """List environment variables."""
2838 """List environment variables."""
2839
2839
2840 return os.environ.data
2840 return os.environ.data
2841
2841
2842 def magic_pushd(self, parameter_s=''):
2842 def magic_pushd(self, parameter_s=''):
2843 """Place the current dir on stack and change directory.
2843 """Place the current dir on stack and change directory.
2844
2844
2845 Usage:\\
2845 Usage:\\
2846 %pushd ['dirname']
2846 %pushd ['dirname']
2847 """
2847 """
2848
2848
2849 dir_s = self.shell.dir_stack
2849 dir_s = self.shell.dir_stack
2850 tgt = os.path.expanduser(parameter_s)
2850 tgt = os.path.expanduser(parameter_s)
2851 cwd = os.getcwd().replace(self.home_dir,'~')
2851 cwd = os.getcwd().replace(self.home_dir,'~')
2852 if tgt:
2852 if tgt:
2853 self.magic_cd(parameter_s)
2853 self.magic_cd(parameter_s)
2854 dir_s.insert(0,cwd)
2854 dir_s.insert(0,cwd)
2855 return self.magic_dirs()
2855 return self.magic_dirs()
2856
2856
2857 def magic_popd(self, parameter_s=''):
2857 def magic_popd(self, parameter_s=''):
2858 """Change to directory popped off the top of the stack.
2858 """Change to directory popped off the top of the stack.
2859 """
2859 """
2860 if not self.shell.dir_stack:
2860 if not self.shell.dir_stack:
2861 raise UsageError("%popd on empty stack")
2861 raise UsageError("%popd on empty stack")
2862 top = self.shell.dir_stack.pop(0)
2862 top = self.shell.dir_stack.pop(0)
2863 self.magic_cd(top)
2863 self.magic_cd(top)
2864 print "popd ->",top
2864 print "popd ->",top
2865
2865
2866 def magic_dirs(self, parameter_s=''):
2866 def magic_dirs(self, parameter_s=''):
2867 """Return the current directory stack."""
2867 """Return the current directory stack."""
2868
2868
2869 return self.shell.dir_stack
2869 return self.shell.dir_stack
2870
2870
2871 def magic_dhist(self, parameter_s=''):
2871 def magic_dhist(self, parameter_s=''):
2872 """Print your history of visited directories.
2872 """Print your history of visited directories.
2873
2873
2874 %dhist -> print full history\\
2874 %dhist -> print full history\\
2875 %dhist n -> print last n entries only\\
2875 %dhist n -> print last n entries only\\
2876 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2876 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2877
2877
2878 This history is automatically maintained by the %cd command, and
2878 This history is automatically maintained by the %cd command, and
2879 always available as the global list variable _dh. You can use %cd -<n>
2879 always available as the global list variable _dh. You can use %cd -<n>
2880 to go to directory number <n>.
2880 to go to directory number <n>.
2881
2881
2882 Note that most of time, you should view directory history by entering
2882 Note that most of time, you should view directory history by entering
2883 cd -<TAB>.
2883 cd -<TAB>.
2884
2884
2885 """
2885 """
2886
2886
2887 dh = self.shell.user_ns['_dh']
2887 dh = self.shell.user_ns['_dh']
2888 if parameter_s:
2888 if parameter_s:
2889 try:
2889 try:
2890 args = map(int,parameter_s.split())
2890 args = map(int,parameter_s.split())
2891 except:
2891 except:
2892 self.arg_err(Magic.magic_dhist)
2892 self.arg_err(Magic.magic_dhist)
2893 return
2893 return
2894 if len(args) == 1:
2894 if len(args) == 1:
2895 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2895 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2896 elif len(args) == 2:
2896 elif len(args) == 2:
2897 ini,fin = args
2897 ini,fin = args
2898 else:
2898 else:
2899 self.arg_err(Magic.magic_dhist)
2899 self.arg_err(Magic.magic_dhist)
2900 return
2900 return
2901 else:
2901 else:
2902 ini,fin = 0,len(dh)
2902 ini,fin = 0,len(dh)
2903 nlprint(dh,
2903 nlprint(dh,
2904 header = 'Directory history (kept in _dh)',
2904 header = 'Directory history (kept in _dh)',
2905 start=ini,stop=fin)
2905 start=ini,stop=fin)
2906
2906
2907 @testdec.skip_doctest
2907 @testdec.skip_doctest
2908 def magic_sc(self, parameter_s=''):
2908 def magic_sc(self, parameter_s=''):
2909 """Shell capture - execute a shell command and capture its output.
2909 """Shell capture - execute a shell command and capture its output.
2910
2910
2911 DEPRECATED. Suboptimal, retained for backwards compatibility.
2911 DEPRECATED. Suboptimal, retained for backwards compatibility.
2912
2912
2913 You should use the form 'var = !command' instead. Example:
2913 You should use the form 'var = !command' instead. Example:
2914
2914
2915 "%sc -l myfiles = ls ~" should now be written as
2915 "%sc -l myfiles = ls ~" should now be written as
2916
2916
2917 "myfiles = !ls ~"
2917 "myfiles = !ls ~"
2918
2918
2919 myfiles.s, myfiles.l and myfiles.n still apply as documented
2919 myfiles.s, myfiles.l and myfiles.n still apply as documented
2920 below.
2920 below.
2921
2921
2922 --
2922 --
2923 %sc [options] varname=command
2923 %sc [options] varname=command
2924
2924
2925 IPython will run the given command using commands.getoutput(), and
2925 IPython will run the given command using commands.getoutput(), and
2926 will then update the user's interactive namespace with a variable
2926 will then update the user's interactive namespace with a variable
2927 called varname, containing the value of the call. Your command can
2927 called varname, containing the value of the call. Your command can
2928 contain shell wildcards, pipes, etc.
2928 contain shell wildcards, pipes, etc.
2929
2929
2930 The '=' sign in the syntax is mandatory, and the variable name you
2930 The '=' sign in the syntax is mandatory, and the variable name you
2931 supply must follow Python's standard conventions for valid names.
2931 supply must follow Python's standard conventions for valid names.
2932
2932
2933 (A special format without variable name exists for internal use)
2933 (A special format without variable name exists for internal use)
2934
2934
2935 Options:
2935 Options:
2936
2936
2937 -l: list output. Split the output on newlines into a list before
2937 -l: list output. Split the output on newlines into a list before
2938 assigning it to the given variable. By default the output is stored
2938 assigning it to the given variable. By default the output is stored
2939 as a single string.
2939 as a single string.
2940
2940
2941 -v: verbose. Print the contents of the variable.
2941 -v: verbose. Print the contents of the variable.
2942
2942
2943 In most cases you should not need to split as a list, because the
2943 In most cases you should not need to split as a list, because the
2944 returned value is a special type of string which can automatically
2944 returned value is a special type of string which can automatically
2945 provide its contents either as a list (split on newlines) or as a
2945 provide its contents either as a list (split on newlines) or as a
2946 space-separated string. These are convenient, respectively, either
2946 space-separated string. These are convenient, respectively, either
2947 for sequential processing or to be passed to a shell command.
2947 for sequential processing or to be passed to a shell command.
2948
2948
2949 For example:
2949 For example:
2950
2950
2951 # all-random
2951 # all-random
2952
2952
2953 # Capture into variable a
2953 # Capture into variable a
2954 In [1]: sc a=ls *py
2954 In [1]: sc a=ls *py
2955
2955
2956 # a is a string with embedded newlines
2956 # a is a string with embedded newlines
2957 In [2]: a
2957 In [2]: a
2958 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2958 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2959
2959
2960 # which can be seen as a list:
2960 # which can be seen as a list:
2961 In [3]: a.l
2961 In [3]: a.l
2962 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2962 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2963
2963
2964 # or as a whitespace-separated string:
2964 # or as a whitespace-separated string:
2965 In [4]: a.s
2965 In [4]: a.s
2966 Out[4]: 'setup.py win32_manual_post_install.py'
2966 Out[4]: 'setup.py win32_manual_post_install.py'
2967
2967
2968 # a.s is useful to pass as a single command line:
2968 # a.s is useful to pass as a single command line:
2969 In [5]: !wc -l $a.s
2969 In [5]: !wc -l $a.s
2970 146 setup.py
2970 146 setup.py
2971 130 win32_manual_post_install.py
2971 130 win32_manual_post_install.py
2972 276 total
2972 276 total
2973
2973
2974 # while the list form is useful to loop over:
2974 # while the list form is useful to loop over:
2975 In [6]: for f in a.l:
2975 In [6]: for f in a.l:
2976 ...: !wc -l $f
2976 ...: !wc -l $f
2977 ...:
2977 ...:
2978 146 setup.py
2978 146 setup.py
2979 130 win32_manual_post_install.py
2979 130 win32_manual_post_install.py
2980
2980
2981 Similiarly, the lists returned by the -l option are also special, in
2981 Similiarly, the lists returned by the -l option are also special, in
2982 the sense that you can equally invoke the .s attribute on them to
2982 the sense that you can equally invoke the .s attribute on them to
2983 automatically get a whitespace-separated string from their contents:
2983 automatically get a whitespace-separated string from their contents:
2984
2984
2985 In [7]: sc -l b=ls *py
2985 In [7]: sc -l b=ls *py
2986
2986
2987 In [8]: b
2987 In [8]: b
2988 Out[8]: ['setup.py', 'win32_manual_post_install.py']
2988 Out[8]: ['setup.py', 'win32_manual_post_install.py']
2989
2989
2990 In [9]: b.s
2990 In [9]: b.s
2991 Out[9]: 'setup.py win32_manual_post_install.py'
2991 Out[9]: 'setup.py win32_manual_post_install.py'
2992
2992
2993 In summary, both the lists and strings used for ouptut capture have
2993 In summary, both the lists and strings used for ouptut capture have
2994 the following special attributes:
2994 the following special attributes:
2995
2995
2996 .l (or .list) : value as list.
2996 .l (or .list) : value as list.
2997 .n (or .nlstr): value as newline-separated string.
2997 .n (or .nlstr): value as newline-separated string.
2998 .s (or .spstr): value as space-separated string.
2998 .s (or .spstr): value as space-separated string.
2999 """
2999 """
3000
3000
3001 opts,args = self.parse_options(parameter_s,'lv')
3001 opts,args = self.parse_options(parameter_s,'lv')
3002 # Try to get a variable name and command to run
3002 # Try to get a variable name and command to run
3003 try:
3003 try:
3004 # the variable name must be obtained from the parse_options
3004 # the variable name must be obtained from the parse_options
3005 # output, which uses shlex.split to strip options out.
3005 # output, which uses shlex.split to strip options out.
3006 var,_ = args.split('=',1)
3006 var,_ = args.split('=',1)
3007 var = var.strip()
3007 var = var.strip()
3008 # But the the command has to be extracted from the original input
3008 # But the the command has to be extracted from the original input
3009 # parameter_s, not on what parse_options returns, to avoid the
3009 # parameter_s, not on what parse_options returns, to avoid the
3010 # quote stripping which shlex.split performs on it.
3010 # quote stripping which shlex.split performs on it.
3011 _,cmd = parameter_s.split('=',1)
3011 _,cmd = parameter_s.split('=',1)
3012 except ValueError:
3012 except ValueError:
3013 var,cmd = '',''
3013 var,cmd = '',''
3014 # If all looks ok, proceed
3014 # If all looks ok, proceed
3015 out,err = self.shell.getoutputerror(cmd)
3015 out,err = self.shell.getoutputerror(cmd)
3016 if err:
3016 if err:
3017 print >> Term.cerr,err
3017 print >> Term.cerr,err
3018 if opts.has_key('l'):
3018 if opts.has_key('l'):
3019 out = SList(out.split('\n'))
3019 out = SList(out.split('\n'))
3020 else:
3020 else:
3021 out = LSString(out)
3021 out = LSString(out)
3022 if opts.has_key('v'):
3022 if opts.has_key('v'):
3023 print '%s ==\n%s' % (var,pformat(out))
3023 print '%s ==\n%s' % (var,pformat(out))
3024 if var:
3024 if var:
3025 self.shell.user_ns.update({var:out})
3025 self.shell.user_ns.update({var:out})
3026 else:
3026 else:
3027 return out
3027 return out
3028
3028
3029 def magic_sx(self, parameter_s=''):
3029 def magic_sx(self, parameter_s=''):
3030 """Shell execute - run a shell command and capture its output.
3030 """Shell execute - run a shell command and capture its output.
3031
3031
3032 %sx command
3032 %sx command
3033
3033
3034 IPython will run the given command using commands.getoutput(), and
3034 IPython will run the given command using commands.getoutput(), and
3035 return the result formatted as a list (split on '\\n'). Since the
3035 return the result formatted as a list (split on '\\n'). Since the
3036 output is _returned_, it will be stored in ipython's regular output
3036 output is _returned_, it will be stored in ipython's regular output
3037 cache Out[N] and in the '_N' automatic variables.
3037 cache Out[N] and in the '_N' automatic variables.
3038
3038
3039 Notes:
3039 Notes:
3040
3040
3041 1) If an input line begins with '!!', then %sx is automatically
3041 1) If an input line begins with '!!', then %sx is automatically
3042 invoked. That is, while:
3042 invoked. That is, while:
3043 !ls
3043 !ls
3044 causes ipython to simply issue system('ls'), typing
3044 causes ipython to simply issue system('ls'), typing
3045 !!ls
3045 !!ls
3046 is a shorthand equivalent to:
3046 is a shorthand equivalent to:
3047 %sx ls
3047 %sx ls
3048
3048
3049 2) %sx differs from %sc in that %sx automatically splits into a list,
3049 2) %sx differs from %sc in that %sx automatically splits into a list,
3050 like '%sc -l'. The reason for this is to make it as easy as possible
3050 like '%sc -l'. The reason for this is to make it as easy as possible
3051 to process line-oriented shell output via further python commands.
3051 to process line-oriented shell output via further python commands.
3052 %sc is meant to provide much finer control, but requires more
3052 %sc is meant to provide much finer control, but requires more
3053 typing.
3053 typing.
3054
3054
3055 3) Just like %sc -l, this is a list with special attributes:
3055 3) Just like %sc -l, this is a list with special attributes:
3056
3056
3057 .l (or .list) : value as list.
3057 .l (or .list) : value as list.
3058 .n (or .nlstr): value as newline-separated string.
3058 .n (or .nlstr): value as newline-separated string.
3059 .s (or .spstr): value as whitespace-separated string.
3059 .s (or .spstr): value as whitespace-separated string.
3060
3060
3061 This is very useful when trying to use such lists as arguments to
3061 This is very useful when trying to use such lists as arguments to
3062 system commands."""
3062 system commands."""
3063
3063
3064 if parameter_s:
3064 if parameter_s:
3065 out,err = self.shell.getoutputerror(parameter_s)
3065 out,err = self.shell.getoutputerror(parameter_s)
3066 if err:
3066 if err:
3067 print >> Term.cerr,err
3067 print >> Term.cerr,err
3068 return SList(out.split('\n'))
3068 return SList(out.split('\n'))
3069
3069
3070 def magic_bg(self, parameter_s=''):
3070 def magic_bg(self, parameter_s=''):
3071 """Run a job in the background, in a separate thread.
3071 """Run a job in the background, in a separate thread.
3072
3072
3073 For example,
3073 For example,
3074
3074
3075 %bg myfunc(x,y,z=1)
3075 %bg myfunc(x,y,z=1)
3076
3076
3077 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
3077 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
3078 execution starts, a message will be printed indicating the job
3078 execution starts, a message will be printed indicating the job
3079 number. If your job number is 5, you can use
3079 number. If your job number is 5, you can use
3080
3080
3081 myvar = jobs.result(5) or myvar = jobs[5].result
3081 myvar = jobs.result(5) or myvar = jobs[5].result
3082
3082
3083 to assign this result to variable 'myvar'.
3083 to assign this result to variable 'myvar'.
3084
3084
3085 IPython has a job manager, accessible via the 'jobs' object. You can
3085 IPython has a job manager, accessible via the 'jobs' object. You can
3086 type jobs? to get more information about it, and use jobs.<TAB> to see
3086 type jobs? to get more information about it, and use jobs.<TAB> to see
3087 its attributes. All attributes not starting with an underscore are
3087 its attributes. All attributes not starting with an underscore are
3088 meant for public use.
3088 meant for public use.
3089
3089
3090 In particular, look at the jobs.new() method, which is used to create
3090 In particular, look at the jobs.new() method, which is used to create
3091 new jobs. This magic %bg function is just a convenience wrapper
3091 new jobs. This magic %bg function is just a convenience wrapper
3092 around jobs.new(), for expression-based jobs. If you want to create a
3092 around jobs.new(), for expression-based jobs. If you want to create a
3093 new job with an explicit function object and arguments, you must call
3093 new job with an explicit function object and arguments, you must call
3094 jobs.new() directly.
3094 jobs.new() directly.
3095
3095
3096 The jobs.new docstring also describes in detail several important
3096 The jobs.new docstring also describes in detail several important
3097 caveats associated with a thread-based model for background job
3097 caveats associated with a thread-based model for background job
3098 execution. Type jobs.new? for details.
3098 execution. Type jobs.new? for details.
3099
3099
3100 You can check the status of all jobs with jobs.status().
3100 You can check the status of all jobs with jobs.status().
3101
3101
3102 The jobs variable is set by IPython into the Python builtin namespace.
3102 The jobs variable is set by IPython into the Python builtin namespace.
3103 If you ever declare a variable named 'jobs', you will shadow this
3103 If you ever declare a variable named 'jobs', you will shadow this
3104 name. You can either delete your global jobs variable to regain
3104 name. You can either delete your global jobs variable to regain
3105 access to the job manager, or make a new name and assign it manually
3105 access to the job manager, or make a new name and assign it manually
3106 to the manager (stored in IPython's namespace). For example, to
3106 to the manager (stored in IPython's namespace). For example, to
3107 assign the job manager to the Jobs name, use:
3107 assign the job manager to the Jobs name, use:
3108
3108
3109 Jobs = __builtins__.jobs"""
3109 Jobs = __builtins__.jobs"""
3110
3110
3111 self.shell.jobs.new(parameter_s,self.shell.user_ns)
3111 self.shell.jobs.new(parameter_s,self.shell.user_ns)
3112
3112
3113 def magic_r(self, parameter_s=''):
3113 def magic_r(self, parameter_s=''):
3114 """Repeat previous input.
3114 """Repeat previous input.
3115
3115
3116 Note: Consider using the more powerfull %rep instead!
3116 Note: Consider using the more powerfull %rep instead!
3117
3117
3118 If given an argument, repeats the previous command which starts with
3118 If given an argument, repeats the previous command which starts with
3119 the same string, otherwise it just repeats the previous input.
3119 the same string, otherwise it just repeats the previous input.
3120
3120
3121 Shell escaped commands (with ! as first character) are not recognized
3121 Shell escaped commands (with ! as first character) are not recognized
3122 by this system, only pure python code and magic commands.
3122 by this system, only pure python code and magic commands.
3123 """
3123 """
3124
3124
3125 start = parameter_s.strip()
3125 start = parameter_s.strip()
3126 esc_magic = ESC_MAGIC
3126 esc_magic = ESC_MAGIC
3127 # Identify magic commands even if automagic is on (which means
3127 # Identify magic commands even if automagic is on (which means
3128 # the in-memory version is different from that typed by the user).
3128 # the in-memory version is different from that typed by the user).
3129 if self.shell.automagic:
3129 if self.shell.automagic:
3130 start_magic = esc_magic+start
3130 start_magic = esc_magic+start
3131 else:
3131 else:
3132 start_magic = start
3132 start_magic = start
3133 # Look through the input history in reverse
3133 # Look through the input history in reverse
3134 for n in range(len(self.shell.input_hist)-2,0,-1):
3134 for n in range(len(self.shell.input_hist)-2,0,-1):
3135 input = self.shell.input_hist[n]
3135 input = self.shell.input_hist[n]
3136 # skip plain 'r' lines so we don't recurse to infinity
3136 # skip plain 'r' lines so we don't recurse to infinity
3137 if input != '_ip.magic("r")\n' and \
3137 if input != '_ip.magic("r")\n' and \
3138 (input.startswith(start) or input.startswith(start_magic)):
3138 (input.startswith(start) or input.startswith(start_magic)):
3139 #print 'match',`input` # dbg
3139 #print 'match',`input` # dbg
3140 print 'Executing:',input,
3140 print 'Executing:',input,
3141 self.shell.runlines(input)
3141 self.shell.runlines(input)
3142 return
3142 return
3143 print 'No previous input matching `%s` found.' % start
3143 print 'No previous input matching `%s` found.' % start
3144
3144
3145
3145
3146 def magic_bookmark(self, parameter_s=''):
3146 def magic_bookmark(self, parameter_s=''):
3147 """Manage IPython's bookmark system.
3147 """Manage IPython's bookmark system.
3148
3148
3149 %bookmark <name> - set bookmark to current dir
3149 %bookmark <name> - set bookmark to current dir
3150 %bookmark <name> <dir> - set bookmark to <dir>
3150 %bookmark <name> <dir> - set bookmark to <dir>
3151 %bookmark -l - list all bookmarks
3151 %bookmark -l - list all bookmarks
3152 %bookmark -d <name> - remove bookmark
3152 %bookmark -d <name> - remove bookmark
3153 %bookmark -r - remove all bookmarks
3153 %bookmark -r - remove all bookmarks
3154
3154
3155 You can later on access a bookmarked folder with:
3155 You can later on access a bookmarked folder with:
3156 %cd -b <name>
3156 %cd -b <name>
3157 or simply '%cd <name>' if there is no directory called <name> AND
3157 or simply '%cd <name>' if there is no directory called <name> AND
3158 there is such a bookmark defined.
3158 there is such a bookmark defined.
3159
3159
3160 Your bookmarks persist through IPython sessions, but they are
3160 Your bookmarks persist through IPython sessions, but they are
3161 associated with each profile."""
3161 associated with each profile."""
3162
3162
3163 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3163 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3164 if len(args) > 2:
3164 if len(args) > 2:
3165 raise UsageError("%bookmark: too many arguments")
3165 raise UsageError("%bookmark: too many arguments")
3166
3166
3167 bkms = self.db.get('bookmarks',{})
3167 bkms = self.db.get('bookmarks',{})
3168
3168
3169 if opts.has_key('d'):
3169 if opts.has_key('d'):
3170 try:
3170 try:
3171 todel = args[0]
3171 todel = args[0]
3172 except IndexError:
3172 except IndexError:
3173 raise UsageError(
3173 raise UsageError(
3174 "%bookmark -d: must provide a bookmark to delete")
3174 "%bookmark -d: must provide a bookmark to delete")
3175 else:
3175 else:
3176 try:
3176 try:
3177 del bkms[todel]
3177 del bkms[todel]
3178 except KeyError:
3178 except KeyError:
3179 raise UsageError(
3179 raise UsageError(
3180 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3180 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3181
3181
3182 elif opts.has_key('r'):
3182 elif opts.has_key('r'):
3183 bkms = {}
3183 bkms = {}
3184 elif opts.has_key('l'):
3184 elif opts.has_key('l'):
3185 bks = bkms.keys()
3185 bks = bkms.keys()
3186 bks.sort()
3186 bks.sort()
3187 if bks:
3187 if bks:
3188 size = max(map(len,bks))
3188 size = max(map(len,bks))
3189 else:
3189 else:
3190 size = 0
3190 size = 0
3191 fmt = '%-'+str(size)+'s -> %s'
3191 fmt = '%-'+str(size)+'s -> %s'
3192 print 'Current bookmarks:'
3192 print 'Current bookmarks:'
3193 for bk in bks:
3193 for bk in bks:
3194 print fmt % (bk,bkms[bk])
3194 print fmt % (bk,bkms[bk])
3195 else:
3195 else:
3196 if not args:
3196 if not args:
3197 raise UsageError("%bookmark: You must specify the bookmark name")
3197 raise UsageError("%bookmark: You must specify the bookmark name")
3198 elif len(args)==1:
3198 elif len(args)==1:
3199 bkms[args[0]] = os.getcwd()
3199 bkms[args[0]] = os.getcwd()
3200 elif len(args)==2:
3200 elif len(args)==2:
3201 bkms[args[0]] = args[1]
3201 bkms[args[0]] = args[1]
3202 self.db['bookmarks'] = bkms
3202 self.db['bookmarks'] = bkms
3203
3203
3204 def magic_pycat(self, parameter_s=''):
3204 def magic_pycat(self, parameter_s=''):
3205 """Show a syntax-highlighted file through a pager.
3205 """Show a syntax-highlighted file through a pager.
3206
3206
3207 This magic is similar to the cat utility, but it will assume the file
3207 This magic is similar to the cat utility, but it will assume the file
3208 to be Python source and will show it with syntax highlighting. """
3208 to be Python source and will show it with syntax highlighting. """
3209
3209
3210 try:
3210 try:
3211 filename = get_py_filename(parameter_s)
3211 filename = get_py_filename(parameter_s)
3212 cont = file_read(filename)
3212 cont = file_read(filename)
3213 except IOError:
3213 except IOError:
3214 try:
3214 try:
3215 cont = eval(parameter_s,self.user_ns)
3215 cont = eval(parameter_s,self.user_ns)
3216 except NameError:
3216 except NameError:
3217 cont = None
3217 cont = None
3218 if cont is None:
3218 if cont is None:
3219 print "Error: no such file or variable"
3219 print "Error: no such file or variable"
3220 return
3220 return
3221
3221
3222 page(self.shell.pycolorize(cont),
3222 page(self.shell.pycolorize(cont),
3223 screen_lines=self.shell.usable_screen_length)
3223 screen_lines=self.shell.usable_screen_length)
3224
3224
3225 def _rerun_pasted(self):
3225 def _rerun_pasted(self):
3226 """ Rerun a previously pasted command.
3226 """ Rerun a previously pasted command.
3227 """
3227 """
3228 b = self.user_ns.get('pasted_block', None)
3228 b = self.user_ns.get('pasted_block', None)
3229 if b is None:
3229 if b is None:
3230 raise UsageError('No previous pasted block available')
3230 raise UsageError('No previous pasted block available')
3231 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3231 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3232 exec b in self.user_ns
3232 exec b in self.user_ns
3233
3233
3234 def _get_pasted_lines(self, sentinel):
3234 def _get_pasted_lines(self, sentinel):
3235 """ Yield pasted lines until the user enters the given sentinel value.
3235 """ Yield pasted lines until the user enters the given sentinel value.
3236 """
3236 """
3237 from IPython.core import iplib
3237 from IPython.core import iplib
3238 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3238 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3239 while True:
3239 while True:
3240 l = iplib.raw_input_original(':')
3240 l = iplib.raw_input_original(':')
3241 if l == sentinel:
3241 if l == sentinel:
3242 return
3242 return
3243 else:
3243 else:
3244 yield l
3244 yield l
3245
3245
3246 def _strip_pasted_lines_for_code(self, raw_lines):
3246 def _strip_pasted_lines_for_code(self, raw_lines):
3247 """ Strip non-code parts of a sequence of lines to return a block of
3247 """ Strip non-code parts of a sequence of lines to return a block of
3248 code.
3248 code.
3249 """
3249 """
3250 # Regular expressions that declare text we strip from the input:
3250 # Regular expressions that declare text we strip from the input:
3251 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3251 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3252 r'^\s*(\s?>)+', # Python input prompt
3252 r'^\s*(\s?>)+', # Python input prompt
3253 r'^\s*\.{3,}', # Continuation prompts
3253 r'^\s*\.{3,}', # Continuation prompts
3254 r'^\++',
3254 r'^\++',
3255 ]
3255 ]
3256
3256
3257 strip_from_start = map(re.compile,strip_re)
3257 strip_from_start = map(re.compile,strip_re)
3258
3258
3259 lines = []
3259 lines = []
3260 for l in raw_lines:
3260 for l in raw_lines:
3261 for pat in strip_from_start:
3261 for pat in strip_from_start:
3262 l = pat.sub('',l)
3262 l = pat.sub('',l)
3263 lines.append(l)
3263 lines.append(l)
3264
3264
3265 block = "\n".join(lines) + '\n'
3265 block = "\n".join(lines) + '\n'
3266 #print "block:\n",block
3266 #print "block:\n",block
3267 return block
3267 return block
3268
3268
3269 def _execute_block(self, block, par):
3269 def _execute_block(self, block, par):
3270 """ Execute a block, or store it in a variable, per the user's request.
3270 """ Execute a block, or store it in a variable, per the user's request.
3271 """
3271 """
3272 if not par:
3272 if not par:
3273 b = textwrap.dedent(block)
3273 b = textwrap.dedent(block)
3274 self.user_ns['pasted_block'] = b
3274 self.user_ns['pasted_block'] = b
3275 exec b in self.user_ns
3275 exec b in self.user_ns
3276 else:
3276 else:
3277 self.user_ns[par] = SList(block.splitlines())
3277 self.user_ns[par] = SList(block.splitlines())
3278 print "Block assigned to '%s'" % par
3278 print "Block assigned to '%s'" % par
3279
3279
3280 def magic_cpaste(self, parameter_s=''):
3280 def magic_cpaste(self, parameter_s=''):
3281 """Allows you to paste & execute a pre-formatted code block from clipboard.
3281 """Allows you to paste & execute a pre-formatted code block from clipboard.
3282
3282
3283 You must terminate the block with '--' (two minus-signs) alone on the
3283 You must terminate the block with '--' (two minus-signs) alone on the
3284 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3284 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3285 is the new sentinel for this operation)
3285 is the new sentinel for this operation)
3286
3286
3287 The block is dedented prior to execution to enable execution of method
3287 The block is dedented prior to execution to enable execution of method
3288 definitions. '>' and '+' characters at the beginning of a line are
3288 definitions. '>' and '+' characters at the beginning of a line are
3289 ignored, to allow pasting directly from e-mails, diff files and
3289 ignored, to allow pasting directly from e-mails, diff files and
3290 doctests (the '...' continuation prompt is also stripped). The
3290 doctests (the '...' continuation prompt is also stripped). The
3291 executed block is also assigned to variable named 'pasted_block' for
3291 executed block is also assigned to variable named 'pasted_block' for
3292 later editing with '%edit pasted_block'.
3292 later editing with '%edit pasted_block'.
3293
3293
3294 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3294 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3295 This assigns the pasted block to variable 'foo' as string, without
3295 This assigns the pasted block to variable 'foo' as string, without
3296 dedenting or executing it (preceding >>> and + is still stripped)
3296 dedenting or executing it (preceding >>> and + is still stripped)
3297
3297
3298 '%cpaste -r' re-executes the block previously entered by cpaste.
3298 '%cpaste -r' re-executes the block previously entered by cpaste.
3299
3299
3300 Do not be alarmed by garbled output on Windows (it's a readline bug).
3300 Do not be alarmed by garbled output on Windows (it's a readline bug).
3301 Just press enter and type -- (and press enter again) and the block
3301 Just press enter and type -- (and press enter again) and the block
3302 will be what was just pasted.
3302 will be what was just pasted.
3303
3303
3304 IPython statements (magics, shell escapes) are not supported (yet).
3304 IPython statements (magics, shell escapes) are not supported (yet).
3305
3305
3306 See also
3306 See also
3307 --------
3307 --------
3308 paste: automatically pull code from clipboard.
3308 paste: automatically pull code from clipboard.
3309 """
3309 """
3310
3310
3311 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3311 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3312 par = args.strip()
3312 par = args.strip()
3313 if opts.has_key('r'):
3313 if opts.has_key('r'):
3314 self._rerun_pasted()
3314 self._rerun_pasted()
3315 return
3315 return
3316
3316
3317 sentinel = opts.get('s','--')
3317 sentinel = opts.get('s','--')
3318
3318
3319 block = self._strip_pasted_lines_for_code(
3319 block = self._strip_pasted_lines_for_code(
3320 self._get_pasted_lines(sentinel))
3320 self._get_pasted_lines(sentinel))
3321
3321
3322 self._execute_block(block, par)
3322 self._execute_block(block, par)
3323
3323
3324 def magic_paste(self, parameter_s=''):
3324 def magic_paste(self, parameter_s=''):
3325 """Allows you to paste & execute a pre-formatted code block from clipboard.
3325 """Allows you to paste & execute a pre-formatted code block from clipboard.
3326
3326
3327 The text is pulled directly from the clipboard without user
3327 The text is pulled directly from the clipboard without user
3328 intervention and printed back on the screen before execution (unless
3328 intervention and printed back on the screen before execution (unless
3329 the -q flag is given to force quiet mode).
3329 the -q flag is given to force quiet mode).
3330
3330
3331 The block is dedented prior to execution to enable execution of method
3331 The block is dedented prior to execution to enable execution of method
3332 definitions. '>' and '+' characters at the beginning of a line are
3332 definitions. '>' and '+' characters at the beginning of a line are
3333 ignored, to allow pasting directly from e-mails, diff files and
3333 ignored, to allow pasting directly from e-mails, diff files and
3334 doctests (the '...' continuation prompt is also stripped). The
3334 doctests (the '...' continuation prompt is also stripped). The
3335 executed block is also assigned to variable named 'pasted_block' for
3335 executed block is also assigned to variable named 'pasted_block' for
3336 later editing with '%edit pasted_block'.
3336 later editing with '%edit pasted_block'.
3337
3337
3338 You can also pass a variable name as an argument, e.g. '%paste foo'.
3338 You can also pass a variable name as an argument, e.g. '%paste foo'.
3339 This assigns the pasted block to variable 'foo' as string, without
3339 This assigns the pasted block to variable 'foo' as string, without
3340 dedenting or executing it (preceding >>> and + is still stripped)
3340 dedenting or executing it (preceding >>> and + is still stripped)
3341
3341
3342 Options
3342 Options
3343 -------
3343 -------
3344
3344
3345 -r: re-executes the block previously entered by cpaste.
3345 -r: re-executes the block previously entered by cpaste.
3346
3346
3347 -q: quiet mode: do not echo the pasted text back to the terminal.
3347 -q: quiet mode: do not echo the pasted text back to the terminal.
3348
3348
3349 IPython statements (magics, shell escapes) are not supported (yet).
3349 IPython statements (magics, shell escapes) are not supported (yet).
3350
3350
3351 See also
3351 See also
3352 --------
3352 --------
3353 cpaste: manually paste code into terminal until you mark its end.
3353 cpaste: manually paste code into terminal until you mark its end.
3354 """
3354 """
3355 opts,args = self.parse_options(parameter_s,'rq',mode='string')
3355 opts,args = self.parse_options(parameter_s,'rq',mode='string')
3356 par = args.strip()
3356 par = args.strip()
3357 if opts.has_key('r'):
3357 if opts.has_key('r'):
3358 self._rerun_pasted()
3358 self._rerun_pasted()
3359 return
3359 return
3360
3360
3361 text = self.shell.hooks.clipboard_get()
3361 text = self.shell.hooks.clipboard_get()
3362 block = self._strip_pasted_lines_for_code(text.splitlines())
3362 block = self._strip_pasted_lines_for_code(text.splitlines())
3363
3363
3364 # By default, echo back to terminal unless quiet mode is requested
3364 # By default, echo back to terminal unless quiet mode is requested
3365 if not opts.has_key('q'):
3365 if not opts.has_key('q'):
3366 write = self.shell.write
3366 write = self.shell.write
3367 write(block)
3367 write(block)
3368 if not block.endswith('\n'):
3368 if not block.endswith('\n'):
3369 write('\n')
3369 write('\n')
3370 write("## -- End pasted text --\n")
3370 write("## -- End pasted text --\n")
3371
3371
3372 self._execute_block(block, par)
3372 self._execute_block(block, par)
3373
3373
3374 def magic_quickref(self,arg):
3374 def magic_quickref(self,arg):
3375 """ Show a quick reference sheet """
3375 """ Show a quick reference sheet """
3376 import IPython.core.usage
3376 import IPython.core.usage
3377 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3377 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3378
3378
3379 page(qr)
3379 page(qr)
3380
3380
3381 def magic_upgrade(self,arg):
3381 def magic_upgrade(self,arg):
3382 """ Upgrade your IPython installation
3382 """ Upgrade your IPython installation
3383
3383
3384 This will copy the config files that don't yet exist in your
3384 This will copy the config files that don't yet exist in your
3385 ipython dir from the system config dir. Use this after upgrading
3385 ipython dir from the system config dir. Use this after upgrading
3386 IPython if you don't wish to delete your .ipython dir.
3386 IPython if you don't wish to delete your .ipython dir.
3387
3387
3388 Call with -nolegacy to get rid of ipythonrc* files (recommended for
3388 Call with -nolegacy to get rid of ipythonrc* files (recommended for
3389 new users)
3389 new users)
3390
3390
3391 """
3391 """
3392 ip = self.getapi()
3392 ip = self.getapi()
3393 ipinstallation = path(IPython.__file__).dirname()
3393 ipinstallation = path(IPython.__file__).dirname()
3394 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'utils' / 'upgradedir.py')
3394 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'utils' / 'upgradedir.py')
3395 src_config = ipinstallation / 'config' / 'userconfig'
3395 src_config = ipinstallation / 'config' / 'userconfig'
3396 userdir = path(ip.config.IPYTHONDIR)
3396 userdir = path(ip.config.IPYTHONDIR)
3397 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
3397 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
3398 print ">",cmd
3398 print ">",cmd
3399 shell(cmd)
3399 shell(cmd)
3400 if arg == '-nolegacy':
3400 if arg == '-nolegacy':
3401 legacy = userdir.files('ipythonrc*')
3401 legacy = userdir.files('ipythonrc*')
3402 print "Nuking legacy files:",legacy
3402 print "Nuking legacy files:",legacy
3403
3403
3404 [p.remove() for p in legacy]
3404 [p.remove() for p in legacy]
3405 suffix = (sys.platform == 'win32' and '.ini' or '')
3405 suffix = (sys.platform == 'win32' and '.ini' or '')
3406 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
3406 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
3407
3407
3408
3408
3409 def magic_doctest_mode(self,parameter_s=''):
3409 def magic_doctest_mode(self,parameter_s=''):
3410 """Toggle doctest mode on and off.
3410 """Toggle doctest mode on and off.
3411
3411
3412 This mode allows you to toggle the prompt behavior between normal
3412 This mode allows you to toggle the prompt behavior between normal
3413 IPython prompts and ones that are as similar to the default IPython
3413 IPython prompts and ones that are as similar to the default IPython
3414 interpreter as possible.
3414 interpreter as possible.
3415
3415
3416 It also supports the pasting of code snippets that have leading '>>>'
3416 It also supports the pasting of code snippets that have leading '>>>'
3417 and '...' prompts in them. This means that you can paste doctests from
3417 and '...' prompts in them. This means that you can paste doctests from
3418 files or docstrings (even if they have leading whitespace), and the
3418 files or docstrings (even if they have leading whitespace), and the
3419 code will execute correctly. You can then use '%history -tn' to see
3419 code will execute correctly. You can then use '%history -tn' to see
3420 the translated history without line numbers; this will give you the
3420 the translated history without line numbers; this will give you the
3421 input after removal of all the leading prompts and whitespace, which
3421 input after removal of all the leading prompts and whitespace, which
3422 can be pasted back into an editor.
3422 can be pasted back into an editor.
3423
3423
3424 With these features, you can switch into this mode easily whenever you
3424 With these features, you can switch into this mode easily whenever you
3425 need to do testing and changes to doctests, without having to leave
3425 need to do testing and changes to doctests, without having to leave
3426 your existing IPython session.
3426 your existing IPython session.
3427 """
3427 """
3428
3428
3429 # XXX - Fix this to have cleaner activate/deactivate calls.
3429 # XXX - Fix this to have cleaner activate/deactivate calls.
3430 from IPython.extensions import InterpreterPasteInput as ipaste
3430 from IPython.extensions import InterpreterPasteInput as ipaste
3431 from IPython.utils.ipstruct import Struct
3431 from IPython.utils.ipstruct import Struct
3432
3432
3433 # Shorthands
3433 # Shorthands
3434 shell = self.shell
3434 shell = self.shell
3435 oc = shell.outputcache
3435 oc = shell.outputcache
3436 meta = shell.meta
3436 meta = shell.meta
3437 # dstore is a data store kept in the instance metadata bag to track any
3437 # dstore is a data store kept in the instance metadata bag to track any
3438 # changes we make, so we can undo them later.
3438 # changes we make, so we can undo them later.
3439 dstore = meta.setdefault('doctest_mode',Struct())
3439 dstore = meta.setdefault('doctest_mode',Struct())
3440 save_dstore = dstore.setdefault
3440 save_dstore = dstore.setdefault
3441
3441
3442 # save a few values we'll need to recover later
3442 # save a few values we'll need to recover later
3443 mode = save_dstore('mode',False)
3443 mode = save_dstore('mode',False)
3444 save_dstore('rc_pprint',shell.pprint)
3444 save_dstore('rc_pprint',shell.pprint)
3445 save_dstore('xmode',shell.InteractiveTB.mode)
3445 save_dstore('xmode',shell.InteractiveTB.mode)
3446 save_dstore('rc_separate_out',shell.separate_out)
3446 save_dstore('rc_separate_out',shell.separate_out)
3447 save_dstore('rc_separate_out2',shell.separate_out2)
3447 save_dstore('rc_separate_out2',shell.separate_out2)
3448 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3448 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3449 save_dstore('rc_separate_in',shell.separate_in)
3449 save_dstore('rc_separate_in',shell.separate_in)
3450
3450
3451 if mode == False:
3451 if mode == False:
3452 # turn on
3452 # turn on
3453 ipaste.activate_prefilter()
3453 ipaste.activate_prefilter()
3454
3454
3455 oc.prompt1.p_template = '>>> '
3455 oc.prompt1.p_template = '>>> '
3456 oc.prompt2.p_template = '... '
3456 oc.prompt2.p_template = '... '
3457 oc.prompt_out.p_template = ''
3457 oc.prompt_out.p_template = ''
3458
3458
3459 # Prompt separators like plain python
3459 # Prompt separators like plain python
3460 oc.input_sep = oc.prompt1.sep = ''
3460 oc.input_sep = oc.prompt1.sep = ''
3461 oc.output_sep = ''
3461 oc.output_sep = ''
3462 oc.output_sep2 = ''
3462 oc.output_sep2 = ''
3463
3463
3464 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3464 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3465 oc.prompt_out.pad_left = False
3465 oc.prompt_out.pad_left = False
3466
3466
3467 shell.pprint = False
3467 shell.pprint = False
3468
3468
3469 shell.magic_xmode('Plain')
3469 shell.magic_xmode('Plain')
3470
3470
3471 else:
3471 else:
3472 # turn off
3472 # turn off
3473 ipaste.deactivate_prefilter()
3473 ipaste.deactivate_prefilter()
3474
3474
3475 oc.prompt1.p_template = shell.prompt_in1
3475 oc.prompt1.p_template = shell.prompt_in1
3476 oc.prompt2.p_template = shell.prompt_in2
3476 oc.prompt2.p_template = shell.prompt_in2
3477 oc.prompt_out.p_template = shell.prompt_out
3477 oc.prompt_out.p_template = shell.prompt_out
3478
3478
3479 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3479 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3480
3480
3481 oc.output_sep = dstore.rc_separate_out
3481 oc.output_sep = dstore.rc_separate_out
3482 oc.output_sep2 = dstore.rc_separate_out2
3482 oc.output_sep2 = dstore.rc_separate_out2
3483
3483
3484 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3484 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3485 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3485 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3486
3486
3487 rc.pprint = dstore.rc_pprint
3487 rc.pprint = dstore.rc_pprint
3488
3488
3489 shell.magic_xmode(dstore.xmode)
3489 shell.magic_xmode(dstore.xmode)
3490
3490
3491 # Store new mode and inform
3491 # Store new mode and inform
3492 dstore.mode = bool(1-int(mode))
3492 dstore.mode = bool(1-int(mode))
3493 print 'Doctest mode is:',
3493 print 'Doctest mode is:',
3494 print ['OFF','ON'][dstore.mode]
3494 print ['OFF','ON'][dstore.mode]
3495
3495
3496 def magic_gui(self, parameter_s=''):
3496 def magic_gui(self, parameter_s=''):
3497 """Enable or disable IPython GUI event loop integration.
3497 """Enable or disable IPython GUI event loop integration.
3498
3498
3499 %gui [-a] [GUINAME]
3499 %gui [-a] [GUINAME]
3500
3500
3501 This magic replaces IPython's threaded shells that were activated
3501 This magic replaces IPython's threaded shells that were activated
3502 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3502 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3503 can now be enabled, disabled and swtiched at runtime and keyboard
3503 can now be enabled, disabled and swtiched at runtime and keyboard
3504 interrupts should work without any problems. The following toolkits
3504 interrupts should work without any problems. The following toolkits
3505 are supports: wxPython, PyQt4, PyGTK, and Tk::
3505 are supports: wxPython, PyQt4, PyGTK, and Tk::
3506
3506
3507 %gui wx # enable wxPython event loop integration
3507 %gui wx # enable wxPython event loop integration
3508 %gui qt4|qt # enable PyQt4 event loop integration
3508 %gui qt4|qt # enable PyQt4 event loop integration
3509 %gui gtk # enable PyGTK event loop integration
3509 %gui gtk # enable PyGTK event loop integration
3510 %gui tk # enable Tk event loop integration
3510 %gui tk # enable Tk event loop integration
3511 %gui # disable all event loop integration
3511 %gui # disable all event loop integration
3512
3512
3513 WARNING: after any of these has been called you can simply create
3513 WARNING: after any of these has been called you can simply create
3514 an application object, but DO NOT start the event loop yourself, as
3514 an application object, but DO NOT start the event loop yourself, as
3515 we have already handled that.
3515 we have already handled that.
3516
3516
3517 If you want us to create an appropriate application object add the
3517 If you want us to create an appropriate application object add the
3518 "-a" flag to your command::
3518 "-a" flag to your command::
3519
3519
3520 %gui -a wx
3520 %gui -a wx
3521
3521
3522 This is highly recommended for most users.
3522 This is highly recommended for most users.
3523 """
3523 """
3524 from IPython.lib import inputhook
3524 from IPython.lib import inputhook
3525 if "-a" in parameter_s:
3525 if "-a" in parameter_s:
3526 app = True
3526 app = True
3527 else:
3527 else:
3528 app = False
3528 app = False
3529 if not parameter_s:
3529 if not parameter_s:
3530 inputhook.clear_inputhook()
3530 inputhook.clear_inputhook()
3531 elif 'wx' in parameter_s:
3531 elif 'wx' in parameter_s:
3532 return inputhook.enable_wx(app)
3532 return inputhook.enable_wx(app)
3533 elif ('qt4' in parameter_s) or ('qt' in parameter_s):
3533 elif ('qt4' in parameter_s) or ('qt' in parameter_s):
3534 return inputhook.enable_qt4(app)
3534 return inputhook.enable_qt4(app)
3535 elif 'gtk' in parameter_s:
3535 elif 'gtk' in parameter_s:
3536 return inputhook.enable_gtk(app)
3536 return inputhook.enable_gtk(app)
3537 elif 'tk' in parameter_s:
3537 elif 'tk' in parameter_s:
3538 return inputhook.enable_tk(app)
3538 return inputhook.enable_tk(app)
3539
3539
3540 def magic_load_ext(self, module_str):
3541 """Load an IPython extension by its module name."""
3542 self.load_extension(module_str)
3543
3544 def magic_unload_ext(self, module_str):
3545 """Unload an IPython extension by its module name."""
3546 self.unload_extension(module_str)
3547
3548 def magic_reload_ext(self, module_str):
3549 """Reload an IPython extension by its module name."""
3550 self.reload_extension(module_str)
3540
3551
3541 # end Magic
3552 # end Magic
@@ -1,192 +1,192 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 #
2 #
3 # IPython documentation build configuration file.
3 # IPython documentation build configuration file.
4
4
5 # NOTE: This file has been edited manually from the auto-generated one from
5 # NOTE: This file has been edited manually from the auto-generated one from
6 # sphinx. Do NOT delete and re-generate. If any changes from sphinx are
6 # sphinx. Do NOT delete and re-generate. If any changes from sphinx are
7 # needed, generate a scratch one and merge by hand any new fields needed.
7 # needed, generate a scratch one and merge by hand any new fields needed.
8
8
9 #
9 #
10 # This file is execfile()d with the current directory set to its containing dir.
10 # This file is execfile()d with the current directory set to its containing dir.
11 #
11 #
12 # The contents of this file are pickled, so don't put values in the namespace
12 # The contents of this file are pickled, so don't put values in the namespace
13 # that aren't pickleable (module imports are okay, they're removed automatically).
13 # that aren't pickleable (module imports are okay, they're removed automatically).
14 #
14 #
15 # All configuration values have a default value; values that are commented out
15 # All configuration values have a default value; values that are commented out
16 # serve to show the default value.
16 # serve to show the default value.
17
17
18 import sys, os
18 import sys, os
19
19
20 # If your extensions are in another directory, add it here. If the directory
20 # If your extensions are in another directory, add it here. If the directory
21 # is relative to the documentation root, use os.path.abspath to make it
21 # is relative to the documentation root, use os.path.abspath to make it
22 # absolute, like shown here.
22 # absolute, like shown here.
23 sys.path.append(os.path.abspath('../sphinxext'))
23 sys.path.append(os.path.abspath('../sphinxext'))
24
24
25 # Import support for ipython console session syntax highlighting (lives
25 # Import support for ipython console session syntax highlighting (lives
26 # in the sphinxext directory defined above)
26 # in the sphinxext directory defined above)
27 import ipython_console_highlighting
27 import ipython_console_highlighting
28
28
29 # We load the ipython release info into a dict by explicit execution
29 # We load the ipython release info into a dict by explicit execution
30 iprelease = {}
30 iprelease = {}
31 execfile('../../IPython/core/release.py',iprelease)
31 execfile('../../IPython/core/release.py',iprelease)
32
32
33 # General configuration
33 # General configuration
34 # ---------------------
34 # ---------------------
35
35
36 # Add any Sphinx extension module names here, as strings. They can be extensions
36 # Add any Sphinx extension module names here, as strings. They can be extensions
37 # coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
37 # coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
38 extensions = [
38 extensions = [
39 # 'matplotlib.sphinxext.mathmpl',
39 # 'matplotlib.sphinxext.mathmpl',
40 'matplotlib.sphinxext.only_directives',
40 'matplotlib.sphinxext.only_directives',
41 # 'matplotlib.sphinxext.plot_directive',
41 # 'matplotlib.sphinxext.plot_directive',
42 'sphinx.ext.autodoc',
42 'sphinx.ext.autodoc',
43 'sphinx.ext.doctest',
43 'sphinx.ext.doctest',
44 'inheritance_diagram',
44 'inheritance_diagram',
45 'ipython_console_highlighting',
45 'ipython_console_highlighting',
46 'numpydoc', # to preprocess docstrings
46 'numpydoc', # to preprocess docstrings
47 ]
47 ]
48
48
49 # Add any paths that contain templates here, relative to this directory.
49 # Add any paths that contain templates here, relative to this directory.
50 templates_path = ['_templates']
50 templates_path = ['_templates']
51
51
52 # The suffix of source filenames.
52 # The suffix of source filenames.
53 source_suffix = '.txt'
53 source_suffix = '.txt'
54
54
55 # The master toctree document.
55 # The master toctree document.
56 master_doc = 'index'
56 master_doc = 'index'
57
57
58 # General substitutions.
58 # General substitutions.
59 project = 'IPython'
59 project = 'IPython'
60 copyright = '2008, The IPython Development Team'
60 copyright = '2008, The IPython Development Team'
61
61
62 # The default replacements for |version| and |release|, also used in various
62 # The default replacements for |version| and |release|, also used in various
63 # other places throughout the built documents.
63 # other places throughout the built documents.
64 #
64 #
65 # The full version, including alpha/beta/rc tags.
65 # The full version, including alpha/beta/rc tags.
66 release = iprelease['version']
66 release = iprelease['version']
67 # The short X.Y version.
67 # The short X.Y version.
68 version = '.'.join(release.split('.',2)[:2])
68 version = '.'.join(release.split('.',2)[:2])
69
69
70
70
71 # There are two options for replacing |today|: either, you set today to some
71 # There are two options for replacing |today|: either, you set today to some
72 # non-false value, then it is used:
72 # non-false value, then it is used:
73 #today = ''
73 #today = ''
74 # Else, today_fmt is used as the format for a strftime call.
74 # Else, today_fmt is used as the format for a strftime call.
75 today_fmt = '%B %d, %Y'
75 today_fmt = '%B %d, %Y'
76
76
77 # List of documents that shouldn't be included in the build.
77 # List of documents that shouldn't be included in the build.
78 #unused_docs = []
78 #unused_docs = []
79
79
80 # List of directories, relative to source directories, that shouldn't be searched
80 # List of directories, relative to source directories, that shouldn't be searched
81 # for source files.
81 # for source files.
82 exclude_dirs = ['attic']
82 exclude_dirs = ['attic']
83
83
84 # If true, '()' will be appended to :func: etc. cross-reference text.
84 # If true, '()' will be appended to :func: etc. cross-reference text.
85 #add_function_parentheses = True
85 #add_function_parentheses = True
86
86
87 # If true, the current module name will be prepended to all description
87 # If true, the current module name will be prepended to all description
88 # unit titles (such as .. function::).
88 # unit titles (such as .. function::).
89 #add_module_names = True
89 #add_module_names = True
90
90
91 # If true, sectionauthor and moduleauthor directives will be shown in the
91 # If true, sectionauthor and moduleauthor directives will be shown in the
92 # output. They are ignored by default.
92 # output. They are ignored by default.
93 #show_authors = False
93 #show_authors = False
94
94
95 # The name of the Pygments (syntax highlighting) style to use.
95 # The name of the Pygments (syntax highlighting) style to use.
96 pygments_style = 'sphinx'
96 pygments_style = 'sphinx'
97
97
98
98
99 # Options for HTML output
99 # Options for HTML output
100 # -----------------------
100 # -----------------------
101
101
102 # The style sheet to use for HTML and HTML Help pages. A file of that name
102 # The style sheet to use for HTML and HTML Help pages. A file of that name
103 # must exist either in Sphinx' static/ path, or in one of the custom paths
103 # must exist either in Sphinx' static/ path, or in one of the custom paths
104 # given in html_static_path.
104 # given in html_static_path.
105 html_style = 'default.css'
105 html_style = 'default.css'
106
106
107 # The name for this set of Sphinx documents. If None, it defaults to
107 # The name for this set of Sphinx documents. If None, it defaults to
108 # "<project> v<release> documentation".
108 # "<project> v<release> documentation".
109 #html_title = None
109 #html_title = None
110
110
111 # The name of an image file (within the static path) to place at the top of
111 # The name of an image file (within the static path) to place at the top of
112 # the sidebar.
112 # the sidebar.
113 #html_logo = None
113 #html_logo = None
114
114
115 # Add any paths that contain custom static files (such as style sheets) here,
115 # Add any paths that contain custom static files (such as style sheets) here,
116 # relative to this directory. They are copied after the builtin static files,
116 # relative to this directory. They are copied after the builtin static files,
117 # so a file named "default.css" will overwrite the builtin "default.css".
117 # so a file named "default.css" will overwrite the builtin "default.css".
118 html_static_path = ['_static']
118 html_static_path = ['_static']
119
119
120 # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
120 # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
121 # using the given strftime format.
121 # using the given strftime format.
122 html_last_updated_fmt = '%b %d, %Y'
122 html_last_updated_fmt = '%b %d, %Y'
123
123
124 # If true, SmartyPants will be used to convert quotes and dashes to
124 # If true, SmartyPants will be used to convert quotes and dashes to
125 # typographically correct entities.
125 # typographically correct entities.
126 #html_use_smartypants = True
126 #html_use_smartypants = True
127
127
128 # Custom sidebar templates, maps document names to template names.
128 # Custom sidebar templates, maps document names to template names.
129 #html_sidebars = {}
129 #html_sidebars = {}
130
130
131 # Additional templates that should be rendered to pages, maps page names to
131 # Additional templates that should be rendered to pages, maps page names to
132 # template names.
132 # template names.
133 #html_additional_pages = {}
133 #html_additional_pages = {}
134
134
135 # If false, no module index is generated.
135 # If false, no module index is generated.
136 #html_use_modindex = True
136 #html_use_modindex = True
137
137
138 # If true, the reST sources are included in the HTML build as _sources/<name>.
138 # If true, the reST sources are included in the HTML build as _sources/<name>.
139 #html_copy_source = True
139 #html_copy_source = True
140
140
141 # If true, an OpenSearch description file will be output, and all pages will
141 # If true, an OpenSearch description file will be output, and all pages will
142 # contain a <link> tag referring to it. The value of this option must be the
142 # contain a <link> tag referring to it. The value of this option must be the
143 # base URL from which the finished HTML is served.
143 # base URL from which the finished HTML is served.
144 #html_use_opensearch = ''
144 #html_use_opensearch = ''
145
145
146 # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
146 # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
147 #html_file_suffix = ''
147 #html_file_suffix = ''
148
148
149 # Output file base name for HTML help builder.
149 # Output file base name for HTML help builder.
150 htmlhelp_basename = 'ipythondoc'
150 htmlhelp_basename = 'ipythondoc'
151
151
152
152
153 # Options for LaTeX output
153 # Options for LaTeX output
154 # ------------------------
154 # ------------------------
155
155
156 # The paper size ('letter' or 'a4').
156 # The paper size ('letter' or 'a4').
157 latex_paper_size = 'letter'
157 latex_paper_size = 'letter'
158
158
159 # The font size ('10pt', '11pt' or '12pt').
159 # The font size ('10pt', '11pt' or '12pt').
160 latex_font_size = '11pt'
160 latex_font_size = '11pt'
161
161
162 # Grouping the document tree into LaTeX files. List of tuples
162 # Grouping the document tree into LaTeX files. List of tuples
163 # (source start file, target name, title, author, document class [howto/manual]).
163 # (source start file, target name, title, author, document class [howto/manual]).
164
164
165 latex_documents = [ ('index', 'ipython.tex', 'IPython Documentation',
165 latex_documents = [ ('index', 'ipython.tex', 'IPython Documentation',
166 ur"""The IPython Development Team""",
166 ur"""The IPython Development Team""",
167 'manual'),
167 'manual', True),
168 ]
168 ]
169
169
170 # The name of an image file (relative to this directory) to place at the top of
170 # The name of an image file (relative to this directory) to place at the top of
171 # the title page.
171 # the title page.
172 #latex_logo = None
172 #latex_logo = None
173
173
174 # For "manual" documents, if this is true, then toplevel headings are parts,
174 # For "manual" documents, if this is true, then toplevel headings are parts,
175 # not chapters.
175 # not chapters.
176 #latex_use_parts = False
176 #latex_use_parts = False
177
177
178 # Additional stuff for the LaTeX preamble.
178 # Additional stuff for the LaTeX preamble.
179 #latex_preamble = ''
179 #latex_preamble = ''
180
180
181 # Documents to append as an appendix to all manuals.
181 # Documents to append as an appendix to all manuals.
182 #latex_appendices = []
182 #latex_appendices = []
183
183
184 # If false, no module index is generated.
184 # If false, no module index is generated.
185 #latex_use_modindex = True
185 #latex_use_modindex = True
186
186
187
187
188 # Cleanup
188 # Cleanup
189 # -------
189 # -------
190 # delete release info to avoid pickling errors from sphinx
190 # delete release info to avoid pickling errors from sphinx
191
191
192 del iprelease
192 del iprelease
@@ -1,134 +1,136 b''
1 .. _configuring_ipython:
1 .. _configuring_ipython:
2
2
3 ===========================================================
3 ===========================================================
4 Configuring the :command:`ipython` command line application
4 Configuring the :command:`ipython` command line application
5 ===========================================================
5 ===========================================================
6
6
7 This section contains information about how to configure the
7 This section contains information about how to configure the
8 :command:`ipython` command line application. See the :ref:`configuration
8 :command:`ipython` command line application. See the :ref:`configuration
9 overview <config_overview>` for a more general description of the
9 overview <config_overview>` for a more general description of the
10 configuration system and configuration file format.
10 configuration system and configuration file format.
11
11
12 The default configuration file for the :command:`ipython` command line application
12 The default configuration file for the :command:`ipython` command line application
13 is :file:`ipython_config.py`. By setting the attributes in this file, you
13 is :file:`ipython_config.py`. By setting the attributes in this file, you
14 can configure the application. A sample is provided in
14 can configure the application. A sample is provided in
15 :mod:`IPython.config.default.ipython_config`. Simply copy this file to your
15 :mod:`IPython.config.default.ipython_config`. Simply copy this file to your
16 IPython directory to start using it.
16 IPython directory to start using it.
17
17
18 Most configuration attributes that this file accepts are associated with
18 Most configuration attributes that this file accepts are associated with
19 classes that are subclasses of :class:`~IPython.core.component.Component`.
19 classes that are subclasses of :class:`~IPython.core.component.Component`.
20
20
21 A few configuration attributes are not associated with a particular
21 A few configuration attributes are not associated with a particular
22 :class:`~IPython.core.component.Component` subclass. These are application
22 :class:`~IPython.core.component.Component` subclass. These are application
23 wide configuration attributes and are stored in the ``Global``
23 wide configuration attributes and are stored in the ``Global``
24 sub-configuration section. We begin with a description of these
24 sub-configuration section. We begin with a description of these
25 attributes.
25 attributes.
26
26
27 Global configuration
27 Global configuration
28 ====================
28 ====================
29
29
30 Assuming that your configuration file has the following at the top::
30 Assuming that your configuration file has the following at the top::
31
31
32 c = get_config()
32 c = get_config()
33
33
34 the following attributes can be set in the ``Global`` section.
34 the following attributes can be set in the ``Global`` section.
35
35
36 :attr:`c.Global.display_banner`
36 :attr:`c.Global.display_banner`
37 A boolean that determined if the banner is printer when :command:`ipython`
37 A boolean that determined if the banner is printer when :command:`ipython`
38 is started.
38 is started.
39
39
40 :attr:`c.Global.classic`
40 :attr:`c.Global.classic`
41 A boolean that determines if IPython starts in "classic" mode. In this
41 A boolean that determines if IPython starts in "classic" mode. In this
42 mode, the prompts and everything mimic that of the normal :command:`python`
42 mode, the prompts and everything mimic that of the normal :command:`python`
43 shell
43 shell
44
44
45 :attr:`c.Global.nosep`
45 :attr:`c.Global.nosep`
46 A boolean that determines if there should be no blank lines between
46 A boolean that determines if there should be no blank lines between
47 prompts.
47 prompts.
48
48
49 :attr:`c.Global.log_level`
49 :attr:`c.Global.log_level`
50 An integer that sets the detail of the logging level during the startup
50 An integer that sets the detail of the logging level during the startup
51 of :command:`ipython`. The default is 30 and the possible values are
51 of :command:`ipython`. The default is 30 and the possible values are
52 (0, 10, 20, 30, 40, 50). Higher is quieter and lower is more verbose.
52 (0, 10, 20, 30, 40, 50). Higher is quieter and lower is more verbose.
53
53
54 :attr:`c.Global.extensions`
54 :attr:`c.Global.extensions`
55 A list of strings, each of which is an importable IPython extension. An
55 A list of strings, each of which is an importable IPython extension. An
56 IPython extension is a regular Python module or package that has a
56 IPython extension is a regular Python module or package that has a
57 :func:`load_in_ipython(ip)` method. This method gets called when the
57 :func:`load_ipython_extension(ip)` method. This method gets called when
58 extension is loaded with the currently running
58 the extension is loaded with the currently running
59 :class:`~IPython.core.iplib.InteractiveShell` as its only argument. You
59 :class:`~IPython.core.iplib.InteractiveShell` as its only argument. You
60 can put your extensions anywhere they can be imported but we add the
60 can put your extensions anywhere they can be imported but we add the
61 :file:`extensions` subdirectory of the ipython directory to ``sys.path``
61 :file:`extensions` subdirectory of the ipython directory to ``sys.path``
62 during extension loading, so you can put them there as well. Extensions
62 during extension loading, so you can put them there as well. Extensions
63 are not executed in the user's interactive namespace and they must
63 are not executed in the user's interactive namespace and they must be pure
64 be pure Python code. Extensions are the recommended way of customizing
64 Python code. Extensions are the recommended way of customizing
65 :command:`ipython`.
65 :command:`ipython`. Extensions can provide an
66 :func:`unload_ipython_extension` that will be called when the extension is
67 unloaded.
66
68
67 :attr:`c.Global.exec_lines`
69 :attr:`c.Global.exec_lines`
68 A list of strings, each of which is Python code that is run in the user's
70 A list of strings, each of which is Python code that is run in the user's
69 namespace after IPython start. These lines can contain full IPython syntax
71 namespace after IPython start. These lines can contain full IPython syntax
70 with magics, etc.
72 with magics, etc.
71
73
72 :attr:`c.Global.exec_files`
74 :attr:`c.Global.exec_files`
73 A list of strings, each of which is the full pathname of a ``.py`` or
75 A list of strings, each of which is the full pathname of a ``.py`` or
74 ``.ipy`` file that will be executed as IPython starts. These files are run
76 ``.ipy`` file that will be executed as IPython starts. These files are run
75 in IPython in the user's namespace. Files with a ``.py`` extension need to
77 in IPython in the user's namespace. Files with a ``.py`` extension need to
76 be pure Python. Files with a ``.ipy`` extension can have custom IPython
78 be pure Python. Files with a ``.ipy`` extension can have custom IPython
77 syntax (magics, etc.). These files need to be in the cwd, the ipythondir
79 syntax (magics, etc.). These files need to be in the cwd, the ipythondir
78 or be absolute paths.
80 or be absolute paths.
79
81
80 Classes that can be configured
82 Classes that can be configured
81 ==============================
83 ==============================
82
84
83 The following classes can also be configured in the configuration file for
85 The following classes can also be configured in the configuration file for
84 :command:`ipython`:
86 :command:`ipython`:
85
87
86 * :class:`~IPython.core.iplib.InteractiveShell`
88 * :class:`~IPython.core.iplib.InteractiveShell`
87
89
88 * :class:`~IPython.core.prefilter.PrefilterManager`
90 * :class:`~IPython.core.prefilter.PrefilterManager`
89
91
90 * :class:`~IPython.core.alias.AliasManager`
92 * :class:`~IPython.core.alias.AliasManager`
91
93
92 To see which attributes of these classes are configurable, please see the
94 To see which attributes of these classes are configurable, please see the
93 source code for these classes, the class docstrings or the sample
95 source code for these classes, the class docstrings or the sample
94 configuration file :mod:`IPython.config.default.ipython_config`.
96 configuration file :mod:`IPython.config.default.ipython_config`.
95
97
96 Example
98 Example
97 =======
99 =======
98
100
99 For those who want to get a quick start, here is a sample
101 For those who want to get a quick start, here is a sample
100 :file:`ipython_config.py` that sets some of the common configuration
102 :file:`ipython_config.py` that sets some of the common configuration
101 attributes::
103 attributes::
102
104
103 # sample ipython_config.py
105 # sample ipython_config.py
104 c = get_config()
106 c = get_config()
105
107
106 c.Global.display_banner = True
108 c.Global.display_banner = True
107 c.Global.log_level = 20
109 c.Global.log_level = 20
108 c.Global.extensions = [
110 c.Global.extensions = [
109 'myextension'
111 'myextension'
110 ]
112 ]
111 c.Global.exec_lines = [
113 c.Global.exec_lines = [
112 'import numpy',
114 'import numpy',
113 'import scipy'
115 'import scipy'
114 ]
116 ]
115 c.Global.exec_files = [
117 c.Global.exec_files = [
116 'mycode.py',
118 'mycode.py',
117 'fancy.ipy'
119 'fancy.ipy'
118 ]
120 ]
119 c.InteractiveShell.autoindent = True
121 c.InteractiveShell.autoindent = True
120 c.InteractiveShell.colors = 'LightBG'
122 c.InteractiveShell.colors = 'LightBG'
121 c.InteractiveShell.confirm_exit = False
123 c.InteractiveShell.confirm_exit = False
122 c.InteractiveShell.deep_reload = True
124 c.InteractiveShell.deep_reload = True
123 c.InteractiveShell.editor = 'nano'
125 c.InteractiveShell.editor = 'nano'
124 c.InteractiveShell.prompt_in1 = 'In [\#]: '
126 c.InteractiveShell.prompt_in1 = 'In [\#]: '
125 c.InteractiveShell.prompt_in2 = ' .\D.: '
127 c.InteractiveShell.prompt_in2 = ' .\D.: '
126 c.InteractiveShell.prompt_out = 'Out[\#]: '
128 c.InteractiveShell.prompt_out = 'Out[\#]: '
127 c.InteractiveShell.prompts_pad_left = True
129 c.InteractiveShell.prompts_pad_left = True
128 c.InteractiveShell.xmode = 'Context'
130 c.InteractiveShell.xmode = 'Context'
129
131
130 c.PrefilterManager.multi_line_specials = True
132 c.PrefilterManager.multi_line_specials = True
131
133
132 c.AliasManager.user_aliases = [
134 c.AliasManager.user_aliases = [
133 ('la', 'ls -al')
135 ('la', 'ls -al')
134 ] No newline at end of file
136 ]
@@ -1,64 +1,71 b''
1 .. _module_reorg:
1 .. _module_reorg:
2
2
3 ===========================
3 ===========================
4 IPython module organization
4 IPython module organization
5 ===========================
5 ===========================
6
6
7 As of the 0.11 release of IPython, the top-level packages and modules have
7 As of the 0.11 release of IPython, the top-level packages and modules have
8 been completely reorganized. This section describes the purpose of the
8 been completely reorganized. This section describes the purpose of the
9 top-level IPython subpackages.
9 top-level IPython subpackages.
10
10
11 Subpackage descriptions
11 Subpackage descriptions
12 =======================
12 =======================
13
13
14 * :mod:`IPython.config`. This package contains the configuration system of
14 * :mod:`IPython.config`. This package contains the configuration system of
15 IPython, as well as default configuration files for the different IPython
15 IPython, as well as default configuration files for the different IPython
16 applications.
16 applications.
17
17
18 * :mod:`IPython.core`. This sub-package contains the core of the IPython
18 * :mod:`IPython.core`. This sub-package contains the core of the IPython
19 interpreter, but none of its extended capabilities.
19 interpreter, but none of its extended capabilities.
20
20
21 * :mod:`IPython.deathrow`. This is for code that is outdated, untested,
21 * :mod:`IPython.deathrow`. This is for code that is outdated, untested,
22 rotting, or that belongs in a separate third party project. Eventually all
22 rotting, or that belongs in a separate third party project. Eventually all
23 this code will either i) be revived by someone willing to maintain it with
23 this code will either i) be revived by someone willing to maintain it with
24 tests and docs and re-included into IPython or 2) be removed from IPython
24 tests and docs and re-included into IPython or 2) be removed from IPython
25 proper, but put into a separate third-party Python package. No new code will
25 proper, but put into a separate third-party Python package. No new code will
26 be allowed here.
26 be allowed here. If your favorite extension has been moved here please
27 contact the IPython developer mailing list to help us determine the best
28 course of action.
27
29
28 * :mod:`IPython.extensions`. This package contains fully supported IPython
30 * :mod:`IPython.extensions`. This package contains fully supported IPython
29 extensions. These extensions adhere to the official IPython extension API
31 extensions. These extensions adhere to the official IPython extension API
30 and can be enabled by adding them to a field in the configuration file.
32 and can be enabled by adding them to a field in the configuration file.
33 If your extension is no longer in this location, please look in
34 :mod:`IPython.quarantine` and :mod:`IPython.deathrow` and contact the
35 IPython developer mailing list.
31
36
32 * :mod:`IPython.external`. This package contains third party packages and
37 * :mod:`IPython.external`. This package contains third party packages and
33 modules that IPython ships internally to reduce the number of dependencies.
38 modules that IPython ships internally to reduce the number of dependencies.
34 Usually, these are short, single file modules.
39 Usually, these are short, single file modules.
35
40
36 * :mod:`IPython.frontend`. This package contains the various IPython
41 * :mod:`IPython.frontend`. This package contains the various IPython
37 frontends. Currently, the code in this subpackage is very experimental and
42 frontends. Currently, the code in this subpackage is very experimental and
38 may be broken.
43 may be broken.
39
44
40 * :mod:`IPython.gui`. Another semi-experimental wxPython based IPython GUI.
45 * :mod:`IPython.gui`. Another semi-experimental wxPython based IPython GUI.
41
46
42 * :mod:`IPython.kernel`. This contains IPython's parallel computing system.
47 * :mod:`IPython.kernel`. This contains IPython's parallel computing system.
43
48
44 * :mod:`IPython.lib`. IPython has many extended capabilities that are not part
49 * :mod:`IPython.lib`. IPython has many extended capabilities that are not part
45 of the IPython core. These things will go here and in. Modules in this
50 of the IPython core. These things will go here and in. Modules in this
46 package are similar to extensions, but don't adhere to the official
51 package are similar to extensions, but don't adhere to the official
47 IPython extension API.
52 IPython extension API.
48
53
49 * :mod:`IPython.quarantine`. This is for code that doesn't meet IPython's
54 * :mod:`IPython.quarantine`. This is for code that doesn't meet IPython's
50 standards, but that we plan on keeping. To be moved out of this sub-package
55 standards, but that we plan on keeping. To be moved out of this sub-package
51 a module needs to have approval of the core IPython developers, tests and
56 a module needs to have approval of the core IPython developers, tests and
52 documentation.
57 documentation. If your favorite extension has been moved here please contact
58 the IPython developer mailing list to help us determine the best course of
59 action.
53
60
54 * :mod:`IPython.scripts`. This package contains a variety of top-level
61 * :mod:`IPython.scripts`. This package contains a variety of top-level
55 command line scripts. Eventually, these should be moved to the
62 command line scripts. Eventually, these should be moved to the
56 :file:`scripts` subdirectory of the appropriate IPython subpackage.
63 :file:`scripts` subdirectory of the appropriate IPython subpackage.
57
64
58 * :mod:`IPython.utils`. This sub-package will contain anything that might
65 * :mod:`IPython.utils`. This sub-package will contain anything that might
59 eventually be found in the Python standard library, like things in
66 eventually be found in the Python standard library, like things in
60 :mod:`genutils`. Each sub-module in this sub-package should contain
67 :mod:`genutils`. Each sub-module in this sub-package should contain
61 functions and classes that serve a single purpose and that don't
68 functions and classes that serve a single purpose and that don't
62 depend on things in the rest of IPython.
69 depend on things in the rest of IPython.
63
70
64
71
@@ -1,178 +1,182 b''
1 .. _parallelmpi:
1 .. _parallelmpi:
2
2
3 =======================
3 =======================
4 Using MPI with IPython
4 Using MPI with IPython
5 =======================
5 =======================
6
6
7 Often, a parallel algorithm will require moving data between the engines. One
7 Often, a parallel algorithm will require moving data between the engines. One
8 way of accomplishing this is by doing a pull and then a push using the
8 way of accomplishing this is by doing a pull and then a push using the
9 multiengine client. However, this will be slow as all the data has to go
9 multiengine client. However, this will be slow as all the data has to go
10 through the controller to the client and then back through the controller, to
10 through the controller to the client and then back through the controller, to
11 its final destination.
11 its final destination.
12
12
13 A much better way of moving data between engines is to use a message passing
13 A much better way of moving data between engines is to use a message passing
14 library, such as the Message Passing Interface (MPI) [MPI]_. IPython's
14 library, such as the Message Passing Interface (MPI) [MPI]_. IPython's
15 parallel computing architecture has been designed from the ground up to
15 parallel computing architecture has been designed from the ground up to
16 integrate with MPI. This document describes how to use MPI with IPython.
16 integrate with MPI. This document describes how to use MPI with IPython.
17
17
18 Additional installation requirements
18 Additional installation requirements
19 ====================================
19 ====================================
20
20
21 If you want to use MPI with IPython, you will need to install:
21 If you want to use MPI with IPython, you will need to install:
22
22
23 * A standard MPI implementation such as OpenMPI [OpenMPI]_ or MPICH.
23 * A standard MPI implementation such as OpenMPI [OpenMPI]_ or MPICH.
24 * The mpi4py [mpi4py]_ package.
24 * The mpi4py [mpi4py]_ package.
25
25
26 .. note::
26 .. note::
27
27
28 The mpi4py package is not a strict requirement. However, you need to
28 The mpi4py package is not a strict requirement. However, you need to
29 have *some* way of calling MPI from Python. You also need some way of
29 have *some* way of calling MPI from Python. You also need some way of
30 making sure that :func:`MPI_Init` is called when the IPython engines start
30 making sure that :func:`MPI_Init` is called when the IPython engines start
31 up. There are a number of ways of doing this and a good number of
31 up. There are a number of ways of doing this and a good number of
32 associated subtleties. We highly recommend just using mpi4py as it
32 associated subtleties. We highly recommend just using mpi4py as it
33 takes care of most of these problems. If you want to do something
33 takes care of most of these problems. If you want to do something
34 different, let us know and we can help you get started.
34 different, let us know and we can help you get started.
35
35
36 Starting the engines with MPI enabled
36 Starting the engines with MPI enabled
37 =====================================
37 =====================================
38
38
39 To use code that calls MPI, there are typically two things that MPI requires.
39 To use code that calls MPI, there are typically two things that MPI requires.
40
40
41 1. The process that wants to call MPI must be started using
41 1. The process that wants to call MPI must be started using
42 :command:`mpiexec` or a batch system (like PBS) that has MPI support.
42 :command:`mpiexec` or a batch system (like PBS) that has MPI support.
43 2. Once the process starts, it must call :func:`MPI_Init`.
43 2. Once the process starts, it must call :func:`MPI_Init`.
44
44
45 There are a couple of ways that you can start the IPython engines and get
45 There are a couple of ways that you can start the IPython engines and get
46 these things to happen.
46 these things to happen.
47
47
48 Automatic starting using :command:`mpiexec` and :command:`ipcluster`
48 Automatic starting using :command:`mpiexec` and :command:`ipcluster`
49 --------------------------------------------------------------------
49 --------------------------------------------------------------------
50
50
51 The easiest approach is to use the `mpiexec` mode of :command:`ipcluster`,
51 The easiest approach is to use the `mpiexec` mode of :command:`ipcluster`,
52 which will first start a controller and then a set of engines using
52 which will first start a controller and then a set of engines using
53 :command:`mpiexec`::
53 :command:`mpiexec`::
54
54
55 $ ipcluster mpiexec -n 4
55 $ ipcluster mpiexec -n 4
56
56
57 This approach is best as interrupting :command:`ipcluster` will automatically
57 This approach is best as interrupting :command:`ipcluster` will automatically
58 stop and clean up the controller and engines.
58 stop and clean up the controller and engines.
59
59
60 Manual starting using :command:`mpiexec`
60 Manual starting using :command:`mpiexec`
61 ----------------------------------------
61 ----------------------------------------
62
62
63 If you want to start the IPython engines using the :command:`mpiexec`, just
63 If you want to start the IPython engines using the :command:`mpiexec`, just
64 do::
64 do::
65
65
66 $ mpiexec -n 4 ipengine --mpi=mpi4py
66 $ mpiexec -n 4 ipengine --mpi=mpi4py
67
67
68 This requires that you already have a controller running and that the FURL
68 This requires that you already have a controller running and that the FURL
69 files for the engines are in place. We also have built in support for
69 files for the engines are in place. We also have built in support for
70 PyTrilinos [PyTrilinos]_, which can be used (assuming is installed) by
70 PyTrilinos [PyTrilinos]_, which can be used (assuming is installed) by
71 starting the engines with::
71 starting the engines with::
72
72
73 mpiexec -n 4 ipengine --mpi=pytrilinos
73 mpiexec -n 4 ipengine --mpi=pytrilinos
74
74
75 Automatic starting using PBS and :command:`ipcluster`
75 Automatic starting using PBS and :command:`ipcluster`
76 -----------------------------------------------------
76 -----------------------------------------------------
77
77
78 The :command:`ipcluster` command also has built-in integration with PBS. For
78 The :command:`ipcluster` command also has built-in integration with PBS. For
79 more information on this approach, see our documentation on :ref:`ipcluster
79 more information on this approach, see our documentation on :ref:`ipcluster
80 <parallel_process>`.
80 <parallel_process>`.
81
81
82 Actually using MPI
82 Actually using MPI
83 ==================
83 ==================
84
84
85 Once the engines are running with MPI enabled, you are ready to go. You can
85 Once the engines are running with MPI enabled, you are ready to go. You can
86 now call any code that uses MPI in the IPython engines. And, all of this can
86 now call any code that uses MPI in the IPython engines. And, all of this can
87 be done interactively. Here we show a simple example that uses mpi4py
87 be done interactively. Here we show a simple example that uses mpi4py
88 [mpi4py]_.
88 [mpi4py]_ version 1.1.0 or later.
89
89
90 First, lets define a simply function that uses MPI to calculate the sum of a
90 First, lets define a simply function that uses MPI to calculate the sum of a
91 distributed array. Save the following text in a file called :file:`psum.py`:
91 distributed array. Save the following text in a file called :file:`psum.py`:
92
92
93 .. sourcecode:: python
93 .. sourcecode:: python
94
94
95 from mpi4py import MPI
95 from mpi4py import MPI
96 import numpy as np
96 import numpy as np
97
97
98 def psum(a):
98 def psum(a):
99 s = np.sum(a)
99 s = np.sum(a)
100 return MPI.COMM_WORLD.Allreduce(s,MPI.SUM)
100 rcvBuf = np.array(0.0,'d')
101 MPI.COMM_WORLD.Allreduce([s, MPI.DOUBLE],
102 [rcvBuf, MPI.DOUBLE],
103 op=MPI.SUM)
104 return rcvBuf
101
105
102 Now, start an IPython cluster in the same directory as :file:`psum.py`::
106 Now, start an IPython cluster in the same directory as :file:`psum.py`::
103
107
104 $ ipcluster mpiexec -n 4
108 $ ipcluster mpiexec -n 4
105
109
106 Finally, connect to the cluster and use this function interactively. In this
110 Finally, connect to the cluster and use this function interactively. In this
107 case, we create a random array on each engine and sum up all the random arrays
111 case, we create a random array on each engine and sum up all the random arrays
108 using our :func:`psum` function:
112 using our :func:`psum` function:
109
113
110 .. sourcecode:: ipython
114 .. sourcecode:: ipython
111
115
112 In [1]: from IPython.kernel import client
116 In [1]: from IPython.kernel import client
113
117
114 In [2]: mec = client.MultiEngineClient()
118 In [2]: mec = client.MultiEngineClient()
115
119
116 In [3]: mec.activate()
120 In [3]: mec.activate()
117
121
118 In [4]: px import numpy as np
122 In [4]: px import numpy as np
119 Parallel execution on engines: all
123 Parallel execution on engines: all
120 Out[4]:
124 Out[4]:
121 <Results List>
125 <Results List>
122 [0] In [13]: import numpy as np
126 [0] In [13]: import numpy as np
123 [1] In [13]: import numpy as np
127 [1] In [13]: import numpy as np
124 [2] In [13]: import numpy as np
128 [2] In [13]: import numpy as np
125 [3] In [13]: import numpy as np
129 [3] In [13]: import numpy as np
126
130
127 In [6]: px a = np.random.rand(100)
131 In [6]: px a = np.random.rand(100)
128 Parallel execution on engines: all
132 Parallel execution on engines: all
129 Out[6]:
133 Out[6]:
130 <Results List>
134 <Results List>
131 [0] In [15]: a = np.random.rand(100)
135 [0] In [15]: a = np.random.rand(100)
132 [1] In [15]: a = np.random.rand(100)
136 [1] In [15]: a = np.random.rand(100)
133 [2] In [15]: a = np.random.rand(100)
137 [2] In [15]: a = np.random.rand(100)
134 [3] In [15]: a = np.random.rand(100)
138 [3] In [15]: a = np.random.rand(100)
135
139
136 In [7]: px from psum import psum
140 In [7]: px from psum import psum
137 Parallel execution on engines: all
141 Parallel execution on engines: all
138 Out[7]:
142 Out[7]:
139 <Results List>
143 <Results List>
140 [0] In [16]: from psum import psum
144 [0] In [16]: from psum import psum
141 [1] In [16]: from psum import psum
145 [1] In [16]: from psum import psum
142 [2] In [16]: from psum import psum
146 [2] In [16]: from psum import psum
143 [3] In [16]: from psum import psum
147 [3] In [16]: from psum import psum
144
148
145 In [8]: px s = psum(a)
149 In [8]: px s = psum(a)
146 Parallel execution on engines: all
150 Parallel execution on engines: all
147 Out[8]:
151 Out[8]:
148 <Results List>
152 <Results List>
149 [0] In [17]: s = psum(a)
153 [0] In [17]: s = psum(a)
150 [1] In [17]: s = psum(a)
154 [1] In [17]: s = psum(a)
151 [2] In [17]: s = psum(a)
155 [2] In [17]: s = psum(a)
152 [3] In [17]: s = psum(a)
156 [3] In [17]: s = psum(a)
153
157
154 In [9]: px print s
158 In [9]: px print s
155 Parallel execution on engines: all
159 Parallel execution on engines: all
156 Out[9]:
160 Out[9]:
157 <Results List>
161 <Results List>
158 [0] In [18]: print s
162 [0] In [18]: print s
159 [0] Out[18]: 187.451545803
163 [0] Out[18]: 187.451545803
160
164
161 [1] In [18]: print s
165 [1] In [18]: print s
162 [1] Out[18]: 187.451545803
166 [1] Out[18]: 187.451545803
163
167
164 [2] In [18]: print s
168 [2] In [18]: print s
165 [2] Out[18]: 187.451545803
169 [2] Out[18]: 187.451545803
166
170
167 [3] In [18]: print s
171 [3] In [18]: print s
168 [3] Out[18]: 187.451545803
172 [3] Out[18]: 187.451545803
169
173
170 Any Python code that makes calls to MPI can be used in this manner, including
174 Any Python code that makes calls to MPI can be used in this manner, including
171 compiled C, C++ and Fortran libraries that have been exposed to Python.
175 compiled C, C++ and Fortran libraries that have been exposed to Python.
172
176
173 .. [MPI] Message Passing Interface. http://www-unix.mcs.anl.gov/mpi/
177 .. [MPI] Message Passing Interface. http://www-unix.mcs.anl.gov/mpi/
174 .. [mpi4py] MPI for Python. mpi4py: http://mpi4py.scipy.org/
178 .. [mpi4py] MPI for Python. mpi4py: http://mpi4py.scipy.org/
175 .. [OpenMPI] Open MPI. http://www.open-mpi.org/
179 .. [OpenMPI] Open MPI. http://www.open-mpi.org/
176 .. [PyTrilinos] PyTrilinos. http://trilinos.sandia.gov/packages/pytrilinos/
180 .. [PyTrilinos] PyTrilinos. http://trilinos.sandia.gov/packages/pytrilinos/
177
181
178
182
@@ -1,212 +1,231 b''
1 ================================================
1 ================================================
2 Development version
2 Development version
3 ================================================
3 ================================================
4
4
5 Main `ipython` branch
5 Main `ipython` branch
6 =====================
6 =====================
7
7
8 As of the 0.11 version of IPython, a signifiant portion of the core has been
8 As of the 0.11 version of IPython, a signifiant portion of the core has been
9 refactored. This refactoring is founded on a number of new abstractions.
9 refactored. This refactoring is founded on a number of new abstractions.
10 The main new classes that implement these abstractions are:
10 The main new classes that implement these abstractions are:
11
11
12 * :class:`IPython.utils.traitlets.HasTraitlets`.
12 * :class:`IPython.utils.traitlets.HasTraitlets`.
13 * :class:`IPython.core.component.Component`.
13 * :class:`IPython.core.component.Component`.
14 * :class:`IPython.core.application.Application`.
14 * :class:`IPython.core.application.Application`.
15 * :class:`IPython.config.loader.ConfigLoader`.
15 * :class:`IPython.config.loader.ConfigLoader`.
16 * :class:`IPython.config.loader.Config`
16 * :class:`IPython.config.loader.Config`
17
17
18 We are still in the process of writing developer focused documentation about
18 We are still in the process of writing developer focused documentation about
19 these classes, but for now our :ref:`configuration documentation
19 these classes, but for now our :ref:`configuration documentation
20 <config_overview>` contains a high level overview of the concepts that these
20 <config_overview>` contains a high level overview of the concepts that these
21 classes express.
21 classes express.
22
22
23 The changes listed here are a brief summary of the recent work on IPython.
23 The changes listed here are a brief summary of the recent work on IPython.
24 For more details, please consult the actual source.
24 For more details, please consult the actual source.
25
25
26 New features
26 New features
27 ------------
27 ------------
28
28
29 * The :mod:`IPython.extensions.pretty` extension has been moved out of
30 quarantine and fully updated to the new extension API.
31
32 * New magics for loading/unloading/reloading extensions have been added:
33 ``%load_ext``, ``%unload_ext`` and ``%reload_ext``.
34
29 * The configuration system and configuration files are brand new. See the
35 * The configuration system and configuration files are brand new. See the
30 configuration system :ref:`documentation <config_index>` for more details.
36 configuration system :ref:`documentation <config_index>` for more details.
31
37
32 * The :class:`~IPython.core.iplib.InteractiveShell` class is now a
38 * The :class:`~IPython.core.iplib.InteractiveShell` class is now a
33 :class:`~IPython.core.component.Component` subclass and has traitlets that
39 :class:`~IPython.core.component.Component` subclass and has traitlets that
34 determine the defaults and runtime environment. The ``__init__`` method has
40 determine the defaults and runtime environment. The ``__init__`` method has
35 also been refactored so this class can be instantiated and run without the
41 also been refactored so this class can be instantiated and run without the
36 old :mod:`ipmaker` module.
42 old :mod:`ipmaker` module.
37
43
38 * The methods of :class:`~IPython.core.iplib.InteractiveShell` have
44 * The methods of :class:`~IPython.core.iplib.InteractiveShell` have
39 been organized into sections to make it easier to turn more sections
45 been organized into sections to make it easier to turn more sections
40 of functionality into componenets.
46 of functionality into componenets.
41
47
42 * The embedded shell has been refactored into a truly standalone subclass of
48 * The embedded shell has been refactored into a truly standalone subclass of
43 :class:`InteractiveShell` called :class:`InteractiveShellEmbed`. All
49 :class:`InteractiveShell` called :class:`InteractiveShellEmbed`. All
44 embedding logic has been taken out of the base class and put into the
50 embedding logic has been taken out of the base class and put into the
45 embedded subclass.
51 embedded subclass.
46
52
47 * I have created methods of :class:`~IPython.core.iplib.InteractiveShell` to
53 * I have created methods of :class:`~IPython.core.iplib.InteractiveShell` to
48 help it cleanup after itself. The :meth:`cleanup` method controls this. We
54 help it cleanup after itself. The :meth:`cleanup` method controls this. We
49 couldn't do this in :meth:`__del__` because we have cycles in our object
55 couldn't do this in :meth:`__del__` because we have cycles in our object
50 graph that prevent it from being called.
56 graph that prevent it from being called.
51
57
52 * Created a new module :mod:`IPython.utils.importstring` for resolving
58 * Created a new module :mod:`IPython.utils.importstring` for resolving
53 strings like ``foo.bar.Bar`` to the actual class.
59 strings like ``foo.bar.Bar`` to the actual class.
54
60
55 * Completely refactored the :mod:`IPython.core.prefilter` module into
61 * Completely refactored the :mod:`IPython.core.prefilter` module into
56 :class:`~IPython.core.component.Component` subclasses. Added a new layer
62 :class:`~IPython.core.component.Component` subclasses. Added a new layer
57 into the prefilter system, called "transformations" that all new prefilter
63 into the prefilter system, called "transformations" that all new prefilter
58 logic should use (rather than the older "checker/handler" approach).
64 logic should use (rather than the older "checker/handler" approach).
59
65
60 * Aliases are now components (:mod:`IPython.core.alias`).
66 * Aliases are now components (:mod:`IPython.core.alias`).
61
67
62 * We are now using an internally shipped version of
68 * We are now using an internally shipped version of
63 :mod:`~IPython.external.argparse` to parse command line options for
69 :mod:`~IPython.external.argparse` to parse command line options for
64 :command:`ipython`.
70 :command:`ipython`.
65
71
66 * New top level :func:`~IPython.core.embed.embed` function that can be called
72 * New top level :func:`~IPython.core.embed.embed` function that can be called
67 to embed IPython at any place in user's code. One the first call it will
73 to embed IPython at any place in user's code. One the first call it will
68 create an :class:`~IPython.core.embed.InteractiveShellEmbed` instance and
74 create an :class:`~IPython.core.embed.InteractiveShellEmbed` instance and
69 call it. In later calls, it just calls the previously created
75 call it. In later calls, it just calls the previously created
70 :class:`~IPython.core.embed.InteractiveShellEmbed`.
76 :class:`~IPython.core.embed.InteractiveShellEmbed`.
71
77
72 * Created a component system (:mod:`IPython.core.component`) that is based on
78 * Created a component system (:mod:`IPython.core.component`) that is based on
73 :mod:`IPython.utils.traitlets`. Components are arranged into a runtime
79 :mod:`IPython.utils.traitlets`. Components are arranged into a runtime
74 containment tree (not inheritance) that i) automatically propagates
80 containment tree (not inheritance) that i) automatically propagates
75 configuration information and ii) allows components to discover each other
81 configuration information and ii) allows components to discover each other
76 in a loosely coupled manner. In the future all parts of IPython will be
82 in a loosely coupled manner. In the future all parts of IPython will be
77 subclasses of :class:`~IPython.core.component.Component`. All IPython
83 subclasses of :class:`~IPython.core.component.Component`. All IPython
78 developers should become familiar with the component system.
84 developers should become familiar with the component system.
79
85
80 * Created a new :class:`~IPython.config.loader.Config` for holding
86 * Created a new :class:`~IPython.config.loader.Config` for holding
81 configuration information. This is a dict like class with a few extras: i)
87 configuration information. This is a dict like class with a few extras: i)
82 it supports attribute style access, ii) it has a merge function that merges
88 it supports attribute style access, ii) it has a merge function that merges
83 two :class:`~IPython.config.loader.Config` instances recursively and iii) it
89 two :class:`~IPython.config.loader.Config` instances recursively and iii) it
84 will automatically create sub-:class:`~IPython.config.loader.Config`
90 will automatically create sub-:class:`~IPython.config.loader.Config`
85 instances for attributes that start with an uppercase character.
91 instances for attributes that start with an uppercase character.
86
92
87 * Created new configuration loaders in :mod:`IPython.config.loader`. These
93 * Created new configuration loaders in :mod:`IPython.config.loader`. These
88 loaders provide a unified loading interface for all configuration
94 loaders provide a unified loading interface for all configuration
89 information including command line arguments and configuration files. We
95 information including command line arguments and configuration files. We
90 have two default implementations based on :mod:`argparse` and plain python
96 have two default implementations based on :mod:`argparse` and plain python
91 files. These are used to implement the new configuration system.
97 files. These are used to implement the new configuration system.
92
98
93 * Created a top-level :class:`Application` class in
99 * Created a top-level :class:`Application` class in
94 :mod:`IPython.core.application` that is designed to encapsulate the starting
100 :mod:`IPython.core.application` that is designed to encapsulate the starting
95 of any IPython process. An application loads and merges all the
101 of any IPython process. An application loads and merges all the
96 configuration objects, constructs the main application :class:`Component`
102 configuration objects, constructs the main application :class:`Component`
97 instances and then starts the application running. The default
103 instances and then starts the application running. The default
98 :class:`Application` class has built-in logic for handling the IPython
104 :class:`Application` class has built-in logic for handling the IPython
99 directory as well as profiles.
105 directory as well as profiles.
100
106
101 * The :class:`Type` and :class:`Instance` traitlets now handle classes given
107 * The :class:`Type` and :class:`Instance` traitlets now handle classes given
102 as strings, like ``foo.bar.Bar``. This is needed for forward declarations.
108 as strings, like ``foo.bar.Bar``. This is needed for forward declarations.
103 But, this was implemented in a careful way so that string to class
109 But, this was implemented in a careful way so that string to class
104 resolution is done at a single point, when the parent
110 resolution is done at a single point, when the parent
105 :class:`~IPython.utils.traitlets.HasTraitlets` is instantiated.
111 :class:`~IPython.utils.traitlets.HasTraitlets` is instantiated.
106
112
107 * :mod:`IPython.utils.ipstruct` has been refactored to be a subclass of
113 * :mod:`IPython.utils.ipstruct` has been refactored to be a subclass of
108 dict. It also now has full docstrings and doctests.
114 dict. It also now has full docstrings and doctests.
109 * Created a Trait's like implementation in :mod:`IPython.utils.traitlets`.
115 * Created a Trait's like implementation in :mod:`IPython.utils.traitlets`.
110 This is a pure Python, lightweight version of a library that is similar to
116 This is a pure Python, lightweight version of a library that is similar to
111 :mod:`enthought.traits`. We are using this for validation, defaults and
117 :mod:`enthought.traits`. We are using this for validation, defaults and
112 notification in our new component system. Although it is not API compatible
118 notification in our new component system. Although it is not API compatible
113 with :mod:`enthought.traits`, we plan on moving in this direction so that
119 with :mod:`enthought.traits`, we plan on moving in this direction so that
114 eventually our implementation could be replaced by a (yet to exist) pure
120 eventually our implementation could be replaced by a (yet to exist) pure
115 Python version of :mod:`enthought.traits`.
121 Python version of :mod:`enthought.traits`.
116
122
117 * Added a new module :mod:`IPython.lib.inputhook` to manage the integration
123 * Added a new module :mod:`IPython.lib.inputhook` to manage the integration
118 with GUI event loops using `PyOS_InputHook`. See the docstrings in this
124 with GUI event loops using `PyOS_InputHook`. See the docstrings in this
119 module or the main IPython docs for details.
125 module or the main IPython docs for details.
120
126
121 * For users, GUI event loop integration is now handled through the new
127 * For users, GUI event loop integration is now handled through the new
122 :command:`%gui` magic command. Type ``%gui?`` at an IPython prompt for
128 :command:`%gui` magic command. Type ``%gui?`` at an IPython prompt for
123 documentation.
129 documentation.
124
130
125 * The command line options ``-wthread``, ``-qthread`` and
131 * The command line options ``-wthread``, ``-qthread`` and
126 ``-gthread`` just call the appropriate :mod:`IPython.lib.inputhook`
132 ``-gthread`` just call the appropriate :mod:`IPython.lib.inputhook`
127 functions.
133 functions.
128
134
129 * For developers :mod:`IPython.lib.inputhook` provides a simple interface
135 * For developers :mod:`IPython.lib.inputhook` provides a simple interface
130 for managing the event loops in their interactive GUI applications.
136 for managing the event loops in their interactive GUI applications.
131 Examples can be found in our :file:`docs/examples/lib` directory.
137 Examples can be found in our :file:`docs/examples/lib` directory.
132
138
133 Bug fixes
139 Bug fixes
134 ---------
140 ---------
135
141
142 * Previously, the latex Sphinx docs were in a single chapter. This has been
143 fixed by adding a sixth argument of True to the ``latex_documents``
144 attribute of :file:`conf.py`.
145
146 * The ``psum`` example in the MPI documentation has been updated to mpi4py
147 version 1.1.0. Thanks to J. Thomas for this fix.
148
149 * The top-level, zero-install :file:`ipython.py` script has been updated to
150 the new application launching API.
151
136 * Keyboard interrupts now work with GUI support enabled across all platforms
152 * Keyboard interrupts now work with GUI support enabled across all platforms
137 and all GUI toolkits reliably.
153 and all GUI toolkits reliably.
138
154
139 Backwards incompatible changes
155 Backwards incompatible changes
140 ------------------------------
156 ------------------------------
141
157
158 * The extension loading functions have been renamed to
159 :func:`load_ipython_extension` and :func:`unload_ipython_extension`.
160
142 * :class:`~IPython.core.iplib.InteractiveShell` no longer takes an
161 * :class:`~IPython.core.iplib.InteractiveShell` no longer takes an
143 ``embedded`` argument. Instead just use the
162 ``embedded`` argument. Instead just use the
144 :class:`~IPython.core.iplib.InteractiveShellEmbed` class.
163 :class:`~IPython.core.iplib.InteractiveShellEmbed` class.
145
164
146 * ``__IPYTHON__`` is no longer injected into ``__builtin__``.
165 * ``__IPYTHON__`` is no longer injected into ``__builtin__``.
147
166
148 * :meth:`Struct.__init__` no longer takes `None` as its first argument. It
167 * :meth:`Struct.__init__` no longer takes `None` as its first argument. It
149 must be a :class:`dict` or :class:`Struct`.
168 must be a :class:`dict` or :class:`Struct`.
150
169
151 * :meth:`~IPython.core.iplib.InteractiveShell.ipmagic` has been renamed
170 * :meth:`~IPython.core.iplib.InteractiveShell.ipmagic` has been renamed
152 :meth:`~IPython.core.iplib.InteractiveShell.magic.`
171 :meth:`~IPython.core.iplib.InteractiveShell.magic.`
153
172
154 * The functions :func:`ipmagic` and :func:`ipalias` have been removed from
173 * The functions :func:`ipmagic` and :func:`ipalias` have been removed from
155 :mod:`__builtins__`.
174 :mod:`__builtins__`.
156
175
157 * The references to the global :class:`~IPython.core.iplib.InteractiveShell`
176 * The references to the global :class:`~IPython.core.iplib.InteractiveShell`
158 instance (``_ip``, and ``__IP``) have been removed from the user's
177 instance (``_ip``, and ``__IP``) have been removed from the user's
159 namespace. They are replaced by a new function called :func:`get_ipython`
178 namespace. They are replaced by a new function called :func:`get_ipython`
160 that returns the current :class:`~IPython.core.iplib.InteractiveShell`
179 that returns the current :class:`~IPython.core.iplib.InteractiveShell`
161 instance. This function is injected into the user's namespace and is now the
180 instance. This function is injected into the user's namespace and is now the
162 main way of accessing IPython's API.
181 main way of accessing IPython's API.
163
182
164 * Old style configuration files :file:`ipythonrc` and :file:`ipy_user_conf.py`
183 * Old style configuration files :file:`ipythonrc` and :file:`ipy_user_conf.py`
165 are no longer supported. Users should migrate there configuration files to
184 are no longer supported. Users should migrate there configuration files to
166 the new format described :ref:`here <config_overview>` and :ref:`here
185 the new format described :ref:`here <config_overview>` and :ref:`here
167 <configuring_ipython>`.
186 <configuring_ipython>`.
168
187
169 * The old IPython extension API that relied on :func:`ipapi` has been
188 * The old IPython extension API that relied on :func:`ipapi` has been
170 completely removed. The new extension API is described :ref:`here
189 completely removed. The new extension API is described :ref:`here
171 <configuring_ipython>`.
190 <configuring_ipython>`.
172
191
173 * Support for ``qt3`` has been dropped. User's who need this should use
192 * Support for ``qt3`` has been dropped. User's who need this should use
174 previous versions of IPython.
193 previous versions of IPython.
175
194
176 * Removed :mod:`shellglobals` as it was obsolete.
195 * Removed :mod:`shellglobals` as it was obsolete.
177
196
178 * Removed all the threaded shells in :mod:`IPython.core.shell`. These are no
197 * Removed all the threaded shells in :mod:`IPython.core.shell`. These are no
179 longer needed because of the new capabilities in
198 longer needed because of the new capabilities in
180 :mod:`IPython.lib.inputhook`.
199 :mod:`IPython.lib.inputhook`.
181
200
182 * The ``-pylab`` command line flag has been disabled until matplotlib adds
201 * The ``-pylab`` command line flag has been disabled until matplotlib adds
183 support for the new :mod:`IPython.lib.inputhook` approach. The new stuff
202 support for the new :mod:`IPython.lib.inputhook` approach. The new stuff
184 does work with matplotlib, but you have to set everything up by hand.
203 does work with matplotlib, but you have to set everything up by hand.
185
204
186 * New top-level sub-packages have been created: :mod:`IPython.core`,
205 * New top-level sub-packages have been created: :mod:`IPython.core`,
187 :mod:`IPython.lib`, :mod:`IPython.utils`, :mod:`IPython.deathrow`,
206 :mod:`IPython.lib`, :mod:`IPython.utils`, :mod:`IPython.deathrow`,
188 :mod:`IPython.quarantine`. All existing top-level modules have been
207 :mod:`IPython.quarantine`. All existing top-level modules have been
189 moved to appropriate sub-packages. All internal import statements
208 moved to appropriate sub-packages. All internal import statements
190 have been updated and tests have been added. The build system (setup.py
209 have been updated and tests have been added. The build system (setup.py
191 and friends) have been updated. See :ref:`this section <module_reorg>` of the
210 and friends) have been updated. See :ref:`this section <module_reorg>` of the
192 documentation for descriptions of these new sub-packages.
211 documentation for descriptions of these new sub-packages.
193
212
194 * Compatability modules have been created for :mod:`IPython.Shell`,
213 * Compatability modules have been created for :mod:`IPython.Shell`,
195 :mod:`IPython.ipapi` and :mod:`IPython.iplib` that display warnings
214 :mod:`IPython.ipapi` and :mod:`IPython.iplib` that display warnings
196 and then load the actual implementation from :mod:`IPython.core`.
215 and then load the actual implementation from :mod:`IPython.core`.
197
216
198 * :mod:`Extensions` has been moved to :mod:`extensions` and all existing
217 * :mod:`Extensions` has been moved to :mod:`extensions` and all existing
199 extensions have been moved to either :mod:`IPython.quarantine` or
218 extensions have been moved to either :mod:`IPython.quarantine` or
200 :mod:`IPython.deathrow`. :mod:`IPython.quarantine` contains modules that we
219 :mod:`IPython.deathrow`. :mod:`IPython.quarantine` contains modules that we
201 plan on keeping but that need to be updated. :mod:`IPython.deathrow`
220 plan on keeping but that need to be updated. :mod:`IPython.deathrow`
202 contains modules that are either dead or that should be maintained as third
221 contains modules that are either dead or that should be maintained as third
203 party libraries. More details about this can be found :ref:`here
222 party libraries. More details about this can be found :ref:`here
204 <module_reorg>`.
223 <module_reorg>`.
205
224
206 * The IPython GUIs in :mod:`IPython.frontend` and :mod:`IPython.gui` are likely
225 * The IPython GUIs in :mod:`IPython.frontend` and :mod:`IPython.gui` are likely
207 broken because of the refactoring in the core. With proper updates, these
226 broken because of the refactoring in the core. With proper updates, these
208 should still work. We probably want to get these so they are not using
227 should still work. We probably want to get these so they are not using
209 :mod:`IPython.kernel.core` (which is being phased out).
228 :mod:`IPython.kernel.core` (which is being phased out).
210
229
211
230
212
231
@@ -1,11 +1,12 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
2 # -*- coding: utf-8 -*-
3 """IPython -- An enhanced Interactive Python
3 """IPython -- An enhanced Interactive Python
4
4
5 The actual ipython script to be installed with 'python setup.py install' is
5 The actual ipython script to be installed with 'python setup.py install' is
6 in './scripts' directory. This file is here (ipython source root directory)
6 in './scripts' directory. This file is here (ipython source root directory)
7 to facilitate non-root 'zero-installation' (just copy the source tree
7 to facilitate non-root 'zero-installation' (just copy the source tree
8 somewhere and run ipython.py) and development. """
8 somewhere and run ipython.py) and development. """
9
9
10 import IPython.core.shell
10 from IPython.core.ipapp import launch_new_instance
11 IPython.core.shell.start().mainloop()
11
12 launch_new_instance()
1 NO CONTENT: file was removed
NO CONTENT: file was removed
General Comments 0
You need to be logged in to leave comments. Login now