##// END OF EJS Templates
@carreau comment's
Pierre Gerold -
Show More
@@ -1,129 +1,130 b''
1 """Implementation of magic functions that control various automatic behaviors.
1 """Implementation of magic functions that control various automatic behaviors.
2 """
2 """
3 from __future__ import print_function
3 from __future__ import print_function
4 from __future__ import absolute_import
4 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
5 # Copyright (c) 2012 The IPython Development Team.
6 # Copyright (c) 2012 The IPython Development Team.
6 #
7 #
7 # Distributed under the terms of the Modified BSD License.
8 # Distributed under the terms of the Modified BSD License.
8 #
9 #
9 # The full license is in the file COPYING.txt, distributed with this software.
10 # The full license is in the file COPYING.txt, distributed with this software.
10 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
11
12
12 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
13 # Imports
14 # Imports
14 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
15
16
16 # Our own packages
17 # Our own packages
17 from IPython.core.magic import Bunch, Magics, magics_class, line_magic
18 from IPython.core.magic import Bunch, Magics, magics_class, line_magic
18 from IPython.testing.skipdoctest import skip_doctest
19 from IPython.testing.skipdoctest import skip_doctest
19 from logging import error
20 from logging import error
20
21
21 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
22 # Magic implementation classes
23 # Magic implementation classes
23 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
24
25
25 @magics_class
26 @magics_class
26 class AutoMagics(Magics):
27 class AutoMagics(Magics):
27 """Magics that control various autoX behaviors."""
28 """Magics that control various autoX behaviors."""
28
29
29 def __init__(self, shell):
30 def __init__(self, shell):
30 super(AutoMagics, self).__init__(shell)
31 super(AutoMagics, self).__init__(shell)
31 # namespace for holding state we may need
32 # namespace for holding state we may need
32 self._magic_state = Bunch()
33 self._magic_state = Bunch()
33
34
34 @line_magic
35 @line_magic
35 def automagic(self, parameter_s=''):
36 def automagic(self, parameter_s=''):
36 """Make magic functions callable without having to type the initial %.
37 """Make magic functions callable without having to type the initial %.
37
38
38 Without argumentsl toggles on/off (when off, you must call it as
39 Without argumentsl toggles on/off (when off, you must call it as
39 %automagic, of course). With arguments it sets the value, and you can
40 %automagic, of course). With arguments it sets the value, and you can
40 use any of (case insensitive):
41 use any of (case insensitive):
41
42
42 - on, 1, True: to activate
43 - on, 1, True: to activate
43
44
44 - off, 0, False: to deactivate.
45 - off, 0, False: to deactivate.
45
46
46 Note that magic functions have lowest priority, so if there's a
47 Note that magic functions have lowest priority, so if there's a
47 variable whose name collides with that of a magic fn, automagic won't
48 variable whose name collides with that of a magic fn, automagic won't
48 work for that function (you get the variable instead). However, if you
49 work for that function (you get the variable instead). However, if you
49 delete the variable (del var), the previously shadowed magic function
50 delete the variable (del var), the previously shadowed magic function
50 becomes visible to automagic again."""
51 becomes visible to automagic again."""
51
52
52 arg = parameter_s.lower()
53 arg = parameter_s.lower()
53 mman = self.shell.magics_manager
54 mman = self.shell.magics_manager
54 if arg in ('on', '1', 'true'):
55 if arg in ('on', '1', 'true'):
55 val = True
56 val = True
56 elif arg in ('off', '0', 'false'):
57 elif arg in ('off', '0', 'false'):
57 val = False
58 val = False
58 else:
59 else:
59 val = not mman.auto_magic
60 val = not mman.auto_magic
60 mman.auto_magic = val
61 mman.auto_magic = val
61 print('\n' + self.shell.magics_manager.auto_status())
62 print('\n' + self.shell.magics_manager.auto_status())
62
63
63 @skip_doctest
64 @skip_doctest
64 @line_magic
65 @line_magic
65 def autocall(self, parameter_s=''):
66 def autocall(self, parameter_s=''):
66 """Make functions callable without having to type parentheses.
67 """Make functions callable without having to type parentheses.
67
68
68 Usage:
69 Usage:
69
70
70 %autocall [mode]
71 %autocall [mode]
71
72
72 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
73 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
73 value is toggled on and off (remembering the previous state).
74 value is toggled on and off (remembering the previous state).
74
75
75 In more detail, these values mean:
76 In more detail, these values mean:
76
77
77 0 -> fully disabled
78 0 -> fully disabled
78
79
79 1 -> active, but do not apply if there are no arguments on the line.
80 1 -> active, but do not apply if there are no arguments on the line.
80
81
81 In this mode, you get::
82 In this mode, you get::
82
83
83 In [1]: callable
84 In [1]: callable
84 Out[1]: <built-in function callable>
85 Out[1]: <built-in function callable>
85
86
86 In [2]: callable 'hello'
87 In [2]: callable 'hello'
87 ------> callable('hello')
88 ------> callable('hello')
88 Out[2]: False
89 Out[2]: False
89
90
90 2 -> Active always. Even if no arguments are present, the callable
91 2 -> Active always. Even if no arguments are present, the callable
91 object is called::
92 object is called::
92
93
93 In [2]: float
94 In [2]: float
94 ------> float()
95 ------> float()
95 Out[2]: 0.0
96 Out[2]: 0.0
96
97
97 Note that even with autocall off, you can still use '/' at the start of
98 Note that even with autocall off, you can still use '/' at the start of
98 a line to treat the first argument on the command line as a function
99 a line to treat the first argument on the command line as a function
99 and add parentheses to it::
100 and add parentheses to it::
100
101
101 In [8]: /str 43
102 In [8]: /str 43
102 ------> str(43)
103 ------> str(43)
103 Out[8]: '43'
104 Out[8]: '43'
104
105
105 # all-random (note for auto-testing)
106 # all-random (note for auto-testing)
106 """
107 """
107
108
108 if parameter_s:
109 if parameter_s:
109 arg = int(parameter_s)
110 arg = int(parameter_s)
110 else:
111 else:
111 arg = 'toggle'
112 arg = 'toggle'
112
113
113 if not arg in (0, 1, 2, 'toggle'):
114 if not arg in (0, 1, 2, 'toggle'):
114 error('Valid modes: (0->Off, 1->Smart, 2->Full')
115 error('Valid modes: (0->Off, 1->Smart, 2->Full')
115 return
116 return
116
117
117 if arg in (0, 1, 2):
118 if arg in (0, 1, 2):
118 self.shell.autocall = arg
119 self.shell.autocall = arg
119 else: # toggle
120 else: # toggle
120 if self.shell.autocall:
121 if self.shell.autocall:
121 self._magic_state.autocall_save = self.shell.autocall
122 self._magic_state.autocall_save = self.shell.autocall
122 self.shell.autocall = 0
123 self.shell.autocall = 0
123 else:
124 else:
124 try:
125 try:
125 self.shell.autocall = self._magic_state.autocall_save
126 self.shell.autocall = self._magic_state.autocall_save
126 except AttributeError:
127 except AttributeError:
127 self.shell.autocall = self._magic_state.autocall_save = 1
128 self.shell.autocall = self._magic_state.autocall_save = 1
128
129
129 print("Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall])
130 print("Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall])
@@ -1,613 +1,614 b''
1 """Implementation of basic magic functions."""
1 """Implementation of basic magic functions."""
2
2
3 from __future__ import print_function
3 from __future__ import print_function
4 from __future__ import absolute_import
4
5
5 import io
6 import io
6 import sys
7 import sys
7 from pprint import pformat
8 from pprint import pformat
8
9
9 from IPython.core import magic_arguments, page
10 from IPython.core import magic_arguments, page
10 from IPython.core.error import UsageError
11 from IPython.core.error import UsageError
11 from IPython.core.magic import Magics, magics_class, line_magic, magic_escapes
12 from IPython.core.magic import Magics, magics_class, line_magic, magic_escapes
12 from IPython.utils.text import format_screen, dedent, indent
13 from IPython.utils.text import format_screen, dedent, indent
13 from IPython.testing.skipdoctest import skip_doctest
14 from IPython.testing.skipdoctest import skip_doctest
14 from IPython.utils.ipstruct import Struct
15 from IPython.utils.ipstruct import Struct
15 from IPython.utils.path import unquote_filename
16 from IPython.utils.path import unquote_filename
16 from IPython.utils.py3compat import unicode_type
17 from IPython.utils.py3compat import unicode_type
17 from warnings import warn
18 from warnings import warn
18 from logging import error
19 from logging import error
19
20
20
21
21 class MagicsDisplay(object):
22 class MagicsDisplay(object):
22 def __init__(self, magics_manager):
23 def __init__(self, magics_manager):
23 self.magics_manager = magics_manager
24 self.magics_manager = magics_manager
24
25
25 def _lsmagic(self):
26 def _lsmagic(self):
26 """The main implementation of the %lsmagic"""
27 """The main implementation of the %lsmagic"""
27 mesc = magic_escapes['line']
28 mesc = magic_escapes['line']
28 cesc = magic_escapes['cell']
29 cesc = magic_escapes['cell']
29 mman = self.magics_manager
30 mman = self.magics_manager
30 magics = mman.lsmagic()
31 magics = mman.lsmagic()
31 out = ['Available line magics:',
32 out = ['Available line magics:',
32 mesc + (' '+mesc).join(sorted(magics['line'])),
33 mesc + (' '+mesc).join(sorted(magics['line'])),
33 '',
34 '',
34 'Available cell magics:',
35 'Available cell magics:',
35 cesc + (' '+cesc).join(sorted(magics['cell'])),
36 cesc + (' '+cesc).join(sorted(magics['cell'])),
36 '',
37 '',
37 mman.auto_status()]
38 mman.auto_status()]
38 return '\n'.join(out)
39 return '\n'.join(out)
39
40
40 def _repr_pretty_(self, p, cycle):
41 def _repr_pretty_(self, p, cycle):
41 p.text(self._lsmagic())
42 p.text(self._lsmagic())
42
43
43 def __str__(self):
44 def __str__(self):
44 return self._lsmagic()
45 return self._lsmagic()
45
46
46 def _jsonable(self):
47 def _jsonable(self):
47 """turn magics dict into jsonable dict of the same structure
48 """turn magics dict into jsonable dict of the same structure
48
49
49 replaces object instances with their class names as strings
50 replaces object instances with their class names as strings
50 """
51 """
51 magic_dict = {}
52 magic_dict = {}
52 mman = self.magics_manager
53 mman = self.magics_manager
53 magics = mman.lsmagic()
54 magics = mman.lsmagic()
54 for key, subdict in magics.items():
55 for key, subdict in magics.items():
55 d = {}
56 d = {}
56 magic_dict[key] = d
57 magic_dict[key] = d
57 for name, obj in subdict.items():
58 for name, obj in subdict.items():
58 try:
59 try:
59 classname = obj.__self__.__class__.__name__
60 classname = obj.__self__.__class__.__name__
60 except AttributeError:
61 except AttributeError:
61 classname = 'Other'
62 classname = 'Other'
62
63
63 d[name] = classname
64 d[name] = classname
64 return magic_dict
65 return magic_dict
65
66
66 def _repr_json_(self):
67 def _repr_json_(self):
67 return self._jsonable()
68 return self._jsonable()
68
69
69
70
70 @magics_class
71 @magics_class
71 class BasicMagics(Magics):
72 class BasicMagics(Magics):
72 """Magics that provide central IPython functionality.
73 """Magics that provide central IPython functionality.
73
74
74 These are various magics that don't fit into specific categories but that
75 These are various magics that don't fit into specific categories but that
75 are all part of the base 'IPython experience'."""
76 are all part of the base 'IPython experience'."""
76
77
77 @magic_arguments.magic_arguments()
78 @magic_arguments.magic_arguments()
78 @magic_arguments.argument(
79 @magic_arguments.argument(
79 '-l', '--line', action='store_true',
80 '-l', '--line', action='store_true',
80 help="""Create a line magic alias."""
81 help="""Create a line magic alias."""
81 )
82 )
82 @magic_arguments.argument(
83 @magic_arguments.argument(
83 '-c', '--cell', action='store_true',
84 '-c', '--cell', action='store_true',
84 help="""Create a cell magic alias."""
85 help="""Create a cell magic alias."""
85 )
86 )
86 @magic_arguments.argument(
87 @magic_arguments.argument(
87 'name',
88 'name',
88 help="""Name of the magic to be created."""
89 help="""Name of the magic to be created."""
89 )
90 )
90 @magic_arguments.argument(
91 @magic_arguments.argument(
91 'target',
92 'target',
92 help="""Name of the existing line or cell magic."""
93 help="""Name of the existing line or cell magic."""
93 )
94 )
94 @line_magic
95 @line_magic
95 def alias_magic(self, line=''):
96 def alias_magic(self, line=''):
96 """Create an alias for an existing line or cell magic.
97 """Create an alias for an existing line or cell magic.
97
98
98 Examples
99 Examples
99 --------
100 --------
100 ::
101 ::
101
102
102 In [1]: %alias_magic t timeit
103 In [1]: %alias_magic t timeit
103 Created `%t` as an alias for `%timeit`.
104 Created `%t` as an alias for `%timeit`.
104 Created `%%t` as an alias for `%%timeit`.
105 Created `%%t` as an alias for `%%timeit`.
105
106
106 In [2]: %t -n1 pass
107 In [2]: %t -n1 pass
107 1 loops, best of 3: 954 ns per loop
108 1 loops, best of 3: 954 ns per loop
108
109
109 In [3]: %%t -n1
110 In [3]: %%t -n1
110 ...: pass
111 ...: pass
111 ...:
112 ...:
112 1 loops, best of 3: 954 ns per loop
113 1 loops, best of 3: 954 ns per loop
113
114
114 In [4]: %alias_magic --cell whereami pwd
115 In [4]: %alias_magic --cell whereami pwd
115 UsageError: Cell magic function `%%pwd` not found.
116 UsageError: Cell magic function `%%pwd` not found.
116 In [5]: %alias_magic --line whereami pwd
117 In [5]: %alias_magic --line whereami pwd
117 Created `%whereami` as an alias for `%pwd`.
118 Created `%whereami` as an alias for `%pwd`.
118
119
119 In [6]: %whereami
120 In [6]: %whereami
120 Out[6]: u'/home/testuser'
121 Out[6]: u'/home/testuser'
121 """
122 """
122 args = magic_arguments.parse_argstring(self.alias_magic, line)
123 args = magic_arguments.parse_argstring(self.alias_magic, line)
123 shell = self.shell
124 shell = self.shell
124 mman = self.shell.magics_manager
125 mman = self.shell.magics_manager
125 escs = ''.join(magic_escapes.values())
126 escs = ''.join(magic_escapes.values())
126
127
127 target = args.target.lstrip(escs)
128 target = args.target.lstrip(escs)
128 name = args.name.lstrip(escs)
129 name = args.name.lstrip(escs)
129
130
130 # Find the requested magics.
131 # Find the requested magics.
131 m_line = shell.find_magic(target, 'line')
132 m_line = shell.find_magic(target, 'line')
132 m_cell = shell.find_magic(target, 'cell')
133 m_cell = shell.find_magic(target, 'cell')
133 if args.line and m_line is None:
134 if args.line and m_line is None:
134 raise UsageError('Line magic function `%s%s` not found.' %
135 raise UsageError('Line magic function `%s%s` not found.' %
135 (magic_escapes['line'], target))
136 (magic_escapes['line'], target))
136 if args.cell and m_cell is None:
137 if args.cell and m_cell is None:
137 raise UsageError('Cell magic function `%s%s` not found.' %
138 raise UsageError('Cell magic function `%s%s` not found.' %
138 (magic_escapes['cell'], target))
139 (magic_escapes['cell'], target))
139
140
140 # If --line and --cell are not specified, default to the ones
141 # If --line and --cell are not specified, default to the ones
141 # that are available.
142 # that are available.
142 if not args.line and not args.cell:
143 if not args.line and not args.cell:
143 if not m_line and not m_cell:
144 if not m_line and not m_cell:
144 raise UsageError(
145 raise UsageError(
145 'No line or cell magic with name `%s` found.' % target
146 'No line or cell magic with name `%s` found.' % target
146 )
147 )
147 args.line = bool(m_line)
148 args.line = bool(m_line)
148 args.cell = bool(m_cell)
149 args.cell = bool(m_cell)
149
150
150 if args.line:
151 if args.line:
151 mman.register_alias(name, target, 'line')
152 mman.register_alias(name, target, 'line')
152 print('Created `%s%s` as an alias for `%s%s`.' % (
153 print('Created `%s%s` as an alias for `%s%s`.' % (
153 magic_escapes['line'], name,
154 magic_escapes['line'], name,
154 magic_escapes['line'], target))
155 magic_escapes['line'], target))
155
156
156 if args.cell:
157 if args.cell:
157 mman.register_alias(name, target, 'cell')
158 mman.register_alias(name, target, 'cell')
158 print('Created `%s%s` as an alias for `%s%s`.' % (
159 print('Created `%s%s` as an alias for `%s%s`.' % (
159 magic_escapes['cell'], name,
160 magic_escapes['cell'], name,
160 magic_escapes['cell'], target))
161 magic_escapes['cell'], target))
161
162
162 @line_magic
163 @line_magic
163 def lsmagic(self, parameter_s=''):
164 def lsmagic(self, parameter_s=''):
164 """List currently available magic functions."""
165 """List currently available magic functions."""
165 return MagicsDisplay(self.shell.magics_manager)
166 return MagicsDisplay(self.shell.magics_manager)
166
167
167 def _magic_docs(self, brief=False, rest=False):
168 def _magic_docs(self, brief=False, rest=False):
168 """Return docstrings from magic functions."""
169 """Return docstrings from magic functions."""
169 mman = self.shell.magics_manager
170 mman = self.shell.magics_manager
170 docs = mman.lsmagic_docs(brief, missing='No documentation')
171 docs = mman.lsmagic_docs(brief, missing='No documentation')
171
172
172 if rest:
173 if rest:
173 format_string = '**%s%s**::\n\n%s\n\n'
174 format_string = '**%s%s**::\n\n%s\n\n'
174 else:
175 else:
175 format_string = '%s%s:\n%s\n'
176 format_string = '%s%s:\n%s\n'
176
177
177 return ''.join(
178 return ''.join(
178 [format_string % (magic_escapes['line'], fname,
179 [format_string % (magic_escapes['line'], fname,
179 indent(dedent(fndoc)))
180 indent(dedent(fndoc)))
180 for fname, fndoc in sorted(docs['line'].items())]
181 for fname, fndoc in sorted(docs['line'].items())]
181 +
182 +
182 [format_string % (magic_escapes['cell'], fname,
183 [format_string % (magic_escapes['cell'], fname,
183 indent(dedent(fndoc)))
184 indent(dedent(fndoc)))
184 for fname, fndoc in sorted(docs['cell'].items())]
185 for fname, fndoc in sorted(docs['cell'].items())]
185 )
186 )
186
187
187 @line_magic
188 @line_magic
188 def magic(self, parameter_s=''):
189 def magic(self, parameter_s=''):
189 """Print information about the magic function system.
190 """Print information about the magic function system.
190
191
191 Supported formats: -latex, -brief, -rest
192 Supported formats: -latex, -brief, -rest
192 """
193 """
193
194
194 mode = ''
195 mode = ''
195 try:
196 try:
196 mode = parameter_s.split()[0][1:]
197 mode = parameter_s.split()[0][1:]
197 except IndexError:
198 except IndexError:
198 pass
199 pass
199
200
200 brief = (mode == 'brief')
201 brief = (mode == 'brief')
201 rest = (mode == 'rest')
202 rest = (mode == 'rest')
202 magic_docs = self._magic_docs(brief, rest)
203 magic_docs = self._magic_docs(brief, rest)
203
204
204 if mode == 'latex':
205 if mode == 'latex':
205 print(self.format_latex(magic_docs))
206 print(self.format_latex(magic_docs))
206 return
207 return
207 else:
208 else:
208 magic_docs = format_screen(magic_docs)
209 magic_docs = format_screen(magic_docs)
209
210
210 out = ["""
211 out = ["""
211 IPython's 'magic' functions
212 IPython's 'magic' functions
212 ===========================
213 ===========================
213
214
214 The magic function system provides a series of functions which allow you to
215 The magic function system provides a series of functions which allow you to
215 control the behavior of IPython itself, plus a lot of system-type
216 control the behavior of IPython itself, plus a lot of system-type
216 features. There are two kinds of magics, line-oriented and cell-oriented.
217 features. There are two kinds of magics, line-oriented and cell-oriented.
217
218
218 Line magics are prefixed with the % character and work much like OS
219 Line magics are prefixed with the % character and work much like OS
219 command-line calls: they get as an argument the rest of the line, where
220 command-line calls: they get as an argument the rest of the line, where
220 arguments are passed without parentheses or quotes. For example, this will
221 arguments are passed without parentheses or quotes. For example, this will
221 time the given statement::
222 time the given statement::
222
223
223 %timeit range(1000)
224 %timeit range(1000)
224
225
225 Cell magics are prefixed with a double %%, and they are functions that get as
226 Cell magics are prefixed with a double %%, and they are functions that get as
226 an argument not only the rest of the line, but also the lines below it in a
227 an argument not only the rest of the line, but also the lines below it in a
227 separate argument. These magics are called with two arguments: the rest of the
228 separate argument. These magics are called with two arguments: the rest of the
228 call line and the body of the cell, consisting of the lines below the first.
229 call line and the body of the cell, consisting of the lines below the first.
229 For example::
230 For example::
230
231
231 %%timeit x = numpy.random.randn((100, 100))
232 %%timeit x = numpy.random.randn((100, 100))
232 numpy.linalg.svd(x)
233 numpy.linalg.svd(x)
233
234
234 will time the execution of the numpy svd routine, running the assignment of x
235 will time the execution of the numpy svd routine, running the assignment of x
235 as part of the setup phase, which is not timed.
236 as part of the setup phase, which is not timed.
236
237
237 In a line-oriented client (the terminal or Qt console IPython), starting a new
238 In a line-oriented client (the terminal or Qt console IPython), starting a new
238 input with %% will automatically enter cell mode, and IPython will continue
239 input with %% will automatically enter cell mode, and IPython will continue
239 reading input until a blank line is given. In the notebook, simply type the
240 reading input until a blank line is given. In the notebook, simply type the
240 whole cell as one entity, but keep in mind that the %% escape can only be at
241 whole cell as one entity, but keep in mind that the %% escape can only be at
241 the very start of the cell.
242 the very start of the cell.
242
243
243 NOTE: If you have 'automagic' enabled (via the command line option or with the
244 NOTE: If you have 'automagic' enabled (via the command line option or with the
244 %automagic function), you don't need to type in the % explicitly for line
245 %automagic function), you don't need to type in the % explicitly for line
245 magics; cell magics always require an explicit '%%' escape. By default,
246 magics; cell magics always require an explicit '%%' escape. By default,
246 IPython ships with automagic on, so you should only rarely need the % escape.
247 IPython ships with automagic on, so you should only rarely need the % escape.
247
248
248 Example: typing '%cd mydir' (without the quotes) changes your working directory
249 Example: typing '%cd mydir' (without the quotes) changes your working directory
249 to 'mydir', if it exists.
250 to 'mydir', if it exists.
250
251
251 For a list of the available magic functions, use %lsmagic. For a description
252 For a list of the available magic functions, use %lsmagic. For a description
252 of any of them, type %magic_name?, e.g. '%cd?'.
253 of any of them, type %magic_name?, e.g. '%cd?'.
253
254
254 Currently the magic system has the following functions:""",
255 Currently the magic system has the following functions:""",
255 magic_docs,
256 magic_docs,
256 "Summary of magic functions (from %slsmagic):" % magic_escapes['line'],
257 "Summary of magic functions (from %slsmagic):" % magic_escapes['line'],
257 str(self.lsmagic()),
258 str(self.lsmagic()),
258 ]
259 ]
259 page.page('\n'.join(out))
260 page.page('\n'.join(out))
260
261
261
262
262 @line_magic
263 @line_magic
263 def page(self, parameter_s=''):
264 def page(self, parameter_s=''):
264 """Pretty print the object and display it through a pager.
265 """Pretty print the object and display it through a pager.
265
266
266 %page [options] OBJECT
267 %page [options] OBJECT
267
268
268 If no object is given, use _ (last output).
269 If no object is given, use _ (last output).
269
270
270 Options:
271 Options:
271
272
272 -r: page str(object), don't pretty-print it."""
273 -r: page str(object), don't pretty-print it."""
273
274
274 # After a function contributed by Olivier Aubert, slightly modified.
275 # After a function contributed by Olivier Aubert, slightly modified.
275
276
276 # Process options/args
277 # Process options/args
277 opts, args = self.parse_options(parameter_s, 'r')
278 opts, args = self.parse_options(parameter_s, 'r')
278 raw = 'r' in opts
279 raw = 'r' in opts
279
280
280 oname = args and args or '_'
281 oname = args and args or '_'
281 info = self.shell._ofind(oname)
282 info = self.shell._ofind(oname)
282 if info['found']:
283 if info['found']:
283 txt = (raw and str or pformat)( info['obj'] )
284 txt = (raw and str or pformat)( info['obj'] )
284 page.page(txt)
285 page.page(txt)
285 else:
286 else:
286 print('Object `%s` not found' % oname)
287 print('Object `%s` not found' % oname)
287
288
288 @line_magic
289 @line_magic
289 def profile(self, parameter_s=''):
290 def profile(self, parameter_s=''):
290 """Print your currently active IPython profile.
291 """Print your currently active IPython profile.
291
292
292 See Also
293 See Also
293 --------
294 --------
294 prun : run code using the Python profiler
295 prun : run code using the Python profiler
295 (:meth:`~IPython.core.magics.execution.ExecutionMagics.prun`)
296 (:meth:`~IPython.core.magics.execution.ExecutionMagics.prun`)
296 """
297 """
297 warn("%profile is now deprecated. Please use get_ipython().profile instead.")
298 warn("%profile is now deprecated. Please use get_ipython().profile instead.")
298 from IPython.core.application import BaseIPythonApplication
299 from IPython.core.application import BaseIPythonApplication
299 if BaseIPythonApplication.initialized():
300 if BaseIPythonApplication.initialized():
300 print(BaseIPythonApplication.instance().profile)
301 print(BaseIPythonApplication.instance().profile)
301 else:
302 else:
302 error("profile is an application-level value, but you don't appear to be in an IPython application")
303 error("profile is an application-level value, but you don't appear to be in an IPython application")
303
304
304 @line_magic
305 @line_magic
305 def pprint(self, parameter_s=''):
306 def pprint(self, parameter_s=''):
306 """Toggle pretty printing on/off."""
307 """Toggle pretty printing on/off."""
307 ptformatter = self.shell.display_formatter.formatters['text/plain']
308 ptformatter = self.shell.display_formatter.formatters['text/plain']
308 ptformatter.pprint = bool(1 - ptformatter.pprint)
309 ptformatter.pprint = bool(1 - ptformatter.pprint)
309 print('Pretty printing has been turned',
310 print('Pretty printing has been turned',
310 ['OFF','ON'][ptformatter.pprint])
311 ['OFF','ON'][ptformatter.pprint])
311
312
312 @line_magic
313 @line_magic
313 def colors(self, parameter_s=''):
314 def colors(self, parameter_s=''):
314 """Switch color scheme for prompts, info system and exception handlers.
315 """Switch color scheme for prompts, info system and exception handlers.
315
316
316 Currently implemented schemes: NoColor, Linux, LightBG.
317 Currently implemented schemes: NoColor, Linux, LightBG.
317
318
318 Color scheme names are not case-sensitive.
319 Color scheme names are not case-sensitive.
319
320
320 Examples
321 Examples
321 --------
322 --------
322 To get a plain black and white terminal::
323 To get a plain black and white terminal::
323
324
324 %colors nocolor
325 %colors nocolor
325 """
326 """
326 def color_switch_err(name):
327 def color_switch_err(name):
327 warn('Error changing %s color schemes.\n%s' %
328 warn('Error changing %s color schemes.\n%s' %
328 (name, sys.exc_info()[1]))
329 (name, sys.exc_info()[1]))
329
330
330
331
331 new_scheme = parameter_s.strip()
332 new_scheme = parameter_s.strip()
332 if not new_scheme:
333 if not new_scheme:
333 raise UsageError(
334 raise UsageError(
334 "%colors: you must specify a color scheme. See '%colors?'")
335 "%colors: you must specify a color scheme. See '%colors?'")
335 # local shortcut
336 # local shortcut
336 shell = self.shell
337 shell = self.shell
337
338
338
339
339
340
340 if not shell.colors_force:
341 if not shell.colors_force:
341 if sys.platform in {'win32', 'cli'}:
342 if sys.platform in {'win32', 'cli'}:
342 import IPython.utils.rlineimpl as readline
343 import IPython.utils.rlineimpl as readline
343 if not readline.have_readline:
344 if not readline.have_readline:
344 msg = """\
345 msg = """\
345 Proper color support under MS Windows requires the pyreadline library.
346 Proper color support under MS Windows requires the pyreadline library.
346 You can find it at:
347 You can find it at:
347 http://ipython.org/pyreadline.html
348 http://ipython.org/pyreadline.html
348
349
349 Defaulting color scheme to 'NoColor'"""
350 Defaulting color scheme to 'NoColor'"""
350 new_scheme = 'NoColor'
351 new_scheme = 'NoColor'
351 warn(msg)
352 warn(msg)
352
353
353 elif not shell.has_readline:
354 elif not shell.has_readline:
354 # Coloured prompts get messed up without readline
355 # Coloured prompts get messed up without readline
355 # Will remove this check after switching to prompt_toolkit
356 # Will remove this check after switching to prompt_toolkit
356 new_scheme = 'NoColor'
357 new_scheme = 'NoColor'
357
358
358 # Set prompt colors
359 # Set prompt colors
359 try:
360 try:
360 shell.prompt_manager.color_scheme = new_scheme
361 shell.prompt_manager.color_scheme = new_scheme
361 except:
362 except:
362 color_switch_err('prompt')
363 color_switch_err('prompt')
363 else:
364 else:
364 shell.colors = \
365 shell.colors = \
365 shell.prompt_manager.color_scheme_table.active_scheme_name
366 shell.prompt_manager.color_scheme_table.active_scheme_name
366 # Set exception colors
367 # Set exception colors
367 try:
368 try:
368 shell.InteractiveTB.set_colors(scheme = new_scheme)
369 shell.InteractiveTB.set_colors(scheme = new_scheme)
369 shell.SyntaxTB.set_colors(scheme = new_scheme)
370 shell.SyntaxTB.set_colors(scheme = new_scheme)
370 except:
371 except:
371 color_switch_err('exception')
372 color_switch_err('exception')
372
373
373 # Set info (for 'object?') colors
374 # Set info (for 'object?') colors
374 if shell.color_info:
375 if shell.color_info:
375 try:
376 try:
376 shell.inspector.set_active_scheme(new_scheme)
377 shell.inspector.set_active_scheme(new_scheme)
377 except:
378 except:
378 color_switch_err('object inspector')
379 color_switch_err('object inspector')
379 else:
380 else:
380 shell.inspector.set_active_scheme('NoColor')
381 shell.inspector.set_active_scheme('NoColor')
381
382
382 @line_magic
383 @line_magic
383 def xmode(self, parameter_s=''):
384 def xmode(self, parameter_s=''):
384 """Switch modes for the exception handlers.
385 """Switch modes for the exception handlers.
385
386
386 Valid modes: Plain, Context and Verbose.
387 Valid modes: Plain, Context and Verbose.
387
388
388 If called without arguments, acts as a toggle."""
389 If called without arguments, acts as a toggle."""
389
390
390 def xmode_switch_err(name):
391 def xmode_switch_err(name):
391 warn('Error changing %s exception modes.\n%s' %
392 warn('Error changing %s exception modes.\n%s' %
392 (name,sys.exc_info()[1]))
393 (name,sys.exc_info()[1]))
393
394
394 shell = self.shell
395 shell = self.shell
395 new_mode = parameter_s.strip().capitalize()
396 new_mode = parameter_s.strip().capitalize()
396 try:
397 try:
397 shell.InteractiveTB.set_mode(mode=new_mode)
398 shell.InteractiveTB.set_mode(mode=new_mode)
398 print('Exception reporting mode:',shell.InteractiveTB.mode)
399 print('Exception reporting mode:',shell.InteractiveTB.mode)
399 except:
400 except:
400 xmode_switch_err('user')
401 xmode_switch_err('user')
401
402
402 @line_magic
403 @line_magic
403 def quickref(self,arg):
404 def quickref(self,arg):
404 """ Show a quick reference sheet """
405 """ Show a quick reference sheet """
405 from IPython.core.usage import quick_reference
406 from IPython.core.usage import quick_reference
406 qr = quick_reference + self._magic_docs(brief=True)
407 qr = quick_reference + self._magic_docs(brief=True)
407 page.page(qr)
408 page.page(qr)
408
409
409 @line_magic
410 @line_magic
410 def doctest_mode(self, parameter_s=''):
411 def doctest_mode(self, parameter_s=''):
411 """Toggle doctest mode on and off.
412 """Toggle doctest mode on and off.
412
413
413 This mode is intended to make IPython behave as much as possible like a
414 This mode is intended to make IPython behave as much as possible like a
414 plain Python shell, from the perspective of how its prompts, exceptions
415 plain Python shell, from the perspective of how its prompts, exceptions
415 and output look. This makes it easy to copy and paste parts of a
416 and output look. This makes it easy to copy and paste parts of a
416 session into doctests. It does so by:
417 session into doctests. It does so by:
417
418
418 - Changing the prompts to the classic ``>>>`` ones.
419 - Changing the prompts to the classic ``>>>`` ones.
419 - Changing the exception reporting mode to 'Plain'.
420 - Changing the exception reporting mode to 'Plain'.
420 - Disabling pretty-printing of output.
421 - Disabling pretty-printing of output.
421
422
422 Note that IPython also supports the pasting of code snippets that have
423 Note that IPython also supports the pasting of code snippets that have
423 leading '>>>' and '...' prompts in them. This means that you can paste
424 leading '>>>' and '...' prompts in them. This means that you can paste
424 doctests from files or docstrings (even if they have leading
425 doctests from files or docstrings (even if they have leading
425 whitespace), and the code will execute correctly. You can then use
426 whitespace), and the code will execute correctly. You can then use
426 '%history -t' to see the translated history; this will give you the
427 '%history -t' to see the translated history; this will give you the
427 input after removal of all the leading prompts and whitespace, which
428 input after removal of all the leading prompts and whitespace, which
428 can be pasted back into an editor.
429 can be pasted back into an editor.
429
430
430 With these features, you can switch into this mode easily whenever you
431 With these features, you can switch into this mode easily whenever you
431 need to do testing and changes to doctests, without having to leave
432 need to do testing and changes to doctests, without having to leave
432 your existing IPython session.
433 your existing IPython session.
433 """
434 """
434
435
435 # Shorthands
436 # Shorthands
436 shell = self.shell
437 shell = self.shell
437 pm = shell.prompt_manager
438 pm = shell.prompt_manager
438 meta = shell.meta
439 meta = shell.meta
439 disp_formatter = self.shell.display_formatter
440 disp_formatter = self.shell.display_formatter
440 ptformatter = disp_formatter.formatters['text/plain']
441 ptformatter = disp_formatter.formatters['text/plain']
441 # dstore is a data store kept in the instance metadata bag to track any
442 # dstore is a data store kept in the instance metadata bag to track any
442 # changes we make, so we can undo them later.
443 # changes we make, so we can undo them later.
443 dstore = meta.setdefault('doctest_mode',Struct())
444 dstore = meta.setdefault('doctest_mode',Struct())
444 save_dstore = dstore.setdefault
445 save_dstore = dstore.setdefault
445
446
446 # save a few values we'll need to recover later
447 # save a few values we'll need to recover later
447 mode = save_dstore('mode',False)
448 mode = save_dstore('mode',False)
448 save_dstore('rc_pprint',ptformatter.pprint)
449 save_dstore('rc_pprint',ptformatter.pprint)
449 save_dstore('xmode',shell.InteractiveTB.mode)
450 save_dstore('xmode',shell.InteractiveTB.mode)
450 save_dstore('rc_separate_out',shell.separate_out)
451 save_dstore('rc_separate_out',shell.separate_out)
451 save_dstore('rc_separate_out2',shell.separate_out2)
452 save_dstore('rc_separate_out2',shell.separate_out2)
452 save_dstore('rc_prompts_pad_left',pm.justify)
453 save_dstore('rc_prompts_pad_left',pm.justify)
453 save_dstore('rc_separate_in',shell.separate_in)
454 save_dstore('rc_separate_in',shell.separate_in)
454 save_dstore('rc_active_types',disp_formatter.active_types)
455 save_dstore('rc_active_types',disp_formatter.active_types)
455 save_dstore('prompt_templates',(pm.in_template, pm.in2_template, pm.out_template))
456 save_dstore('prompt_templates',(pm.in_template, pm.in2_template, pm.out_template))
456
457
457 if not mode:
458 if not mode:
458 # turn on
459 # turn on
459 pm.in_template = '>>> '
460 pm.in_template = '>>> '
460 pm.in2_template = '... '
461 pm.in2_template = '... '
461 pm.out_template = ''
462 pm.out_template = ''
462
463
463 # Prompt separators like plain python
464 # Prompt separators like plain python
464 shell.separate_in = ''
465 shell.separate_in = ''
465 shell.separate_out = ''
466 shell.separate_out = ''
466 shell.separate_out2 = ''
467 shell.separate_out2 = ''
467
468
468 pm.justify = False
469 pm.justify = False
469
470
470 ptformatter.pprint = False
471 ptformatter.pprint = False
471 disp_formatter.active_types = ['text/plain']
472 disp_formatter.active_types = ['text/plain']
472
473
473 shell.magic('xmode Plain')
474 shell.magic('xmode Plain')
474 else:
475 else:
475 # turn off
476 # turn off
476 pm.in_template, pm.in2_template, pm.out_template = dstore.prompt_templates
477 pm.in_template, pm.in2_template, pm.out_template = dstore.prompt_templates
477
478
478 shell.separate_in = dstore.rc_separate_in
479 shell.separate_in = dstore.rc_separate_in
479
480
480 shell.separate_out = dstore.rc_separate_out
481 shell.separate_out = dstore.rc_separate_out
481 shell.separate_out2 = dstore.rc_separate_out2
482 shell.separate_out2 = dstore.rc_separate_out2
482
483
483 pm.justify = dstore.rc_prompts_pad_left
484 pm.justify = dstore.rc_prompts_pad_left
484
485
485 ptformatter.pprint = dstore.rc_pprint
486 ptformatter.pprint = dstore.rc_pprint
486 disp_formatter.active_types = dstore.rc_active_types
487 disp_formatter.active_types = dstore.rc_active_types
487
488
488 shell.magic('xmode ' + dstore.xmode)
489 shell.magic('xmode ' + dstore.xmode)
489
490
490 # Store new mode and inform
491 # Store new mode and inform
491 dstore.mode = bool(1-int(mode))
492 dstore.mode = bool(1-int(mode))
492 mode_label = ['OFF','ON'][dstore.mode]
493 mode_label = ['OFF','ON'][dstore.mode]
493 print('Doctest mode is:', mode_label)
494 print('Doctest mode is:', mode_label)
494
495
495 @line_magic
496 @line_magic
496 def gui(self, parameter_s=''):
497 def gui(self, parameter_s=''):
497 """Enable or disable IPython GUI event loop integration.
498 """Enable or disable IPython GUI event loop integration.
498
499
499 %gui [GUINAME]
500 %gui [GUINAME]
500
501
501 This magic replaces IPython's threaded shells that were activated
502 This magic replaces IPython's threaded shells that were activated
502 using the (pylab/wthread/etc.) command line flags. GUI toolkits
503 using the (pylab/wthread/etc.) command line flags. GUI toolkits
503 can now be enabled at runtime and keyboard
504 can now be enabled at runtime and keyboard
504 interrupts should work without any problems. The following toolkits
505 interrupts should work without any problems. The following toolkits
505 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
506 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
506
507
507 %gui wx # enable wxPython event loop integration
508 %gui wx # enable wxPython event loop integration
508 %gui qt4|qt # enable PyQt4 event loop integration
509 %gui qt4|qt # enable PyQt4 event loop integration
509 %gui qt5 # enable PyQt5 event loop integration
510 %gui qt5 # enable PyQt5 event loop integration
510 %gui gtk # enable PyGTK event loop integration
511 %gui gtk # enable PyGTK event loop integration
511 %gui gtk3 # enable Gtk3 event loop integration
512 %gui gtk3 # enable Gtk3 event loop integration
512 %gui tk # enable Tk event loop integration
513 %gui tk # enable Tk event loop integration
513 %gui osx # enable Cocoa event loop integration
514 %gui osx # enable Cocoa event loop integration
514 # (requires %matplotlib 1.1)
515 # (requires %matplotlib 1.1)
515 %gui # disable all event loop integration
516 %gui # disable all event loop integration
516
517
517 WARNING: after any of these has been called you can simply create
518 WARNING: after any of these has been called you can simply create
518 an application object, but DO NOT start the event loop yourself, as
519 an application object, but DO NOT start the event loop yourself, as
519 we have already handled that.
520 we have already handled that.
520 """
521 """
521 opts, arg = self.parse_options(parameter_s, '')
522 opts, arg = self.parse_options(parameter_s, '')
522 if arg=='': arg = None
523 if arg=='': arg = None
523 try:
524 try:
524 return self.shell.enable_gui(arg)
525 return self.shell.enable_gui(arg)
525 except Exception as e:
526 except Exception as e:
526 # print simple error message, rather than traceback if we can't
527 # print simple error message, rather than traceback if we can't
527 # hook up the GUI
528 # hook up the GUI
528 error(str(e))
529 error(str(e))
529
530
530 @skip_doctest
531 @skip_doctest
531 @line_magic
532 @line_magic
532 def precision(self, s=''):
533 def precision(self, s=''):
533 """Set floating point precision for pretty printing.
534 """Set floating point precision for pretty printing.
534
535
535 Can set either integer precision or a format string.
536 Can set either integer precision or a format string.
536
537
537 If numpy has been imported and precision is an int,
538 If numpy has been imported and precision is an int,
538 numpy display precision will also be set, via ``numpy.set_printoptions``.
539 numpy display precision will also be set, via ``numpy.set_printoptions``.
539
540
540 If no argument is given, defaults will be restored.
541 If no argument is given, defaults will be restored.
541
542
542 Examples
543 Examples
543 --------
544 --------
544 ::
545 ::
545
546
546 In [1]: from math import pi
547 In [1]: from math import pi
547
548
548 In [2]: %precision 3
549 In [2]: %precision 3
549 Out[2]: u'%.3f'
550 Out[2]: u'%.3f'
550
551
551 In [3]: pi
552 In [3]: pi
552 Out[3]: 3.142
553 Out[3]: 3.142
553
554
554 In [4]: %precision %i
555 In [4]: %precision %i
555 Out[4]: u'%i'
556 Out[4]: u'%i'
556
557
557 In [5]: pi
558 In [5]: pi
558 Out[5]: 3
559 Out[5]: 3
559
560
560 In [6]: %precision %e
561 In [6]: %precision %e
561 Out[6]: u'%e'
562 Out[6]: u'%e'
562
563
563 In [7]: pi**10
564 In [7]: pi**10
564 Out[7]: 9.364805e+04
565 Out[7]: 9.364805e+04
565
566
566 In [8]: %precision
567 In [8]: %precision
567 Out[8]: u'%r'
568 Out[8]: u'%r'
568
569
569 In [9]: pi**10
570 In [9]: pi**10
570 Out[9]: 93648.047476082982
571 Out[9]: 93648.047476082982
571 """
572 """
572 ptformatter = self.shell.display_formatter.formatters['text/plain']
573 ptformatter = self.shell.display_formatter.formatters['text/plain']
573 ptformatter.float_precision = s
574 ptformatter.float_precision = s
574 return ptformatter.float_format
575 return ptformatter.float_format
575
576
576 @magic_arguments.magic_arguments()
577 @magic_arguments.magic_arguments()
577 @magic_arguments.argument(
578 @magic_arguments.argument(
578 '-e', '--export', action='store_true', default=False,
579 '-e', '--export', action='store_true', default=False,
579 help='Export IPython history as a notebook. The filename argument '
580 help='Export IPython history as a notebook. The filename argument '
580 'is used to specify the notebook name and format. For example '
581 'is used to specify the notebook name and format. For example '
581 'a filename of notebook.ipynb will result in a notebook name '
582 'a filename of notebook.ipynb will result in a notebook name '
582 'of "notebook" and a format of "json". Likewise using a ".py" '
583 'of "notebook" and a format of "json". Likewise using a ".py" '
583 'file extension will write the notebook as a Python script'
584 'file extension will write the notebook as a Python script'
584 )
585 )
585 @magic_arguments.argument(
586 @magic_arguments.argument(
586 'filename', type=unicode_type,
587 'filename', type=unicode_type,
587 help='Notebook name or filename'
588 help='Notebook name or filename'
588 )
589 )
589 @line_magic
590 @line_magic
590 def notebook(self, s):
591 def notebook(self, s):
591 """Export and convert IPython notebooks.
592 """Export and convert IPython notebooks.
592
593
593 This function can export the current IPython history to a notebook file.
594 This function can export the current IPython history to a notebook file.
594 For example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb".
595 For example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb".
595 To export the history to "foo.py" do "%notebook -e foo.py".
596 To export the history to "foo.py" do "%notebook -e foo.py".
596 """
597 """
597 args = magic_arguments.parse_argstring(self.notebook, s)
598 args = magic_arguments.parse_argstring(self.notebook, s)
598
599
599 from nbformat import write, v4
600 from nbformat import write, v4
600 args.filename = unquote_filename(args.filename)
601 args.filename = unquote_filename(args.filename)
601 if args.export:
602 if args.export:
602 cells = []
603 cells = []
603 hist = list(self.shell.history_manager.get_range())
604 hist = list(self.shell.history_manager.get_range())
604 if(len(hist)<=1):
605 if(len(hist)<=1):
605 raise ValueError('History is empty, cannot export')
606 raise ValueError('History is empty, cannot export')
606 for session, execution_count, source in hist[:-1]:
607 for session, execution_count, source in hist[:-1]:
607 cells.append(v4.new_code_cell(
608 cells.append(v4.new_code_cell(
608 execution_count=execution_count,
609 execution_count=execution_count,
609 source=source
610 source=source
610 ))
611 ))
611 nb = v4.new_notebook(cells=cells)
612 nb = v4.new_notebook(cells=cells)
612 with io.open(args.filename, 'w', encoding='utf-8') as f:
613 with io.open(args.filename, 'w', encoding='utf-8') as f:
613 write(nb, f, version=4)
614 write(nb, f, version=4)
@@ -1,716 +1,717 b''
1 """Implementation of code management magic functions.
1 """Implementation of code management magic functions.
2 """
2 """
3 from __future__ import print_function
3 from __future__ import print_function
4 from __future__ import absolute_import
4 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
5 # Copyright (c) 2012 The IPython Development Team.
6 # Copyright (c) 2012 The IPython Development Team.
6 #
7 #
7 # Distributed under the terms of the Modified BSD License.
8 # Distributed under the terms of the Modified BSD License.
8 #
9 #
9 # The full license is in the file COPYING.txt, distributed with this software.
10 # The full license is in the file COPYING.txt, distributed with this software.
10 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
11
12
12 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
13 # Imports
14 # Imports
14 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
15
16
16 # Stdlib
17 # Stdlib
17 import inspect
18 import inspect
18 import io
19 import io
19 import os
20 import os
20 import re
21 import re
21 import sys
22 import sys
22 import ast
23 import ast
23 from itertools import chain
24 from itertools import chain
24
25
25 # Our own packages
26 # Our own packages
26 from IPython.core.error import TryNext, StdinNotImplementedError, UsageError
27 from IPython.core.error import TryNext, StdinNotImplementedError, UsageError
27 from IPython.core.macro import Macro
28 from IPython.core.macro import Macro
28 from IPython.core.magic import Magics, magics_class, line_magic
29 from IPython.core.magic import Magics, magics_class, line_magic
29 from IPython.core.oinspect import find_file, find_source_lines
30 from IPython.core.oinspect import find_file, find_source_lines
30 from IPython.testing.skipdoctest import skip_doctest
31 from IPython.testing.skipdoctest import skip_doctest
31 from IPython.utils import py3compat
32 from IPython.utils import py3compat
32 from IPython.utils.py3compat import string_types
33 from IPython.utils.py3compat import string_types
33 from IPython.utils.contexts import preserve_keys
34 from IPython.utils.contexts import preserve_keys
34 from IPython.utils.path import get_py_filename, unquote_filename
35 from IPython.utils.path import get_py_filename, unquote_filename
35 from warnings import warn
36 from warnings import warn
36 from logging import error
37 from logging import error
37 from IPython.utils.text import get_text_list
38 from IPython.utils.text import get_text_list
38
39
39 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
40 # Magic implementation classes
41 # Magic implementation classes
41 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
42
43
43 # Used for exception handling in magic_edit
44 # Used for exception handling in magic_edit
44 class MacroToEdit(ValueError): pass
45 class MacroToEdit(ValueError): pass
45
46
46 ipython_input_pat = re.compile(r"<ipython\-input\-(\d+)-[a-z\d]+>$")
47 ipython_input_pat = re.compile(r"<ipython\-input\-(\d+)-[a-z\d]+>$")
47
48
48 # To match, e.g. 8-10 1:5 :10 3-
49 # To match, e.g. 8-10 1:5 :10 3-
49 range_re = re.compile(r"""
50 range_re = re.compile(r"""
50 (?P<start>\d+)?
51 (?P<start>\d+)?
51 ((?P<sep>[\-:])
52 ((?P<sep>[\-:])
52 (?P<end>\d+)?)?
53 (?P<end>\d+)?)?
53 $""", re.VERBOSE)
54 $""", re.VERBOSE)
54
55
55
56
56 def extract_code_ranges(ranges_str):
57 def extract_code_ranges(ranges_str):
57 """Turn a string of range for %%load into 2-tuples of (start, stop)
58 """Turn a string of range for %%load into 2-tuples of (start, stop)
58 ready to use as a slice of the content splitted by lines.
59 ready to use as a slice of the content splitted by lines.
59
60
60 Examples
61 Examples
61 --------
62 --------
62 list(extract_input_ranges("5-10 2"))
63 list(extract_input_ranges("5-10 2"))
63 [(4, 10), (1, 2)]
64 [(4, 10), (1, 2)]
64 """
65 """
65 for range_str in ranges_str.split():
66 for range_str in ranges_str.split():
66 rmatch = range_re.match(range_str)
67 rmatch = range_re.match(range_str)
67 if not rmatch:
68 if not rmatch:
68 continue
69 continue
69 sep = rmatch.group("sep")
70 sep = rmatch.group("sep")
70 start = rmatch.group("start")
71 start = rmatch.group("start")
71 end = rmatch.group("end")
72 end = rmatch.group("end")
72
73
73 if sep == '-':
74 if sep == '-':
74 start = int(start) - 1 if start else None
75 start = int(start) - 1 if start else None
75 end = int(end) if end else None
76 end = int(end) if end else None
76 elif sep == ':':
77 elif sep == ':':
77 start = int(start) - 1 if start else None
78 start = int(start) - 1 if start else None
78 end = int(end) - 1 if end else None
79 end = int(end) - 1 if end else None
79 else:
80 else:
80 end = int(start)
81 end = int(start)
81 start = int(start) - 1
82 start = int(start) - 1
82 yield (start, end)
83 yield (start, end)
83
84
84
85
85 @skip_doctest
86 @skip_doctest
86 def extract_symbols(code, symbols):
87 def extract_symbols(code, symbols):
87 """
88 """
88 Return a tuple (blocks, not_found)
89 Return a tuple (blocks, not_found)
89 where ``blocks`` is a list of code fragments
90 where ``blocks`` is a list of code fragments
90 for each symbol parsed from code, and ``not_found`` are
91 for each symbol parsed from code, and ``not_found`` are
91 symbols not found in the code.
92 symbols not found in the code.
92
93
93 For example::
94 For example::
94
95
95 >>> code = '''a = 10
96 >>> code = '''a = 10
96
97
97 def b(): return 42
98 def b(): return 42
98
99
99 class A: pass'''
100 class A: pass'''
100
101
101 >>> extract_symbols(code, 'A,b,z')
102 >>> extract_symbols(code, 'A,b,z')
102 (["class A: pass", "def b(): return 42"], ['z'])
103 (["class A: pass", "def b(): return 42"], ['z'])
103 """
104 """
104 symbols = symbols.split(',')
105 symbols = symbols.split(',')
105
106
106 # this will raise SyntaxError if code isn't valid Python
107 # this will raise SyntaxError if code isn't valid Python
107 py_code = ast.parse(code)
108 py_code = ast.parse(code)
108
109
109 marks = [(getattr(s, 'name', None), s.lineno) for s in py_code.body]
110 marks = [(getattr(s, 'name', None), s.lineno) for s in py_code.body]
110 code = code.split('\n')
111 code = code.split('\n')
111
112
112 symbols_lines = {}
113 symbols_lines = {}
113
114
114 # we already know the start_lineno of each symbol (marks).
115 # we already know the start_lineno of each symbol (marks).
115 # To find each end_lineno, we traverse in reverse order until each
116 # To find each end_lineno, we traverse in reverse order until each
116 # non-blank line
117 # non-blank line
117 end = len(code)
118 end = len(code)
118 for name, start in reversed(marks):
119 for name, start in reversed(marks):
119 while not code[end - 1].strip():
120 while not code[end - 1].strip():
120 end -= 1
121 end -= 1
121 if name:
122 if name:
122 symbols_lines[name] = (start - 1, end)
123 symbols_lines[name] = (start - 1, end)
123 end = start - 1
124 end = start - 1
124
125
125 # Now symbols_lines is a map
126 # Now symbols_lines is a map
126 # {'symbol_name': (start_lineno, end_lineno), ...}
127 # {'symbol_name': (start_lineno, end_lineno), ...}
127
128
128 # fill a list with chunks of codes for each requested symbol
129 # fill a list with chunks of codes for each requested symbol
129 blocks = []
130 blocks = []
130 not_found = []
131 not_found = []
131 for symbol in symbols:
132 for symbol in symbols:
132 if symbol in symbols_lines:
133 if symbol in symbols_lines:
133 start, end = symbols_lines[symbol]
134 start, end = symbols_lines[symbol]
134 blocks.append('\n'.join(code[start:end]) + '\n')
135 blocks.append('\n'.join(code[start:end]) + '\n')
135 else:
136 else:
136 not_found.append(symbol)
137 not_found.append(symbol)
137
138
138 return blocks, not_found
139 return blocks, not_found
139
140
140
141
141 class InteractivelyDefined(Exception):
142 class InteractivelyDefined(Exception):
142 """Exception for interactively defined variable in magic_edit"""
143 """Exception for interactively defined variable in magic_edit"""
143 def __init__(self, index):
144 def __init__(self, index):
144 self.index = index
145 self.index = index
145
146
146
147
147 @magics_class
148 @magics_class
148 class CodeMagics(Magics):
149 class CodeMagics(Magics):
149 """Magics related to code management (loading, saving, editing, ...)."""
150 """Magics related to code management (loading, saving, editing, ...)."""
150
151
151 def __init__(self, *args, **kwargs):
152 def __init__(self, *args, **kwargs):
152 self._knowntemps = set()
153 self._knowntemps = set()
153 super(CodeMagics, self).__init__(*args, **kwargs)
154 super(CodeMagics, self).__init__(*args, **kwargs)
154
155
155 @line_magic
156 @line_magic
156 def save(self, parameter_s=''):
157 def save(self, parameter_s=''):
157 """Save a set of lines or a macro to a given filename.
158 """Save a set of lines or a macro to a given filename.
158
159
159 Usage:\\
160 Usage:\\
160 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
161 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
161
162
162 Options:
163 Options:
163
164
164 -r: use 'raw' input. By default, the 'processed' history is used,
165 -r: use 'raw' input. By default, the 'processed' history is used,
165 so that magics are loaded in their transformed version to valid
166 so that magics are loaded in their transformed version to valid
166 Python. If this option is given, the raw input as typed as the
167 Python. If this option is given, the raw input as typed as the
167 command line is used instead.
168 command line is used instead.
168
169
169 -f: force overwrite. If file exists, %save will prompt for overwrite
170 -f: force overwrite. If file exists, %save will prompt for overwrite
170 unless -f is given.
171 unless -f is given.
171
172
172 -a: append to the file instead of overwriting it.
173 -a: append to the file instead of overwriting it.
173
174
174 This function uses the same syntax as %history for input ranges,
175 This function uses the same syntax as %history for input ranges,
175 then saves the lines to the filename you specify.
176 then saves the lines to the filename you specify.
176
177
177 It adds a '.py' extension to the file if you don't do so yourself, and
178 It adds a '.py' extension to the file if you don't do so yourself, and
178 it asks for confirmation before overwriting existing files.
179 it asks for confirmation before overwriting existing files.
179
180
180 If `-r` option is used, the default extension is `.ipy`.
181 If `-r` option is used, the default extension is `.ipy`.
181 """
182 """
182
183
183 opts,args = self.parse_options(parameter_s,'fra',mode='list')
184 opts,args = self.parse_options(parameter_s,'fra',mode='list')
184 if not args:
185 if not args:
185 raise UsageError('Missing filename.')
186 raise UsageError('Missing filename.')
186 raw = 'r' in opts
187 raw = 'r' in opts
187 force = 'f' in opts
188 force = 'f' in opts
188 append = 'a' in opts
189 append = 'a' in opts
189 mode = 'a' if append else 'w'
190 mode = 'a' if append else 'w'
190 ext = u'.ipy' if raw else u'.py'
191 ext = u'.ipy' if raw else u'.py'
191 fname, codefrom = unquote_filename(args[0]), " ".join(args[1:])
192 fname, codefrom = unquote_filename(args[0]), " ".join(args[1:])
192 if not fname.endswith((u'.py',u'.ipy')):
193 if not fname.endswith((u'.py',u'.ipy')):
193 fname += ext
194 fname += ext
194 file_exists = os.path.isfile(fname)
195 file_exists = os.path.isfile(fname)
195 if file_exists and not force and not append:
196 if file_exists and not force and not append:
196 try:
197 try:
197 overwrite = self.shell.ask_yes_no('File `%s` exists. Overwrite (y/[N])? ' % fname, default='n')
198 overwrite = self.shell.ask_yes_no('File `%s` exists. Overwrite (y/[N])? ' % fname, default='n')
198 except StdinNotImplementedError:
199 except StdinNotImplementedError:
199 print("File `%s` exists. Use `%%save -f %s` to force overwrite" % (fname, parameter_s))
200 print("File `%s` exists. Use `%%save -f %s` to force overwrite" % (fname, parameter_s))
200 return
201 return
201 if not overwrite :
202 if not overwrite :
202 print('Operation cancelled.')
203 print('Operation cancelled.')
203 return
204 return
204 try:
205 try:
205 cmds = self.shell.find_user_code(codefrom,raw)
206 cmds = self.shell.find_user_code(codefrom,raw)
206 except (TypeError, ValueError) as e:
207 except (TypeError, ValueError) as e:
207 print(e.args[0])
208 print(e.args[0])
208 return
209 return
209 out = py3compat.cast_unicode(cmds)
210 out = py3compat.cast_unicode(cmds)
210 with io.open(fname, mode, encoding="utf-8") as f:
211 with io.open(fname, mode, encoding="utf-8") as f:
211 if not file_exists or not append:
212 if not file_exists or not append:
212 f.write(u"# coding: utf-8\n")
213 f.write(u"# coding: utf-8\n")
213 f.write(out)
214 f.write(out)
214 # make sure we end on a newline
215 # make sure we end on a newline
215 if not out.endswith(u'\n'):
216 if not out.endswith(u'\n'):
216 f.write(u'\n')
217 f.write(u'\n')
217 print('The following commands were written to file `%s`:' % fname)
218 print('The following commands were written to file `%s`:' % fname)
218 print(cmds)
219 print(cmds)
219
220
220 @line_magic
221 @line_magic
221 def pastebin(self, parameter_s=''):
222 def pastebin(self, parameter_s=''):
222 """Upload code to Github's Gist paste bin, returning the URL.
223 """Upload code to Github's Gist paste bin, returning the URL.
223
224
224 Usage:\\
225 Usage:\\
225 %pastebin [-d "Custom description"] 1-7
226 %pastebin [-d "Custom description"] 1-7
226
227
227 The argument can be an input history range, a filename, or the name of a
228 The argument can be an input history range, a filename, or the name of a
228 string or macro.
229 string or macro.
229
230
230 Options:
231 Options:
231
232
232 -d: Pass a custom description for the gist. The default will say
233 -d: Pass a custom description for the gist. The default will say
233 "Pasted from IPython".
234 "Pasted from IPython".
234 """
235 """
235 opts, args = self.parse_options(parameter_s, 'd:')
236 opts, args = self.parse_options(parameter_s, 'd:')
236
237
237 try:
238 try:
238 code = self.shell.find_user_code(args)
239 code = self.shell.find_user_code(args)
239 except (ValueError, TypeError) as e:
240 except (ValueError, TypeError) as e:
240 print(e.args[0])
241 print(e.args[0])
241 return
242 return
242
243
243 # Deferred import
244 # Deferred import
244 try:
245 try:
245 from urllib.request import urlopen # Py 3
246 from urllib.request import urlopen # Py 3
246 except ImportError:
247 except ImportError:
247 from urllib2 import urlopen
248 from urllib2 import urlopen
248 import json
249 import json
249 post_data = json.dumps({
250 post_data = json.dumps({
250 "description": opts.get('d', "Pasted from IPython"),
251 "description": opts.get('d', "Pasted from IPython"),
251 "public": True,
252 "public": True,
252 "files": {
253 "files": {
253 "file1.py": {
254 "file1.py": {
254 "content": code
255 "content": code
255 }
256 }
256 }
257 }
257 }).encode('utf-8')
258 }).encode('utf-8')
258
259
259 response = urlopen("https://api.github.com/gists", post_data)
260 response = urlopen("https://api.github.com/gists", post_data)
260 response_data = json.loads(response.read().decode('utf-8'))
261 response_data = json.loads(response.read().decode('utf-8'))
261 return response_data['html_url']
262 return response_data['html_url']
262
263
263 @line_magic
264 @line_magic
264 def loadpy(self, arg_s):
265 def loadpy(self, arg_s):
265 """Alias of `%load`
266 """Alias of `%load`
266
267
267 `%loadpy` has gained some flexibility and dropped the requirement of a `.py`
268 `%loadpy` has gained some flexibility and dropped the requirement of a `.py`
268 extension. So it has been renamed simply into %load. You can look at
269 extension. So it has been renamed simply into %load. You can look at
269 `%load`'s docstring for more info.
270 `%load`'s docstring for more info.
270 """
271 """
271 self.load(arg_s)
272 self.load(arg_s)
272
273
273 @line_magic
274 @line_magic
274 def load(self, arg_s):
275 def load(self, arg_s):
275 """Load code into the current frontend.
276 """Load code into the current frontend.
276
277
277 Usage:\\
278 Usage:\\
278 %load [options] source
279 %load [options] source
279
280
280 where source can be a filename, URL, input history range, macro, or
281 where source can be a filename, URL, input history range, macro, or
281 element in the user namespace
282 element in the user namespace
282
283
283 Options:
284 Options:
284
285
285 -r <lines>: Specify lines or ranges of lines to load from the source.
286 -r <lines>: Specify lines or ranges of lines to load from the source.
286 Ranges could be specified as x-y (x..y) or in python-style x:y
287 Ranges could be specified as x-y (x..y) or in python-style x:y
287 (x..(y-1)). Both limits x and y can be left blank (meaning the
288 (x..(y-1)). Both limits x and y can be left blank (meaning the
288 beginning and end of the file, respectively).
289 beginning and end of the file, respectively).
289
290
290 -s <symbols>: Specify function or classes to load from python source.
291 -s <symbols>: Specify function or classes to load from python source.
291
292
292 -y : Don't ask confirmation for loading source above 200 000 characters.
293 -y : Don't ask confirmation for loading source above 200 000 characters.
293
294
294 -n : Include the user's namespace when searching for source code.
295 -n : Include the user's namespace when searching for source code.
295
296
296 This magic command can either take a local filename, a URL, an history
297 This magic command can either take a local filename, a URL, an history
297 range (see %history) or a macro as argument, it will prompt for
298 range (see %history) or a macro as argument, it will prompt for
298 confirmation before loading source with more than 200 000 characters, unless
299 confirmation before loading source with more than 200 000 characters, unless
299 -y flag is passed or if the frontend does not support raw_input::
300 -y flag is passed or if the frontend does not support raw_input::
300
301
301 %load myscript.py
302 %load myscript.py
302 %load 7-27
303 %load 7-27
303 %load myMacro
304 %load myMacro
304 %load http://www.example.com/myscript.py
305 %load http://www.example.com/myscript.py
305 %load -r 5-10 myscript.py
306 %load -r 5-10 myscript.py
306 %load -r 10-20,30,40: foo.py
307 %load -r 10-20,30,40: foo.py
307 %load -s MyClass,wonder_function myscript.py
308 %load -s MyClass,wonder_function myscript.py
308 %load -n MyClass
309 %load -n MyClass
309 %load -n my_module.wonder_function
310 %load -n my_module.wonder_function
310 """
311 """
311 opts,args = self.parse_options(arg_s,'yns:r:')
312 opts,args = self.parse_options(arg_s,'yns:r:')
312
313
313 if not args:
314 if not args:
314 raise UsageError('Missing filename, URL, input history range, '
315 raise UsageError('Missing filename, URL, input history range, '
315 'macro, or element in the user namespace.')
316 'macro, or element in the user namespace.')
316
317
317 search_ns = 'n' in opts
318 search_ns = 'n' in opts
318
319
319 contents = self.shell.find_user_code(args, search_ns=search_ns)
320 contents = self.shell.find_user_code(args, search_ns=search_ns)
320
321
321 if 's' in opts:
322 if 's' in opts:
322 try:
323 try:
323 blocks, not_found = extract_symbols(contents, opts['s'])
324 blocks, not_found = extract_symbols(contents, opts['s'])
324 except SyntaxError:
325 except SyntaxError:
325 # non python code
326 # non python code
326 error("Unable to parse the input as valid Python code")
327 error("Unable to parse the input as valid Python code")
327 return
328 return
328
329
329 if len(not_found) == 1:
330 if len(not_found) == 1:
330 warn('The symbol `%s` was not found' % not_found[0])
331 warn('The symbol `%s` was not found' % not_found[0])
331 elif len(not_found) > 1:
332 elif len(not_found) > 1:
332 warn('The symbols %s were not found' % get_text_list(not_found,
333 warn('The symbols %s were not found' % get_text_list(not_found,
333 wrap_item_with='`')
334 wrap_item_with='`')
334 )
335 )
335
336
336 contents = '\n'.join(blocks)
337 contents = '\n'.join(blocks)
337
338
338 if 'r' in opts:
339 if 'r' in opts:
339 ranges = opts['r'].replace(',', ' ')
340 ranges = opts['r'].replace(',', ' ')
340 lines = contents.split('\n')
341 lines = contents.split('\n')
341 slices = extract_code_ranges(ranges)
342 slices = extract_code_ranges(ranges)
342 contents = [lines[slice(*slc)] for slc in slices]
343 contents = [lines[slice(*slc)] for slc in slices]
343 contents = '\n'.join(chain.from_iterable(contents))
344 contents = '\n'.join(chain.from_iterable(contents))
344
345
345 l = len(contents)
346 l = len(contents)
346
347
347 # 200 000 is ~ 2500 full 80 caracter lines
348 # 200 000 is ~ 2500 full 80 caracter lines
348 # so in average, more than 5000 lines
349 # so in average, more than 5000 lines
349 if l > 200000 and 'y' not in opts:
350 if l > 200000 and 'y' not in opts:
350 try:
351 try:
351 ans = self.shell.ask_yes_no(("The text you're trying to load seems pretty big"\
352 ans = self.shell.ask_yes_no(("The text you're trying to load seems pretty big"\
352 " (%d characters). Continue (y/[N]) ?" % l), default='n' )
353 " (%d characters). Continue (y/[N]) ?" % l), default='n' )
353 except StdinNotImplementedError:
354 except StdinNotImplementedError:
354 #asume yes if raw input not implemented
355 #asume yes if raw input not implemented
355 ans = True
356 ans = True
356
357
357 if ans is False :
358 if ans is False :
358 print('Operation cancelled.')
359 print('Operation cancelled.')
359 return
360 return
360
361
361 contents = "# %load {}\n".format(arg_s) + contents
362 contents = "# %load {}\n".format(arg_s) + contents
362
363
363 self.shell.set_next_input(contents, replace=True)
364 self.shell.set_next_input(contents, replace=True)
364
365
365 @staticmethod
366 @staticmethod
366 def _find_edit_target(shell, args, opts, last_call):
367 def _find_edit_target(shell, args, opts, last_call):
367 """Utility method used by magic_edit to find what to edit."""
368 """Utility method used by magic_edit to find what to edit."""
368
369
369 def make_filename(arg):
370 def make_filename(arg):
370 "Make a filename from the given args"
371 "Make a filename from the given args"
371 arg = unquote_filename(arg)
372 arg = unquote_filename(arg)
372 try:
373 try:
373 filename = get_py_filename(arg)
374 filename = get_py_filename(arg)
374 except IOError:
375 except IOError:
375 # If it ends with .py but doesn't already exist, assume we want
376 # If it ends with .py but doesn't already exist, assume we want
376 # a new file.
377 # a new file.
377 if arg.endswith('.py'):
378 if arg.endswith('.py'):
378 filename = arg
379 filename = arg
379 else:
380 else:
380 filename = None
381 filename = None
381 return filename
382 return filename
382
383
383 # Set a few locals from the options for convenience:
384 # Set a few locals from the options for convenience:
384 opts_prev = 'p' in opts
385 opts_prev = 'p' in opts
385 opts_raw = 'r' in opts
386 opts_raw = 'r' in opts
386
387
387 # custom exceptions
388 # custom exceptions
388 class DataIsObject(Exception): pass
389 class DataIsObject(Exception): pass
389
390
390 # Default line number value
391 # Default line number value
391 lineno = opts.get('n',None)
392 lineno = opts.get('n',None)
392
393
393 if opts_prev:
394 if opts_prev:
394 args = '_%s' % last_call[0]
395 args = '_%s' % last_call[0]
395 if args not in shell.user_ns:
396 if args not in shell.user_ns:
396 args = last_call[1]
397 args = last_call[1]
397
398
398 # by default this is done with temp files, except when the given
399 # by default this is done with temp files, except when the given
399 # arg is a filename
400 # arg is a filename
400 use_temp = True
401 use_temp = True
401
402
402 data = ''
403 data = ''
403
404
404 # First, see if the arguments should be a filename.
405 # First, see if the arguments should be a filename.
405 filename = make_filename(args)
406 filename = make_filename(args)
406 if filename:
407 if filename:
407 use_temp = False
408 use_temp = False
408 elif args:
409 elif args:
409 # Mode where user specifies ranges of lines, like in %macro.
410 # Mode where user specifies ranges of lines, like in %macro.
410 data = shell.extract_input_lines(args, opts_raw)
411 data = shell.extract_input_lines(args, opts_raw)
411 if not data:
412 if not data:
412 try:
413 try:
413 # Load the parameter given as a variable. If not a string,
414 # Load the parameter given as a variable. If not a string,
414 # process it as an object instead (below)
415 # process it as an object instead (below)
415
416
416 #print '*** args',args,'type',type(args) # dbg
417 #print '*** args',args,'type',type(args) # dbg
417 data = eval(args, shell.user_ns)
418 data = eval(args, shell.user_ns)
418 if not isinstance(data, string_types):
419 if not isinstance(data, string_types):
419 raise DataIsObject
420 raise DataIsObject
420
421
421 except (NameError,SyntaxError):
422 except (NameError,SyntaxError):
422 # given argument is not a variable, try as a filename
423 # given argument is not a variable, try as a filename
423 filename = make_filename(args)
424 filename = make_filename(args)
424 if filename is None:
425 if filename is None:
425 warn("Argument given (%s) can't be found as a variable "
426 warn("Argument given (%s) can't be found as a variable "
426 "or as a filename." % args)
427 "or as a filename." % args)
427 return (None, None, None)
428 return (None, None, None)
428 use_temp = False
429 use_temp = False
429
430
430 except DataIsObject:
431 except DataIsObject:
431 # macros have a special edit function
432 # macros have a special edit function
432 if isinstance(data, Macro):
433 if isinstance(data, Macro):
433 raise MacroToEdit(data)
434 raise MacroToEdit(data)
434
435
435 # For objects, try to edit the file where they are defined
436 # For objects, try to edit the file where they are defined
436 filename = find_file(data)
437 filename = find_file(data)
437 if filename:
438 if filename:
438 if 'fakemodule' in filename.lower() and \
439 if 'fakemodule' in filename.lower() and \
439 inspect.isclass(data):
440 inspect.isclass(data):
440 # class created by %edit? Try to find source
441 # class created by %edit? Try to find source
441 # by looking for method definitions instead, the
442 # by looking for method definitions instead, the
442 # __module__ in those classes is FakeModule.
443 # __module__ in those classes is FakeModule.
443 attrs = [getattr(data, aname) for aname in dir(data)]
444 attrs = [getattr(data, aname) for aname in dir(data)]
444 for attr in attrs:
445 for attr in attrs:
445 if not inspect.ismethod(attr):
446 if not inspect.ismethod(attr):
446 continue
447 continue
447 filename = find_file(attr)
448 filename = find_file(attr)
448 if filename and \
449 if filename and \
449 'fakemodule' not in filename.lower():
450 'fakemodule' not in filename.lower():
450 # change the attribute to be the edit
451 # change the attribute to be the edit
451 # target instead
452 # target instead
452 data = attr
453 data = attr
453 break
454 break
454
455
455 m = ipython_input_pat.match(os.path.basename(filename))
456 m = ipython_input_pat.match(os.path.basename(filename))
456 if m:
457 if m:
457 raise InteractivelyDefined(int(m.groups()[0]))
458 raise InteractivelyDefined(int(m.groups()[0]))
458
459
459 datafile = 1
460 datafile = 1
460 if filename is None:
461 if filename is None:
461 filename = make_filename(args)
462 filename = make_filename(args)
462 datafile = 1
463 datafile = 1
463 if filename is not None:
464 if filename is not None:
464 # only warn about this if we get a real name
465 # only warn about this if we get a real name
465 warn('Could not find file where `%s` is defined.\n'
466 warn('Could not find file where `%s` is defined.\n'
466 'Opening a file named `%s`' % (args, filename))
467 'Opening a file named `%s`' % (args, filename))
467 # Now, make sure we can actually read the source (if it was
468 # Now, make sure we can actually read the source (if it was
468 # in a temp file it's gone by now).
469 # in a temp file it's gone by now).
469 if datafile:
470 if datafile:
470 if lineno is None:
471 if lineno is None:
471 lineno = find_source_lines(data)
472 lineno = find_source_lines(data)
472 if lineno is None:
473 if lineno is None:
473 filename = make_filename(args)
474 filename = make_filename(args)
474 if filename is None:
475 if filename is None:
475 warn('The file where `%s` was defined '
476 warn('The file where `%s` was defined '
476 'cannot be read or found.' % data)
477 'cannot be read or found.' % data)
477 return (None, None, None)
478 return (None, None, None)
478 use_temp = False
479 use_temp = False
479
480
480 if use_temp:
481 if use_temp:
481 filename = shell.mktempfile(data)
482 filename = shell.mktempfile(data)
482 print('IPython will make a temporary file named:',filename)
483 print('IPython will make a temporary file named:',filename)
483
484
484 # use last_call to remember the state of the previous call, but don't
485 # use last_call to remember the state of the previous call, but don't
485 # let it be clobbered by successive '-p' calls.
486 # let it be clobbered by successive '-p' calls.
486 try:
487 try:
487 last_call[0] = shell.displayhook.prompt_count
488 last_call[0] = shell.displayhook.prompt_count
488 if not opts_prev:
489 if not opts_prev:
489 last_call[1] = args
490 last_call[1] = args
490 except:
491 except:
491 pass
492 pass
492
493
493
494
494 return filename, lineno, use_temp
495 return filename, lineno, use_temp
495
496
496 def _edit_macro(self,mname,macro):
497 def _edit_macro(self,mname,macro):
497 """open an editor with the macro data in a file"""
498 """open an editor with the macro data in a file"""
498 filename = self.shell.mktempfile(macro.value)
499 filename = self.shell.mktempfile(macro.value)
499 self.shell.hooks.editor(filename)
500 self.shell.hooks.editor(filename)
500
501
501 # and make a new macro object, to replace the old one
502 # and make a new macro object, to replace the old one
502 with open(filename) as mfile:
503 with open(filename) as mfile:
503 mvalue = mfile.read()
504 mvalue = mfile.read()
504 self.shell.user_ns[mname] = Macro(mvalue)
505 self.shell.user_ns[mname] = Macro(mvalue)
505
506
506 @skip_doctest
507 @skip_doctest
507 @line_magic
508 @line_magic
508 def edit(self, parameter_s='',last_call=['','']):
509 def edit(self, parameter_s='',last_call=['','']):
509 """Bring up an editor and execute the resulting code.
510 """Bring up an editor and execute the resulting code.
510
511
511 Usage:
512 Usage:
512 %edit [options] [args]
513 %edit [options] [args]
513
514
514 %edit runs IPython's editor hook. The default version of this hook is
515 %edit runs IPython's editor hook. The default version of this hook is
515 set to call the editor specified by your $EDITOR environment variable.
516 set to call the editor specified by your $EDITOR environment variable.
516 If this isn't found, it will default to vi under Linux/Unix and to
517 If this isn't found, it will default to vi under Linux/Unix and to
517 notepad under Windows. See the end of this docstring for how to change
518 notepad under Windows. See the end of this docstring for how to change
518 the editor hook.
519 the editor hook.
519
520
520 You can also set the value of this editor via the
521 You can also set the value of this editor via the
521 ``TerminalInteractiveShell.editor`` option in your configuration file.
522 ``TerminalInteractiveShell.editor`` option in your configuration file.
522 This is useful if you wish to use a different editor from your typical
523 This is useful if you wish to use a different editor from your typical
523 default with IPython (and for Windows users who typically don't set
524 default with IPython (and for Windows users who typically don't set
524 environment variables).
525 environment variables).
525
526
526 This command allows you to conveniently edit multi-line code right in
527 This command allows you to conveniently edit multi-line code right in
527 your IPython session.
528 your IPython session.
528
529
529 If called without arguments, %edit opens up an empty editor with a
530 If called without arguments, %edit opens up an empty editor with a
530 temporary file and will execute the contents of this file when you
531 temporary file and will execute the contents of this file when you
531 close it (don't forget to save it!).
532 close it (don't forget to save it!).
532
533
533
534
534 Options:
535 Options:
535
536
536 -n <number>: open the editor at a specified line number. By default,
537 -n <number>: open the editor at a specified line number. By default,
537 the IPython editor hook uses the unix syntax 'editor +N filename', but
538 the IPython editor hook uses the unix syntax 'editor +N filename', but
538 you can configure this by providing your own modified hook if your
539 you can configure this by providing your own modified hook if your
539 favorite editor supports line-number specifications with a different
540 favorite editor supports line-number specifications with a different
540 syntax.
541 syntax.
541
542
542 -p: this will call the editor with the same data as the previous time
543 -p: this will call the editor with the same data as the previous time
543 it was used, regardless of how long ago (in your current session) it
544 it was used, regardless of how long ago (in your current session) it
544 was.
545 was.
545
546
546 -r: use 'raw' input. This option only applies to input taken from the
547 -r: use 'raw' input. This option only applies to input taken from the
547 user's history. By default, the 'processed' history is used, so that
548 user's history. By default, the 'processed' history is used, so that
548 magics are loaded in their transformed version to valid Python. If
549 magics are loaded in their transformed version to valid Python. If
549 this option is given, the raw input as typed as the command line is
550 this option is given, the raw input as typed as the command line is
550 used instead. When you exit the editor, it will be executed by
551 used instead. When you exit the editor, it will be executed by
551 IPython's own processor.
552 IPython's own processor.
552
553
553 -x: do not execute the edited code immediately upon exit. This is
554 -x: do not execute the edited code immediately upon exit. This is
554 mainly useful if you are editing programs which need to be called with
555 mainly useful if you are editing programs which need to be called with
555 command line arguments, which you can then do using %run.
556 command line arguments, which you can then do using %run.
556
557
557
558
558 Arguments:
559 Arguments:
559
560
560 If arguments are given, the following possibilities exist:
561 If arguments are given, the following possibilities exist:
561
562
562 - If the argument is a filename, IPython will load that into the
563 - If the argument is a filename, IPython will load that into the
563 editor. It will execute its contents with execfile() when you exit,
564 editor. It will execute its contents with execfile() when you exit,
564 loading any code in the file into your interactive namespace.
565 loading any code in the file into your interactive namespace.
565
566
566 - The arguments are ranges of input history, e.g. "7 ~1/4-6".
567 - The arguments are ranges of input history, e.g. "7 ~1/4-6".
567 The syntax is the same as in the %history magic.
568 The syntax is the same as in the %history magic.
568
569
569 - If the argument is a string variable, its contents are loaded
570 - If the argument is a string variable, its contents are loaded
570 into the editor. You can thus edit any string which contains
571 into the editor. You can thus edit any string which contains
571 python code (including the result of previous edits).
572 python code (including the result of previous edits).
572
573
573 - If the argument is the name of an object (other than a string),
574 - If the argument is the name of an object (other than a string),
574 IPython will try to locate the file where it was defined and open the
575 IPython will try to locate the file where it was defined and open the
575 editor at the point where it is defined. You can use `%edit function`
576 editor at the point where it is defined. You can use `%edit function`
576 to load an editor exactly at the point where 'function' is defined,
577 to load an editor exactly at the point where 'function' is defined,
577 edit it and have the file be executed automatically.
578 edit it and have the file be executed automatically.
578
579
579 - If the object is a macro (see %macro for details), this opens up your
580 - If the object is a macro (see %macro for details), this opens up your
580 specified editor with a temporary file containing the macro's data.
581 specified editor with a temporary file containing the macro's data.
581 Upon exit, the macro is reloaded with the contents of the file.
582 Upon exit, the macro is reloaded with the contents of the file.
582
583
583 Note: opening at an exact line is only supported under Unix, and some
584 Note: opening at an exact line is only supported under Unix, and some
584 editors (like kedit and gedit up to Gnome 2.8) do not understand the
585 editors (like kedit and gedit up to Gnome 2.8) do not understand the
585 '+NUMBER' parameter necessary for this feature. Good editors like
586 '+NUMBER' parameter necessary for this feature. Good editors like
586 (X)Emacs, vi, jed, pico and joe all do.
587 (X)Emacs, vi, jed, pico and joe all do.
587
588
588 After executing your code, %edit will return as output the code you
589 After executing your code, %edit will return as output the code you
589 typed in the editor (except when it was an existing file). This way
590 typed in the editor (except when it was an existing file). This way
590 you can reload the code in further invocations of %edit as a variable,
591 you can reload the code in further invocations of %edit as a variable,
591 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
592 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
592 the output.
593 the output.
593
594
594 Note that %edit is also available through the alias %ed.
595 Note that %edit is also available through the alias %ed.
595
596
596 This is an example of creating a simple function inside the editor and
597 This is an example of creating a simple function inside the editor and
597 then modifying it. First, start up the editor::
598 then modifying it. First, start up the editor::
598
599
599 In [1]: edit
600 In [1]: edit
600 Editing... done. Executing edited code...
601 Editing... done. Executing edited code...
601 Out[1]: 'def foo():\\n print "foo() was defined in an editing
602 Out[1]: 'def foo():\\n print "foo() was defined in an editing
602 session"\\n'
603 session"\\n'
603
604
604 We can then call the function foo()::
605 We can then call the function foo()::
605
606
606 In [2]: foo()
607 In [2]: foo()
607 foo() was defined in an editing session
608 foo() was defined in an editing session
608
609
609 Now we edit foo. IPython automatically loads the editor with the
610 Now we edit foo. IPython automatically loads the editor with the
610 (temporary) file where foo() was previously defined::
611 (temporary) file where foo() was previously defined::
611
612
612 In [3]: edit foo
613 In [3]: edit foo
613 Editing... done. Executing edited code...
614 Editing... done. Executing edited code...
614
615
615 And if we call foo() again we get the modified version::
616 And if we call foo() again we get the modified version::
616
617
617 In [4]: foo()
618 In [4]: foo()
618 foo() has now been changed!
619 foo() has now been changed!
619
620
620 Here is an example of how to edit a code snippet successive
621 Here is an example of how to edit a code snippet successive
621 times. First we call the editor::
622 times. First we call the editor::
622
623
623 In [5]: edit
624 In [5]: edit
624 Editing... done. Executing edited code...
625 Editing... done. Executing edited code...
625 hello
626 hello
626 Out[5]: "print 'hello'\\n"
627 Out[5]: "print 'hello'\\n"
627
628
628 Now we call it again with the previous output (stored in _)::
629 Now we call it again with the previous output (stored in _)::
629
630
630 In [6]: edit _
631 In [6]: edit _
631 Editing... done. Executing edited code...
632 Editing... done. Executing edited code...
632 hello world
633 hello world
633 Out[6]: "print 'hello world'\\n"
634 Out[6]: "print 'hello world'\\n"
634
635
635 Now we call it with the output #8 (stored in _8, also as Out[8])::
636 Now we call it with the output #8 (stored in _8, also as Out[8])::
636
637
637 In [7]: edit _8
638 In [7]: edit _8
638 Editing... done. Executing edited code...
639 Editing... done. Executing edited code...
639 hello again
640 hello again
640 Out[7]: "print 'hello again'\\n"
641 Out[7]: "print 'hello again'\\n"
641
642
642
643
643 Changing the default editor hook:
644 Changing the default editor hook:
644
645
645 If you wish to write your own editor hook, you can put it in a
646 If you wish to write your own editor hook, you can put it in a
646 configuration file which you load at startup time. The default hook
647 configuration file which you load at startup time. The default hook
647 is defined in the IPython.core.hooks module, and you can use that as a
648 is defined in the IPython.core.hooks module, and you can use that as a
648 starting example for further modifications. That file also has
649 starting example for further modifications. That file also has
649 general instructions on how to set a new hook for use once you've
650 general instructions on how to set a new hook for use once you've
650 defined it."""
651 defined it."""
651 opts,args = self.parse_options(parameter_s,'prxn:')
652 opts,args = self.parse_options(parameter_s,'prxn:')
652
653
653 try:
654 try:
654 filename, lineno, is_temp = self._find_edit_target(self.shell,
655 filename, lineno, is_temp = self._find_edit_target(self.shell,
655 args, opts, last_call)
656 args, opts, last_call)
656 except MacroToEdit as e:
657 except MacroToEdit as e:
657 self._edit_macro(args, e.args[0])
658 self._edit_macro(args, e.args[0])
658 return
659 return
659 except InteractivelyDefined as e:
660 except InteractivelyDefined as e:
660 print("Editing In[%i]" % e.index)
661 print("Editing In[%i]" % e.index)
661 args = str(e.index)
662 args = str(e.index)
662 filename, lineno, is_temp = self._find_edit_target(self.shell,
663 filename, lineno, is_temp = self._find_edit_target(self.shell,
663 args, opts, last_call)
664 args, opts, last_call)
664 if filename is None:
665 if filename is None:
665 # nothing was found, warnings have already been issued,
666 # nothing was found, warnings have already been issued,
666 # just give up.
667 # just give up.
667 return
668 return
668
669
669 if is_temp:
670 if is_temp:
670 self._knowntemps.add(filename)
671 self._knowntemps.add(filename)
671 elif (filename in self._knowntemps):
672 elif (filename in self._knowntemps):
672 is_temp = True
673 is_temp = True
673
674
674
675
675 # do actual editing here
676 # do actual editing here
676 print('Editing...', end=' ')
677 print('Editing...', end=' ')
677 sys.stdout.flush()
678 sys.stdout.flush()
678 try:
679 try:
679 # Quote filenames that may have spaces in them
680 # Quote filenames that may have spaces in them
680 if ' ' in filename:
681 if ' ' in filename:
681 filename = "'%s'" % filename
682 filename = "'%s'" % filename
682 self.shell.hooks.editor(filename,lineno)
683 self.shell.hooks.editor(filename,lineno)
683 except TryNext:
684 except TryNext:
684 warn('Could not open editor')
685 warn('Could not open editor')
685 return
686 return
686
687
687 # XXX TODO: should this be generalized for all string vars?
688 # XXX TODO: should this be generalized for all string vars?
688 # For now, this is special-cased to blocks created by cpaste
689 # For now, this is special-cased to blocks created by cpaste
689 if args.strip() == 'pasted_block':
690 if args.strip() == 'pasted_block':
690 with open(filename, 'r') as f:
691 with open(filename, 'r') as f:
691 self.shell.user_ns['pasted_block'] = f.read()
692 self.shell.user_ns['pasted_block'] = f.read()
692
693
693 if 'x' in opts: # -x prevents actual execution
694 if 'x' in opts: # -x prevents actual execution
694 print()
695 print()
695 else:
696 else:
696 print('done. Executing edited code...')
697 print('done. Executing edited code...')
697 with preserve_keys(self.shell.user_ns, '__file__'):
698 with preserve_keys(self.shell.user_ns, '__file__'):
698 if not is_temp:
699 if not is_temp:
699 self.shell.user_ns['__file__'] = filename
700 self.shell.user_ns['__file__'] = filename
700 if 'r' in opts: # Untranslated IPython code
701 if 'r' in opts: # Untranslated IPython code
701 with open(filename, 'r') as f:
702 with open(filename, 'r') as f:
702 source = f.read()
703 source = f.read()
703 self.shell.run_cell(source, store_history=False)
704 self.shell.run_cell(source, store_history=False)
704 else:
705 else:
705 self.shell.safe_execfile(filename, self.shell.user_ns,
706 self.shell.safe_execfile(filename, self.shell.user_ns,
706 self.shell.user_ns)
707 self.shell.user_ns)
707
708
708 if is_temp:
709 if is_temp:
709 try:
710 try:
710 return open(filename).read()
711 return open(filename).read()
711 except IOError as msg:
712 except IOError as msg:
712 if msg.filename == filename:
713 if msg.filename == filename:
713 warn('File not found. Did you forget to save?')
714 warn('File not found. Did you forget to save?')
714 return
715 return
715 else:
716 else:
716 self.shell.showtraceback()
717 self.shell.showtraceback()
@@ -1,159 +1,160 b''
1 """Implementation of configuration-related magic functions.
1 """Implementation of configuration-related magic functions.
2 """
2 """
3 from __future__ import print_function
3 from __future__ import print_function
4 from __future__ import absolute_import
4 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
5 # Copyright (c) 2012 The IPython Development Team.
6 # Copyright (c) 2012 The IPython Development Team.
6 #
7 #
7 # Distributed under the terms of the Modified BSD License.
8 # Distributed under the terms of the Modified BSD License.
8 #
9 #
9 # The full license is in the file COPYING.txt, distributed with this software.
10 # The full license is in the file COPYING.txt, distributed with this software.
10 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
11
12
12 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
13 # Imports
14 # Imports
14 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
15
16
16 # Stdlib
17 # Stdlib
17 import re
18 import re
18
19
19 # Our own packages
20 # Our own packages
20 from IPython.core.error import UsageError
21 from IPython.core.error import UsageError
21 from IPython.core.magic import Magics, magics_class, line_magic
22 from IPython.core.magic import Magics, magics_class, line_magic
22 from logging import error
23 from logging import error
23
24
24 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
25 # Magic implementation classes
26 # Magic implementation classes
26 #-----------------------------------------------------------------------------
27 #-----------------------------------------------------------------------------
27
28
28 reg = re.compile('^\w+\.\w+$')
29 reg = re.compile('^\w+\.\w+$')
29 @magics_class
30 @magics_class
30 class ConfigMagics(Magics):
31 class ConfigMagics(Magics):
31
32
32 def __init__(self, shell):
33 def __init__(self, shell):
33 super(ConfigMagics, self).__init__(shell)
34 super(ConfigMagics, self).__init__(shell)
34 self.configurables = []
35 self.configurables = []
35
36
36 @line_magic
37 @line_magic
37 def config(self, s):
38 def config(self, s):
38 """configure IPython
39 """configure IPython
39
40
40 %config Class[.trait=value]
41 %config Class[.trait=value]
41
42
42 This magic exposes most of the IPython config system. Any
43 This magic exposes most of the IPython config system. Any
43 Configurable class should be able to be configured with the simple
44 Configurable class should be able to be configured with the simple
44 line::
45 line::
45
46
46 %config Class.trait=value
47 %config Class.trait=value
47
48
48 Where `value` will be resolved in the user's namespace, if it is an
49 Where `value` will be resolved in the user's namespace, if it is an
49 expression or variable name.
50 expression or variable name.
50
51
51 Examples
52 Examples
52 --------
53 --------
53
54
54 To see what classes are available for config, pass no arguments::
55 To see what classes are available for config, pass no arguments::
55
56
56 In [1]: %config
57 In [1]: %config
57 Available objects for config:
58 Available objects for config:
58 TerminalInteractiveShell
59 TerminalInteractiveShell
59 HistoryManager
60 HistoryManager
60 PrefilterManager
61 PrefilterManager
61 AliasManager
62 AliasManager
62 IPCompleter
63 IPCompleter
63 PromptManager
64 PromptManager
64 DisplayFormatter
65 DisplayFormatter
65
66
66 To view what is configurable on a given class, just pass the class
67 To view what is configurable on a given class, just pass the class
67 name::
68 name::
68
69
69 In [2]: %config IPCompleter
70 In [2]: %config IPCompleter
70 IPCompleter options
71 IPCompleter options
71 -----------------
72 -----------------
72 IPCompleter.omit__names=<Enum>
73 IPCompleter.omit__names=<Enum>
73 Current: 2
74 Current: 2
74 Choices: (0, 1, 2)
75 Choices: (0, 1, 2)
75 Instruct the completer to omit private method names
76 Instruct the completer to omit private method names
76 Specifically, when completing on ``object.<tab>``.
77 Specifically, when completing on ``object.<tab>``.
77 When 2 [default]: all names that start with '_' will be excluded.
78 When 2 [default]: all names that start with '_' will be excluded.
78 When 1: all 'magic' names (``__foo__``) will be excluded.
79 When 1: all 'magic' names (``__foo__``) will be excluded.
79 When 0: nothing will be excluded.
80 When 0: nothing will be excluded.
80 IPCompleter.merge_completions=<CBool>
81 IPCompleter.merge_completions=<CBool>
81 Current: True
82 Current: True
82 Whether to merge completion results into a single list
83 Whether to merge completion results into a single list
83 If False, only the completion results from the first non-empty
84 If False, only the completion results from the first non-empty
84 completer will be returned.
85 completer will be returned.
85 IPCompleter.limit_to__all__=<CBool>
86 IPCompleter.limit_to__all__=<CBool>
86 Current: False
87 Current: False
87 Instruct the completer to use __all__ for the completion
88 Instruct the completer to use __all__ for the completion
88 Specifically, when completing on ``object.<tab>``.
89 Specifically, when completing on ``object.<tab>``.
89 When True: only those names in obj.__all__ will be included.
90 When True: only those names in obj.__all__ will be included.
90 When False [default]: the __all__ attribute is ignored
91 When False [default]: the __all__ attribute is ignored
91 IPCompleter.greedy=<CBool>
92 IPCompleter.greedy=<CBool>
92 Current: False
93 Current: False
93 Activate greedy completion
94 Activate greedy completion
94 This will enable completion on elements of lists, results of
95 This will enable completion on elements of lists, results of
95 function calls, etc., but can be unsafe because the code is
96 function calls, etc., but can be unsafe because the code is
96 actually evaluated on TAB.
97 actually evaluated on TAB.
97
98
98 but the real use is in setting values::
99 but the real use is in setting values::
99
100
100 In [3]: %config IPCompleter.greedy = True
101 In [3]: %config IPCompleter.greedy = True
101
102
102 and these values are read from the user_ns if they are variables::
103 and these values are read from the user_ns if they are variables::
103
104
104 In [4]: feeling_greedy=False
105 In [4]: feeling_greedy=False
105
106
106 In [5]: %config IPCompleter.greedy = feeling_greedy
107 In [5]: %config IPCompleter.greedy = feeling_greedy
107
108
108 """
109 """
109 from traitlets.config.loader import Config
110 from traitlets.config.loader import Config
110 # some IPython objects are Configurable, but do not yet have
111 # some IPython objects are Configurable, but do not yet have
111 # any configurable traits. Exclude them from the effects of
112 # any configurable traits. Exclude them from the effects of
112 # this magic, as their presence is just noise:
113 # this magic, as their presence is just noise:
113 configurables = [ c for c in self.shell.configurables
114 configurables = [ c for c in self.shell.configurables
114 if c.__class__.class_traits(config=True) ]
115 if c.__class__.class_traits(config=True) ]
115 classnames = [ c.__class__.__name__ for c in configurables ]
116 classnames = [ c.__class__.__name__ for c in configurables ]
116
117
117 line = s.strip()
118 line = s.strip()
118 if not line:
119 if not line:
119 # print available configurable names
120 # print available configurable names
120 print("Available objects for config:")
121 print("Available objects for config:")
121 for name in classnames:
122 for name in classnames:
122 print(" ", name)
123 print(" ", name)
123 return
124 return
124 elif line in classnames:
125 elif line in classnames:
125 # `%config TerminalInteractiveShell` will print trait info for
126 # `%config TerminalInteractiveShell` will print trait info for
126 # TerminalInteractiveShell
127 # TerminalInteractiveShell
127 c = configurables[classnames.index(line)]
128 c = configurables[classnames.index(line)]
128 cls = c.__class__
129 cls = c.__class__
129 help = cls.class_get_help(c)
130 help = cls.class_get_help(c)
130 # strip leading '--' from cl-args:
131 # strip leading '--' from cl-args:
131 help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
132 help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
132 print(help)
133 print(help)
133 return
134 return
134 elif reg.match(line):
135 elif reg.match(line):
135 cls, attr = line.split('.')
136 cls, attr = line.split('.')
136 return getattr(configurables[classnames.index(cls)],attr)
137 return getattr(configurables[classnames.index(cls)],attr)
137 elif '=' not in line:
138 elif '=' not in line:
138 msg = "Invalid config statement: %r, "\
139 msg = "Invalid config statement: %r, "\
139 "should be `Class.trait = value`."
140 "should be `Class.trait = value`."
140
141
141 ll = line.lower()
142 ll = line.lower()
142 for classname in classnames:
143 for classname in classnames:
143 if ll == classname.lower():
144 if ll == classname.lower():
144 msg = msg + '\nDid you mean %s (note the case)?' % classname
145 msg = msg + '\nDid you mean %s (note the case)?' % classname
145 break
146 break
146
147
147 raise UsageError( msg % line)
148 raise UsageError( msg % line)
148
149
149 # otherwise, assume we are setting configurables.
150 # otherwise, assume we are setting configurables.
150 # leave quotes on args when splitting, because we want
151 # leave quotes on args when splitting, because we want
151 # unquoted args to eval in user_ns
152 # unquoted args to eval in user_ns
152 cfg = Config()
153 cfg = Config()
153 exec("cfg."+line, locals(), self.shell.user_ns)
154 exec("cfg."+line, locals(), self.shell.user_ns)
154
155
155 for configurable in configurables:
156 for configurable in configurables:
156 try:
157 try:
157 configurable.update_config(cfg)
158 configurable.update_config(cfg)
158 except Exception as e:
159 except Exception as e:
159 error(e)
160 error(e)
@@ -1,1363 +1,1364 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Implementation of execution-related magic functions."""
2 """Implementation of execution-related magic functions."""
3
3
4 # Copyright (c) IPython Development Team.
4 # Copyright (c) IPython Development Team.
5 # Distributed under the terms of the Modified BSD License.
5 # Distributed under the terms of the Modified BSD License.
6
6
7 from __future__ import print_function
7 from __future__ import print_function
8 from __future__ import absolute_import
8
9
9 import ast
10 import ast
10 import bdb
11 import bdb
11 import gc
12 import gc
12 import itertools
13 import itertools
13 import os
14 import os
14 import sys
15 import sys
15 import time
16 import time
16 import timeit
17 import timeit
17 from pdb import Restart
18 from pdb import Restart
18
19
19 # cProfile was added in Python2.5
20 # cProfile was added in Python2.5
20 try:
21 try:
21 import cProfile as profile
22 import cProfile as profile
22 import pstats
23 import pstats
23 except ImportError:
24 except ImportError:
24 # profile isn't bundled by default in Debian for license reasons
25 # profile isn't bundled by default in Debian for license reasons
25 try:
26 try:
26 import profile, pstats
27 import profile, pstats
27 except ImportError:
28 except ImportError:
28 profile = pstats = None
29 profile = pstats = None
29
30
30 from IPython.core import debugger, oinspect
31 from IPython.core import debugger, oinspect
31 from IPython.core import magic_arguments
32 from IPython.core import magic_arguments
32 from IPython.core import page
33 from IPython.core import page
33 from IPython.core.error import UsageError
34 from IPython.core.error import UsageError
34 from IPython.core.macro import Macro
35 from IPython.core.macro import Macro
35 from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,
36 from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,
36 line_cell_magic, on_off, needs_local_scope)
37 line_cell_magic, on_off, needs_local_scope)
37 from IPython.testing.skipdoctest import skip_doctest
38 from IPython.testing.skipdoctest import skip_doctest
38 from IPython.utils import py3compat
39 from IPython.utils import py3compat
39 from IPython.utils.py3compat import builtin_mod, iteritems, PY3
40 from IPython.utils.py3compat import builtin_mod, iteritems, PY3
40 from IPython.utils.contexts import preserve_keys
41 from IPython.utils.contexts import preserve_keys
41 from IPython.utils.capture import capture_output
42 from IPython.utils.capture import capture_output
42 from IPython.utils.ipstruct import Struct
43 from IPython.utils.ipstruct import Struct
43 from IPython.utils.module_paths import find_mod
44 from IPython.utils.module_paths import find_mod
44 from IPython.utils.path import get_py_filename, unquote_filename, shellglob
45 from IPython.utils.path import get_py_filename, unquote_filename, shellglob
45 from IPython.utils.timing import clock, clock2
46 from IPython.utils.timing import clock, clock2
46 from warnings import warn
47 from warnings import warn
47 from logging import error
48 from logging import error
48
49
49 if PY3:
50 if PY3:
50 from io import StringIO
51 from io import StringIO
51 else:
52 else:
52 from StringIO import StringIO
53 from StringIO import StringIO
53
54
54 #-----------------------------------------------------------------------------
55 #-----------------------------------------------------------------------------
55 # Magic implementation classes
56 # Magic implementation classes
56 #-----------------------------------------------------------------------------
57 #-----------------------------------------------------------------------------
57
58
58
59
59 class TimeitResult(object):
60 class TimeitResult(object):
60 """
61 """
61 Object returned by the timeit magic with info about the run.
62 Object returned by the timeit magic with info about the run.
62
63
63 Contain the following attributes :
64 Contain the following attributes :
64
65
65 loops: (int) number of loop done per measurement
66 loops: (int) number of loop done per measurement
66 repeat: (int) number of time the mesurement has been repeated
67 repeat: (int) number of time the mesurement has been repeated
67 best: (float) best execusion time / number
68 best: (float) best execusion time / number
68 all_runs: (list of float) execusion time of each run (in s)
69 all_runs: (list of float) execusion time of each run (in s)
69 compile_time: (float) time of statement compilation (s)
70 compile_time: (float) time of statement compilation (s)
70
71
71 """
72 """
72
73
73 def __init__(self, loops, repeat, best, worst, all_runs, compile_time, precision):
74 def __init__(self, loops, repeat, best, worst, all_runs, compile_time, precision):
74 self.loops = loops
75 self.loops = loops
75 self.repeat = repeat
76 self.repeat = repeat
76 self.best = best
77 self.best = best
77 self.worst = worst
78 self.worst = worst
78 self.all_runs = all_runs
79 self.all_runs = all_runs
79 self.compile_time = compile_time
80 self.compile_time = compile_time
80 self._precision = precision
81 self._precision = precision
81
82
82 def _repr_pretty_(self, p , cycle):
83 def _repr_pretty_(self, p , cycle):
83 if self.loops == 1: # No s at "loops" if only one loop
84 if self.loops == 1: # No s at "loops" if only one loop
84 unic = u"%d loop, best of %d: %s per loop" % (self.loops, self.repeat,
85 unic = u"%d loop, best of %d: %s per loop" % (self.loops, self.repeat,
85 _format_time(self.best, self._precision))
86 _format_time(self.best, self._precision))
86 else:
87 else:
87 unic = u"%d loops, best of %d: %s per loop" % (self.loops, self.repeat,
88 unic = u"%d loops, best of %d: %s per loop" % (self.loops, self.repeat,
88 _format_time(self.best, self._precision))
89 _format_time(self.best, self._precision))
89 p.text(u'<TimeitResult : '+unic+u'>')
90 p.text(u'<TimeitResult : '+unic+u'>')
90
91
91
92
92 class TimeitTemplateFiller(ast.NodeTransformer):
93 class TimeitTemplateFiller(ast.NodeTransformer):
93 """Fill in the AST template for timing execution.
94 """Fill in the AST template for timing execution.
94
95
95 This is quite closely tied to the template definition, which is in
96 This is quite closely tied to the template definition, which is in
96 :meth:`ExecutionMagics.timeit`.
97 :meth:`ExecutionMagics.timeit`.
97 """
98 """
98 def __init__(self, ast_setup, ast_stmt):
99 def __init__(self, ast_setup, ast_stmt):
99 self.ast_setup = ast_setup
100 self.ast_setup = ast_setup
100 self.ast_stmt = ast_stmt
101 self.ast_stmt = ast_stmt
101
102
102 def visit_FunctionDef(self, node):
103 def visit_FunctionDef(self, node):
103 "Fill in the setup statement"
104 "Fill in the setup statement"
104 self.generic_visit(node)
105 self.generic_visit(node)
105 if node.name == "inner":
106 if node.name == "inner":
106 node.body[:1] = self.ast_setup.body
107 node.body[:1] = self.ast_setup.body
107
108
108 return node
109 return node
109
110
110 def visit_For(self, node):
111 def visit_For(self, node):
111 "Fill in the statement to be timed"
112 "Fill in the statement to be timed"
112 if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
113 if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
113 node.body = self.ast_stmt.body
114 node.body = self.ast_stmt.body
114 return node
115 return node
115
116
116
117
117 class Timer(timeit.Timer):
118 class Timer(timeit.Timer):
118 """Timer class that explicitly uses self.inner
119 """Timer class that explicitly uses self.inner
119
120
120 which is an undocumented implementation detail of CPython,
121 which is an undocumented implementation detail of CPython,
121 not shared by PyPy.
122 not shared by PyPy.
122 """
123 """
123 # Timer.timeit copied from CPython 3.4.2
124 # Timer.timeit copied from CPython 3.4.2
124 def timeit(self, number=timeit.default_number):
125 def timeit(self, number=timeit.default_number):
125 """Time 'number' executions of the main statement.
126 """Time 'number' executions of the main statement.
126
127
127 To be precise, this executes the setup statement once, and
128 To be precise, this executes the setup statement once, and
128 then returns the time it takes to execute the main statement
129 then returns the time it takes to execute the main statement
129 a number of times, as a float measured in seconds. The
130 a number of times, as a float measured in seconds. The
130 argument is the number of times through the loop, defaulting
131 argument is the number of times through the loop, defaulting
131 to one million. The main statement, the setup statement and
132 to one million. The main statement, the setup statement and
132 the timer function to be used are passed to the constructor.
133 the timer function to be used are passed to the constructor.
133 """
134 """
134 it = itertools.repeat(None, number)
135 it = itertools.repeat(None, number)
135 gcold = gc.isenabled()
136 gcold = gc.isenabled()
136 gc.disable()
137 gc.disable()
137 try:
138 try:
138 timing = self.inner(it, self.timer)
139 timing = self.inner(it, self.timer)
139 finally:
140 finally:
140 if gcold:
141 if gcold:
141 gc.enable()
142 gc.enable()
142 return timing
143 return timing
143
144
144
145
145 @magics_class
146 @magics_class
146 class ExecutionMagics(Magics):
147 class ExecutionMagics(Magics):
147 """Magics related to code execution, debugging, profiling, etc.
148 """Magics related to code execution, debugging, profiling, etc.
148
149
149 """
150 """
150
151
151 def __init__(self, shell):
152 def __init__(self, shell):
152 super(ExecutionMagics, self).__init__(shell)
153 super(ExecutionMagics, self).__init__(shell)
153 if profile is None:
154 if profile is None:
154 self.prun = self.profile_missing_notice
155 self.prun = self.profile_missing_notice
155 # Default execution function used to actually run user code.
156 # Default execution function used to actually run user code.
156 self.default_runner = None
157 self.default_runner = None
157
158
158 def profile_missing_notice(self, *args, **kwargs):
159 def profile_missing_notice(self, *args, **kwargs):
159 error("""\
160 error("""\
160 The profile module could not be found. It has been removed from the standard
161 The profile module could not be found. It has been removed from the standard
161 python packages because of its non-free license. To use profiling, install the
162 python packages because of its non-free license. To use profiling, install the
162 python-profiler package from non-free.""")
163 python-profiler package from non-free.""")
163
164
164 @skip_doctest
165 @skip_doctest
165 @line_cell_magic
166 @line_cell_magic
166 def prun(self, parameter_s='', cell=None):
167 def prun(self, parameter_s='', cell=None):
167
168
168 """Run a statement through the python code profiler.
169 """Run a statement through the python code profiler.
169
170
170 Usage, in line mode:
171 Usage, in line mode:
171 %prun [options] statement
172 %prun [options] statement
172
173
173 Usage, in cell mode:
174 Usage, in cell mode:
174 %%prun [options] [statement]
175 %%prun [options] [statement]
175 code...
176 code...
176 code...
177 code...
177
178
178 In cell mode, the additional code lines are appended to the (possibly
179 In cell mode, the additional code lines are appended to the (possibly
179 empty) statement in the first line. Cell mode allows you to easily
180 empty) statement in the first line. Cell mode allows you to easily
180 profile multiline blocks without having to put them in a separate
181 profile multiline blocks without having to put them in a separate
181 function.
182 function.
182
183
183 The given statement (which doesn't require quote marks) is run via the
184 The given statement (which doesn't require quote marks) is run via the
184 python profiler in a manner similar to the profile.run() function.
185 python profiler in a manner similar to the profile.run() function.
185 Namespaces are internally managed to work correctly; profile.run
186 Namespaces are internally managed to work correctly; profile.run
186 cannot be used in IPython because it makes certain assumptions about
187 cannot be used in IPython because it makes certain assumptions about
187 namespaces which do not hold under IPython.
188 namespaces which do not hold under IPython.
188
189
189 Options:
190 Options:
190
191
191 -l <limit>
192 -l <limit>
192 you can place restrictions on what or how much of the
193 you can place restrictions on what or how much of the
193 profile gets printed. The limit value can be:
194 profile gets printed. The limit value can be:
194
195
195 * A string: only information for function names containing this string
196 * A string: only information for function names containing this string
196 is printed.
197 is printed.
197
198
198 * An integer: only these many lines are printed.
199 * An integer: only these many lines are printed.
199
200
200 * A float (between 0 and 1): this fraction of the report is printed
201 * A float (between 0 and 1): this fraction of the report is printed
201 (for example, use a limit of 0.4 to see the topmost 40% only).
202 (for example, use a limit of 0.4 to see the topmost 40% only).
202
203
203 You can combine several limits with repeated use of the option. For
204 You can combine several limits with repeated use of the option. For
204 example, ``-l __init__ -l 5`` will print only the topmost 5 lines of
205 example, ``-l __init__ -l 5`` will print only the topmost 5 lines of
205 information about class constructors.
206 information about class constructors.
206
207
207 -r
208 -r
208 return the pstats.Stats object generated by the profiling. This
209 return the pstats.Stats object generated by the profiling. This
209 object has all the information about the profile in it, and you can
210 object has all the information about the profile in it, and you can
210 later use it for further analysis or in other functions.
211 later use it for further analysis or in other functions.
211
212
212 -s <key>
213 -s <key>
213 sort profile by given key. You can provide more than one key
214 sort profile by given key. You can provide more than one key
214 by using the option several times: '-s key1 -s key2 -s key3...'. The
215 by using the option several times: '-s key1 -s key2 -s key3...'. The
215 default sorting key is 'time'.
216 default sorting key is 'time'.
216
217
217 The following is copied verbatim from the profile documentation
218 The following is copied verbatim from the profile documentation
218 referenced below:
219 referenced below:
219
220
220 When more than one key is provided, additional keys are used as
221 When more than one key is provided, additional keys are used as
221 secondary criteria when the there is equality in all keys selected
222 secondary criteria when the there is equality in all keys selected
222 before them.
223 before them.
223
224
224 Abbreviations can be used for any key names, as long as the
225 Abbreviations can be used for any key names, as long as the
225 abbreviation is unambiguous. The following are the keys currently
226 abbreviation is unambiguous. The following are the keys currently
226 defined:
227 defined:
227
228
228 ============ =====================
229 ============ =====================
229 Valid Arg Meaning
230 Valid Arg Meaning
230 ============ =====================
231 ============ =====================
231 "calls" call count
232 "calls" call count
232 "cumulative" cumulative time
233 "cumulative" cumulative time
233 "file" file name
234 "file" file name
234 "module" file name
235 "module" file name
235 "pcalls" primitive call count
236 "pcalls" primitive call count
236 "line" line number
237 "line" line number
237 "name" function name
238 "name" function name
238 "nfl" name/file/line
239 "nfl" name/file/line
239 "stdname" standard name
240 "stdname" standard name
240 "time" internal time
241 "time" internal time
241 ============ =====================
242 ============ =====================
242
243
243 Note that all sorts on statistics are in descending order (placing
244 Note that all sorts on statistics are in descending order (placing
244 most time consuming items first), where as name, file, and line number
245 most time consuming items first), where as name, file, and line number
245 searches are in ascending order (i.e., alphabetical). The subtle
246 searches are in ascending order (i.e., alphabetical). The subtle
246 distinction between "nfl" and "stdname" is that the standard name is a
247 distinction between "nfl" and "stdname" is that the standard name is a
247 sort of the name as printed, which means that the embedded line
248 sort of the name as printed, which means that the embedded line
248 numbers get compared in an odd way. For example, lines 3, 20, and 40
249 numbers get compared in an odd way. For example, lines 3, 20, and 40
249 would (if the file names were the same) appear in the string order
250 would (if the file names were the same) appear in the string order
250 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
251 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
251 line numbers. In fact, sort_stats("nfl") is the same as
252 line numbers. In fact, sort_stats("nfl") is the same as
252 sort_stats("name", "file", "line").
253 sort_stats("name", "file", "line").
253
254
254 -T <filename>
255 -T <filename>
255 save profile results as shown on screen to a text
256 save profile results as shown on screen to a text
256 file. The profile is still shown on screen.
257 file. The profile is still shown on screen.
257
258
258 -D <filename>
259 -D <filename>
259 save (via dump_stats) profile statistics to given
260 save (via dump_stats) profile statistics to given
260 filename. This data is in a format understood by the pstats module, and
261 filename. This data is in a format understood by the pstats module, and
261 is generated by a call to the dump_stats() method of profile
262 is generated by a call to the dump_stats() method of profile
262 objects. The profile is still shown on screen.
263 objects. The profile is still shown on screen.
263
264
264 -q
265 -q
265 suppress output to the pager. Best used with -T and/or -D above.
266 suppress output to the pager. Best used with -T and/or -D above.
266
267
267 If you want to run complete programs under the profiler's control, use
268 If you want to run complete programs under the profiler's control, use
268 ``%run -p [prof_opts] filename.py [args to program]`` where prof_opts
269 ``%run -p [prof_opts] filename.py [args to program]`` where prof_opts
269 contains profiler specific options as described here.
270 contains profiler specific options as described here.
270
271
271 You can read the complete documentation for the profile module with::
272 You can read the complete documentation for the profile module with::
272
273
273 In [1]: import profile; profile.help()
274 In [1]: import profile; profile.help()
274 """
275 """
275 opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q',
276 opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q',
276 list_all=True, posix=False)
277 list_all=True, posix=False)
277 if cell is not None:
278 if cell is not None:
278 arg_str += '\n' + cell
279 arg_str += '\n' + cell
279 arg_str = self.shell.input_splitter.transform_cell(arg_str)
280 arg_str = self.shell.input_splitter.transform_cell(arg_str)
280 return self._run_with_profiler(arg_str, opts, self.shell.user_ns)
281 return self._run_with_profiler(arg_str, opts, self.shell.user_ns)
281
282
282 def _run_with_profiler(self, code, opts, namespace):
283 def _run_with_profiler(self, code, opts, namespace):
283 """
284 """
284 Run `code` with profiler. Used by ``%prun`` and ``%run -p``.
285 Run `code` with profiler. Used by ``%prun`` and ``%run -p``.
285
286
286 Parameters
287 Parameters
287 ----------
288 ----------
288 code : str
289 code : str
289 Code to be executed.
290 Code to be executed.
290 opts : Struct
291 opts : Struct
291 Options parsed by `self.parse_options`.
292 Options parsed by `self.parse_options`.
292 namespace : dict
293 namespace : dict
293 A dictionary for Python namespace (e.g., `self.shell.user_ns`).
294 A dictionary for Python namespace (e.g., `self.shell.user_ns`).
294
295
295 """
296 """
296
297
297 # Fill default values for unspecified options:
298 # Fill default values for unspecified options:
298 opts.merge(Struct(D=[''], l=[], s=['time'], T=['']))
299 opts.merge(Struct(D=[''], l=[], s=['time'], T=['']))
299
300
300 prof = profile.Profile()
301 prof = profile.Profile()
301 try:
302 try:
302 prof = prof.runctx(code, namespace, namespace)
303 prof = prof.runctx(code, namespace, namespace)
303 sys_exit = ''
304 sys_exit = ''
304 except SystemExit:
305 except SystemExit:
305 sys_exit = """*** SystemExit exception caught in code being profiled."""
306 sys_exit = """*** SystemExit exception caught in code being profiled."""
306
307
307 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
308 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
308
309
309 lims = opts.l
310 lims = opts.l
310 if lims:
311 if lims:
311 lims = [] # rebuild lims with ints/floats/strings
312 lims = [] # rebuild lims with ints/floats/strings
312 for lim in opts.l:
313 for lim in opts.l:
313 try:
314 try:
314 lims.append(int(lim))
315 lims.append(int(lim))
315 except ValueError:
316 except ValueError:
316 try:
317 try:
317 lims.append(float(lim))
318 lims.append(float(lim))
318 except ValueError:
319 except ValueError:
319 lims.append(lim)
320 lims.append(lim)
320
321
321 # Trap output.
322 # Trap output.
322 stdout_trap = StringIO()
323 stdout_trap = StringIO()
323 stats_stream = stats.stream
324 stats_stream = stats.stream
324 try:
325 try:
325 stats.stream = stdout_trap
326 stats.stream = stdout_trap
326 stats.print_stats(*lims)
327 stats.print_stats(*lims)
327 finally:
328 finally:
328 stats.stream = stats_stream
329 stats.stream = stats_stream
329
330
330 output = stdout_trap.getvalue()
331 output = stdout_trap.getvalue()
331 output = output.rstrip()
332 output = output.rstrip()
332
333
333 if 'q' not in opts:
334 if 'q' not in opts:
334 page.page(output)
335 page.page(output)
335 print(sys_exit, end=' ')
336 print(sys_exit, end=' ')
336
337
337 dump_file = opts.D[0]
338 dump_file = opts.D[0]
338 text_file = opts.T[0]
339 text_file = opts.T[0]
339 if dump_file:
340 if dump_file:
340 dump_file = unquote_filename(dump_file)
341 dump_file = unquote_filename(dump_file)
341 prof.dump_stats(dump_file)
342 prof.dump_stats(dump_file)
342 print('\n*** Profile stats marshalled to file',\
343 print('\n*** Profile stats marshalled to file',\
343 repr(dump_file)+'.',sys_exit)
344 repr(dump_file)+'.',sys_exit)
344 if text_file:
345 if text_file:
345 text_file = unquote_filename(text_file)
346 text_file = unquote_filename(text_file)
346 pfile = open(text_file,'w')
347 pfile = open(text_file,'w')
347 pfile.write(output)
348 pfile.write(output)
348 pfile.close()
349 pfile.close()
349 print('\n*** Profile printout saved to text file',\
350 print('\n*** Profile printout saved to text file',\
350 repr(text_file)+'.',sys_exit)
351 repr(text_file)+'.',sys_exit)
351
352
352 if 'r' in opts:
353 if 'r' in opts:
353 return stats
354 return stats
354 else:
355 else:
355 return None
356 return None
356
357
357 @line_magic
358 @line_magic
358 def pdb(self, parameter_s=''):
359 def pdb(self, parameter_s=''):
359 """Control the automatic calling of the pdb interactive debugger.
360 """Control the automatic calling of the pdb interactive debugger.
360
361
361 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
362 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
362 argument it works as a toggle.
363 argument it works as a toggle.
363
364
364 When an exception is triggered, IPython can optionally call the
365 When an exception is triggered, IPython can optionally call the
365 interactive pdb debugger after the traceback printout. %pdb toggles
366 interactive pdb debugger after the traceback printout. %pdb toggles
366 this feature on and off.
367 this feature on and off.
367
368
368 The initial state of this feature is set in your configuration
369 The initial state of this feature is set in your configuration
369 file (the option is ``InteractiveShell.pdb``).
370 file (the option is ``InteractiveShell.pdb``).
370
371
371 If you want to just activate the debugger AFTER an exception has fired,
372 If you want to just activate the debugger AFTER an exception has fired,
372 without having to type '%pdb on' and rerunning your code, you can use
373 without having to type '%pdb on' and rerunning your code, you can use
373 the %debug magic."""
374 the %debug magic."""
374
375
375 par = parameter_s.strip().lower()
376 par = parameter_s.strip().lower()
376
377
377 if par:
378 if par:
378 try:
379 try:
379 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
380 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
380 except KeyError:
381 except KeyError:
381 print ('Incorrect argument. Use on/1, off/0, '
382 print ('Incorrect argument. Use on/1, off/0, '
382 'or nothing for a toggle.')
383 'or nothing for a toggle.')
383 return
384 return
384 else:
385 else:
385 # toggle
386 # toggle
386 new_pdb = not self.shell.call_pdb
387 new_pdb = not self.shell.call_pdb
387
388
388 # set on the shell
389 # set on the shell
389 self.shell.call_pdb = new_pdb
390 self.shell.call_pdb = new_pdb
390 print('Automatic pdb calling has been turned',on_off(new_pdb))
391 print('Automatic pdb calling has been turned',on_off(new_pdb))
391
392
392 @skip_doctest
393 @skip_doctest
393 @magic_arguments.magic_arguments()
394 @magic_arguments.magic_arguments()
394 @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE',
395 @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE',
395 help="""
396 help="""
396 Set break point at LINE in FILE.
397 Set break point at LINE in FILE.
397 """
398 """
398 )
399 )
399 @magic_arguments.argument('statement', nargs='*',
400 @magic_arguments.argument('statement', nargs='*',
400 help="""
401 help="""
401 Code to run in debugger.
402 Code to run in debugger.
402 You can omit this in cell magic mode.
403 You can omit this in cell magic mode.
403 """
404 """
404 )
405 )
405 @line_cell_magic
406 @line_cell_magic
406 def debug(self, line='', cell=None):
407 def debug(self, line='', cell=None):
407 """Activate the interactive debugger.
408 """Activate the interactive debugger.
408
409
409 This magic command support two ways of activating debugger.
410 This magic command support two ways of activating debugger.
410 One is to activate debugger before executing code. This way, you
411 One is to activate debugger before executing code. This way, you
411 can set a break point, to step through the code from the point.
412 can set a break point, to step through the code from the point.
412 You can use this mode by giving statements to execute and optionally
413 You can use this mode by giving statements to execute and optionally
413 a breakpoint.
414 a breakpoint.
414
415
415 The other one is to activate debugger in post-mortem mode. You can
416 The other one is to activate debugger in post-mortem mode. You can
416 activate this mode simply running %debug without any argument.
417 activate this mode simply running %debug without any argument.
417 If an exception has just occurred, this lets you inspect its stack
418 If an exception has just occurred, this lets you inspect its stack
418 frames interactively. Note that this will always work only on the last
419 frames interactively. Note that this will always work only on the last
419 traceback that occurred, so you must call this quickly after an
420 traceback that occurred, so you must call this quickly after an
420 exception that you wish to inspect has fired, because if another one
421 exception that you wish to inspect has fired, because if another one
421 occurs, it clobbers the previous one.
422 occurs, it clobbers the previous one.
422
423
423 If you want IPython to automatically do this on every exception, see
424 If you want IPython to automatically do this on every exception, see
424 the %pdb magic for more details.
425 the %pdb magic for more details.
425 """
426 """
426 args = magic_arguments.parse_argstring(self.debug, line)
427 args = magic_arguments.parse_argstring(self.debug, line)
427
428
428 if not (args.breakpoint or args.statement or cell):
429 if not (args.breakpoint or args.statement or cell):
429 self._debug_post_mortem()
430 self._debug_post_mortem()
430 else:
431 else:
431 code = "\n".join(args.statement)
432 code = "\n".join(args.statement)
432 if cell:
433 if cell:
433 code += "\n" + cell
434 code += "\n" + cell
434 self._debug_exec(code, args.breakpoint)
435 self._debug_exec(code, args.breakpoint)
435
436
436 def _debug_post_mortem(self):
437 def _debug_post_mortem(self):
437 self.shell.debugger(force=True)
438 self.shell.debugger(force=True)
438
439
439 def _debug_exec(self, code, breakpoint):
440 def _debug_exec(self, code, breakpoint):
440 if breakpoint:
441 if breakpoint:
441 (filename, bp_line) = breakpoint.split(':', 1)
442 (filename, bp_line) = breakpoint.split(':', 1)
442 bp_line = int(bp_line)
443 bp_line = int(bp_line)
443 else:
444 else:
444 (filename, bp_line) = (None, None)
445 (filename, bp_line) = (None, None)
445 self._run_with_debugger(code, self.shell.user_ns, filename, bp_line)
446 self._run_with_debugger(code, self.shell.user_ns, filename, bp_line)
446
447
447 @line_magic
448 @line_magic
448 def tb(self, s):
449 def tb(self, s):
449 """Print the last traceback with the currently active exception mode.
450 """Print the last traceback with the currently active exception mode.
450
451
451 See %xmode for changing exception reporting modes."""
452 See %xmode for changing exception reporting modes."""
452 self.shell.showtraceback()
453 self.shell.showtraceback()
453
454
454 @skip_doctest
455 @skip_doctest
455 @line_magic
456 @line_magic
456 def run(self, parameter_s='', runner=None,
457 def run(self, parameter_s='', runner=None,
457 file_finder=get_py_filename):
458 file_finder=get_py_filename):
458 """Run the named file inside IPython as a program.
459 """Run the named file inside IPython as a program.
459
460
460 Usage::
461 Usage::
461
462
462 %run [-n -i -e -G]
463 %run [-n -i -e -G]
463 [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
464 [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
464 ( -m mod | file ) [args]
465 ( -m mod | file ) [args]
465
466
466 Parameters after the filename are passed as command-line arguments to
467 Parameters after the filename are passed as command-line arguments to
467 the program (put in sys.argv). Then, control returns to IPython's
468 the program (put in sys.argv). Then, control returns to IPython's
468 prompt.
469 prompt.
469
470
470 This is similar to running at a system prompt ``python file args``,
471 This is similar to running at a system prompt ``python file args``,
471 but with the advantage of giving you IPython's tracebacks, and of
472 but with the advantage of giving you IPython's tracebacks, and of
472 loading all variables into your interactive namespace for further use
473 loading all variables into your interactive namespace for further use
473 (unless -p is used, see below).
474 (unless -p is used, see below).
474
475
475 The file is executed in a namespace initially consisting only of
476 The file is executed in a namespace initially consisting only of
476 ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus
477 ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus
477 sees its environment as if it were being run as a stand-alone program
478 sees its environment as if it were being run as a stand-alone program
478 (except for sharing global objects such as previously imported
479 (except for sharing global objects such as previously imported
479 modules). But after execution, the IPython interactive namespace gets
480 modules). But after execution, the IPython interactive namespace gets
480 updated with all variables defined in the program (except for __name__
481 updated with all variables defined in the program (except for __name__
481 and sys.argv). This allows for very convenient loading of code for
482 and sys.argv). This allows for very convenient loading of code for
482 interactive work, while giving each program a 'clean sheet' to run in.
483 interactive work, while giving each program a 'clean sheet' to run in.
483
484
484 Arguments are expanded using shell-like glob match. Patterns
485 Arguments are expanded using shell-like glob match. Patterns
485 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
486 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
486 tilde '~' will be expanded into user's home directory. Unlike
487 tilde '~' will be expanded into user's home directory. Unlike
487 real shells, quotation does not suppress expansions. Use
488 real shells, quotation does not suppress expansions. Use
488 *two* back slashes (e.g. ``\\\\*``) to suppress expansions.
489 *two* back slashes (e.g. ``\\\\*``) to suppress expansions.
489 To completely disable these expansions, you can use -G flag.
490 To completely disable these expansions, you can use -G flag.
490
491
491 Options:
492 Options:
492
493
493 -n
494 -n
494 __name__ is NOT set to '__main__', but to the running file's name
495 __name__ is NOT set to '__main__', but to the running file's name
495 without extension (as python does under import). This allows running
496 without extension (as python does under import). This allows running
496 scripts and reloading the definitions in them without calling code
497 scripts and reloading the definitions in them without calling code
497 protected by an ``if __name__ == "__main__"`` clause.
498 protected by an ``if __name__ == "__main__"`` clause.
498
499
499 -i
500 -i
500 run the file in IPython's namespace instead of an empty one. This
501 run the file in IPython's namespace instead of an empty one. This
501 is useful if you are experimenting with code written in a text editor
502 is useful if you are experimenting with code written in a text editor
502 which depends on variables defined interactively.
503 which depends on variables defined interactively.
503
504
504 -e
505 -e
505 ignore sys.exit() calls or SystemExit exceptions in the script
506 ignore sys.exit() calls or SystemExit exceptions in the script
506 being run. This is particularly useful if IPython is being used to
507 being run. This is particularly useful if IPython is being used to
507 run unittests, which always exit with a sys.exit() call. In such
508 run unittests, which always exit with a sys.exit() call. In such
508 cases you are interested in the output of the test results, not in
509 cases you are interested in the output of the test results, not in
509 seeing a traceback of the unittest module.
510 seeing a traceback of the unittest module.
510
511
511 -t
512 -t
512 print timing information at the end of the run. IPython will give
513 print timing information at the end of the run. IPython will give
513 you an estimated CPU time consumption for your script, which under
514 you an estimated CPU time consumption for your script, which under
514 Unix uses the resource module to avoid the wraparound problems of
515 Unix uses the resource module to avoid the wraparound problems of
515 time.clock(). Under Unix, an estimate of time spent on system tasks
516 time.clock(). Under Unix, an estimate of time spent on system tasks
516 is also given (for Windows platforms this is reported as 0.0).
517 is also given (for Windows platforms this is reported as 0.0).
517
518
518 If -t is given, an additional ``-N<N>`` option can be given, where <N>
519 If -t is given, an additional ``-N<N>`` option can be given, where <N>
519 must be an integer indicating how many times you want the script to
520 must be an integer indicating how many times you want the script to
520 run. The final timing report will include total and per run results.
521 run. The final timing report will include total and per run results.
521
522
522 For example (testing the script uniq_stable.py)::
523 For example (testing the script uniq_stable.py)::
523
524
524 In [1]: run -t uniq_stable
525 In [1]: run -t uniq_stable
525
526
526 IPython CPU timings (estimated):
527 IPython CPU timings (estimated):
527 User : 0.19597 s.
528 User : 0.19597 s.
528 System: 0.0 s.
529 System: 0.0 s.
529
530
530 In [2]: run -t -N5 uniq_stable
531 In [2]: run -t -N5 uniq_stable
531
532
532 IPython CPU timings (estimated):
533 IPython CPU timings (estimated):
533 Total runs performed: 5
534 Total runs performed: 5
534 Times : Total Per run
535 Times : Total Per run
535 User : 0.910862 s, 0.1821724 s.
536 User : 0.910862 s, 0.1821724 s.
536 System: 0.0 s, 0.0 s.
537 System: 0.0 s, 0.0 s.
537
538
538 -d
539 -d
539 run your program under the control of pdb, the Python debugger.
540 run your program under the control of pdb, the Python debugger.
540 This allows you to execute your program step by step, watch variables,
541 This allows you to execute your program step by step, watch variables,
541 etc. Internally, what IPython does is similar to calling::
542 etc. Internally, what IPython does is similar to calling::
542
543
543 pdb.run('execfile("YOURFILENAME")')
544 pdb.run('execfile("YOURFILENAME")')
544
545
545 with a breakpoint set on line 1 of your file. You can change the line
546 with a breakpoint set on line 1 of your file. You can change the line
546 number for this automatic breakpoint to be <N> by using the -bN option
547 number for this automatic breakpoint to be <N> by using the -bN option
547 (where N must be an integer). For example::
548 (where N must be an integer). For example::
548
549
549 %run -d -b40 myscript
550 %run -d -b40 myscript
550
551
551 will set the first breakpoint at line 40 in myscript.py. Note that
552 will set the first breakpoint at line 40 in myscript.py. Note that
552 the first breakpoint must be set on a line which actually does
553 the first breakpoint must be set on a line which actually does
553 something (not a comment or docstring) for it to stop execution.
554 something (not a comment or docstring) for it to stop execution.
554
555
555 Or you can specify a breakpoint in a different file::
556 Or you can specify a breakpoint in a different file::
556
557
557 %run -d -b myotherfile.py:20 myscript
558 %run -d -b myotherfile.py:20 myscript
558
559
559 When the pdb debugger starts, you will see a (Pdb) prompt. You must
560 When the pdb debugger starts, you will see a (Pdb) prompt. You must
560 first enter 'c' (without quotes) to start execution up to the first
561 first enter 'c' (without quotes) to start execution up to the first
561 breakpoint.
562 breakpoint.
562
563
563 Entering 'help' gives information about the use of the debugger. You
564 Entering 'help' gives information about the use of the debugger. You
564 can easily see pdb's full documentation with "import pdb;pdb.help()"
565 can easily see pdb's full documentation with "import pdb;pdb.help()"
565 at a prompt.
566 at a prompt.
566
567
567 -p
568 -p
568 run program under the control of the Python profiler module (which
569 run program under the control of the Python profiler module (which
569 prints a detailed report of execution times, function calls, etc).
570 prints a detailed report of execution times, function calls, etc).
570
571
571 You can pass other options after -p which affect the behavior of the
572 You can pass other options after -p which affect the behavior of the
572 profiler itself. See the docs for %prun for details.
573 profiler itself. See the docs for %prun for details.
573
574
574 In this mode, the program's variables do NOT propagate back to the
575 In this mode, the program's variables do NOT propagate back to the
575 IPython interactive namespace (because they remain in the namespace
576 IPython interactive namespace (because they remain in the namespace
576 where the profiler executes them).
577 where the profiler executes them).
577
578
578 Internally this triggers a call to %prun, see its documentation for
579 Internally this triggers a call to %prun, see its documentation for
579 details on the options available specifically for profiling.
580 details on the options available specifically for profiling.
580
581
581 There is one special usage for which the text above doesn't apply:
582 There is one special usage for which the text above doesn't apply:
582 if the filename ends with .ipy[nb], the file is run as ipython script,
583 if the filename ends with .ipy[nb], the file is run as ipython script,
583 just as if the commands were written on IPython prompt.
584 just as if the commands were written on IPython prompt.
584
585
585 -m
586 -m
586 specify module name to load instead of script path. Similar to
587 specify module name to load instead of script path. Similar to
587 the -m option for the python interpreter. Use this option last if you
588 the -m option for the python interpreter. Use this option last if you
588 want to combine with other %run options. Unlike the python interpreter
589 want to combine with other %run options. Unlike the python interpreter
589 only source modules are allowed no .pyc or .pyo files.
590 only source modules are allowed no .pyc or .pyo files.
590 For example::
591 For example::
591
592
592 %run -m example
593 %run -m example
593
594
594 will run the example module.
595 will run the example module.
595
596
596 -G
597 -G
597 disable shell-like glob expansion of arguments.
598 disable shell-like glob expansion of arguments.
598
599
599 """
600 """
600
601
601 # get arguments and set sys.argv for program to be run.
602 # get arguments and set sys.argv for program to be run.
602 opts, arg_lst = self.parse_options(parameter_s,
603 opts, arg_lst = self.parse_options(parameter_s,
603 'nidtN:b:pD:l:rs:T:em:G',
604 'nidtN:b:pD:l:rs:T:em:G',
604 mode='list', list_all=1)
605 mode='list', list_all=1)
605 if "m" in opts:
606 if "m" in opts:
606 modulename = opts["m"][0]
607 modulename = opts["m"][0]
607 modpath = find_mod(modulename)
608 modpath = find_mod(modulename)
608 if modpath is None:
609 if modpath is None:
609 warn('%r is not a valid modulename on sys.path'%modulename)
610 warn('%r is not a valid modulename on sys.path'%modulename)
610 return
611 return
611 arg_lst = [modpath] + arg_lst
612 arg_lst = [modpath] + arg_lst
612 try:
613 try:
613 filename = file_finder(arg_lst[0])
614 filename = file_finder(arg_lst[0])
614 except IndexError:
615 except IndexError:
615 warn('you must provide at least a filename.')
616 warn('you must provide at least a filename.')
616 print('\n%run:\n', oinspect.getdoc(self.run))
617 print('\n%run:\n', oinspect.getdoc(self.run))
617 return
618 return
618 except IOError as e:
619 except IOError as e:
619 try:
620 try:
620 msg = str(e)
621 msg = str(e)
621 except UnicodeError:
622 except UnicodeError:
622 msg = e.message
623 msg = e.message
623 error(msg)
624 error(msg)
624 return
625 return
625
626
626 if filename.lower().endswith(('.ipy', '.ipynb')):
627 if filename.lower().endswith(('.ipy', '.ipynb')):
627 with preserve_keys(self.shell.user_ns, '__file__'):
628 with preserve_keys(self.shell.user_ns, '__file__'):
628 self.shell.user_ns['__file__'] = filename
629 self.shell.user_ns['__file__'] = filename
629 self.shell.safe_execfile_ipy(filename)
630 self.shell.safe_execfile_ipy(filename)
630 return
631 return
631
632
632 # Control the response to exit() calls made by the script being run
633 # Control the response to exit() calls made by the script being run
633 exit_ignore = 'e' in opts
634 exit_ignore = 'e' in opts
634
635
635 # Make sure that the running script gets a proper sys.argv as if it
636 # Make sure that the running script gets a proper sys.argv as if it
636 # were run from a system shell.
637 # were run from a system shell.
637 save_argv = sys.argv # save it for later restoring
638 save_argv = sys.argv # save it for later restoring
638
639
639 if 'G' in opts:
640 if 'G' in opts:
640 args = arg_lst[1:]
641 args = arg_lst[1:]
641 else:
642 else:
642 # tilde and glob expansion
643 # tilde and glob expansion
643 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
644 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
644
645
645 sys.argv = [filename] + args # put in the proper filename
646 sys.argv = [filename] + args # put in the proper filename
646 # protect sys.argv from potential unicode strings on Python 2:
647 # protect sys.argv from potential unicode strings on Python 2:
647 if not py3compat.PY3:
648 if not py3compat.PY3:
648 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
649 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
649
650
650 if 'i' in opts:
651 if 'i' in opts:
651 # Run in user's interactive namespace
652 # Run in user's interactive namespace
652 prog_ns = self.shell.user_ns
653 prog_ns = self.shell.user_ns
653 __name__save = self.shell.user_ns['__name__']
654 __name__save = self.shell.user_ns['__name__']
654 prog_ns['__name__'] = '__main__'
655 prog_ns['__name__'] = '__main__'
655 main_mod = self.shell.user_module
656 main_mod = self.shell.user_module
656
657
657 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
658 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
658 # set the __file__ global in the script's namespace
659 # set the __file__ global in the script's namespace
659 # TK: Is this necessary in interactive mode?
660 # TK: Is this necessary in interactive mode?
660 prog_ns['__file__'] = filename
661 prog_ns['__file__'] = filename
661 else:
662 else:
662 # Run in a fresh, empty namespace
663 # Run in a fresh, empty namespace
663 if 'n' in opts:
664 if 'n' in opts:
664 name = os.path.splitext(os.path.basename(filename))[0]
665 name = os.path.splitext(os.path.basename(filename))[0]
665 else:
666 else:
666 name = '__main__'
667 name = '__main__'
667
668
668 # The shell MUST hold a reference to prog_ns so after %run
669 # The shell MUST hold a reference to prog_ns so after %run
669 # exits, the python deletion mechanism doesn't zero it out
670 # exits, the python deletion mechanism doesn't zero it out
670 # (leaving dangling references). See interactiveshell for details
671 # (leaving dangling references). See interactiveshell for details
671 main_mod = self.shell.new_main_mod(filename, name)
672 main_mod = self.shell.new_main_mod(filename, name)
672 prog_ns = main_mod.__dict__
673 prog_ns = main_mod.__dict__
673
674
674 # pickle fix. See interactiveshell for an explanation. But we need to
675 # pickle fix. See interactiveshell for an explanation. But we need to
675 # make sure that, if we overwrite __main__, we replace it at the end
676 # make sure that, if we overwrite __main__, we replace it at the end
676 main_mod_name = prog_ns['__name__']
677 main_mod_name = prog_ns['__name__']
677
678
678 if main_mod_name == '__main__':
679 if main_mod_name == '__main__':
679 restore_main = sys.modules['__main__']
680 restore_main = sys.modules['__main__']
680 else:
681 else:
681 restore_main = False
682 restore_main = False
682
683
683 # This needs to be undone at the end to prevent holding references to
684 # This needs to be undone at the end to prevent holding references to
684 # every single object ever created.
685 # every single object ever created.
685 sys.modules[main_mod_name] = main_mod
686 sys.modules[main_mod_name] = main_mod
686
687
687 if 'p' in opts or 'd' in opts:
688 if 'p' in opts or 'd' in opts:
688 if 'm' in opts:
689 if 'm' in opts:
689 code = 'run_module(modulename, prog_ns)'
690 code = 'run_module(modulename, prog_ns)'
690 code_ns = {
691 code_ns = {
691 'run_module': self.shell.safe_run_module,
692 'run_module': self.shell.safe_run_module,
692 'prog_ns': prog_ns,
693 'prog_ns': prog_ns,
693 'modulename': modulename,
694 'modulename': modulename,
694 }
695 }
695 else:
696 else:
696 if 'd' in opts:
697 if 'd' in opts:
697 # allow exceptions to raise in debug mode
698 # allow exceptions to raise in debug mode
698 code = 'execfile(filename, prog_ns, raise_exceptions=True)'
699 code = 'execfile(filename, prog_ns, raise_exceptions=True)'
699 else:
700 else:
700 code = 'execfile(filename, prog_ns)'
701 code = 'execfile(filename, prog_ns)'
701 code_ns = {
702 code_ns = {
702 'execfile': self.shell.safe_execfile,
703 'execfile': self.shell.safe_execfile,
703 'prog_ns': prog_ns,
704 'prog_ns': prog_ns,
704 'filename': get_py_filename(filename),
705 'filename': get_py_filename(filename),
705 }
706 }
706
707
707 try:
708 try:
708 stats = None
709 stats = None
709 with self.shell.readline_no_record:
710 with self.shell.readline_no_record:
710 if 'p' in opts:
711 if 'p' in opts:
711 stats = self._run_with_profiler(code, opts, code_ns)
712 stats = self._run_with_profiler(code, opts, code_ns)
712 else:
713 else:
713 if 'd' in opts:
714 if 'd' in opts:
714 bp_file, bp_line = parse_breakpoint(
715 bp_file, bp_line = parse_breakpoint(
715 opts.get('b', ['1'])[0], filename)
716 opts.get('b', ['1'])[0], filename)
716 self._run_with_debugger(
717 self._run_with_debugger(
717 code, code_ns, filename, bp_line, bp_file)
718 code, code_ns, filename, bp_line, bp_file)
718 else:
719 else:
719 if 'm' in opts:
720 if 'm' in opts:
720 def run():
721 def run():
721 self.shell.safe_run_module(modulename, prog_ns)
722 self.shell.safe_run_module(modulename, prog_ns)
722 else:
723 else:
723 if runner is None:
724 if runner is None:
724 runner = self.default_runner
725 runner = self.default_runner
725 if runner is None:
726 if runner is None:
726 runner = self.shell.safe_execfile
727 runner = self.shell.safe_execfile
727
728
728 def run():
729 def run():
729 runner(filename, prog_ns, prog_ns,
730 runner(filename, prog_ns, prog_ns,
730 exit_ignore=exit_ignore)
731 exit_ignore=exit_ignore)
731
732
732 if 't' in opts:
733 if 't' in opts:
733 # timed execution
734 # timed execution
734 try:
735 try:
735 nruns = int(opts['N'][0])
736 nruns = int(opts['N'][0])
736 if nruns < 1:
737 if nruns < 1:
737 error('Number of runs must be >=1')
738 error('Number of runs must be >=1')
738 return
739 return
739 except (KeyError):
740 except (KeyError):
740 nruns = 1
741 nruns = 1
741 self._run_with_timing(run, nruns)
742 self._run_with_timing(run, nruns)
742 else:
743 else:
743 # regular execution
744 # regular execution
744 run()
745 run()
745
746
746 if 'i' in opts:
747 if 'i' in opts:
747 self.shell.user_ns['__name__'] = __name__save
748 self.shell.user_ns['__name__'] = __name__save
748 else:
749 else:
749 # update IPython interactive namespace
750 # update IPython interactive namespace
750
751
751 # Some forms of read errors on the file may mean the
752 # Some forms of read errors on the file may mean the
752 # __name__ key was never set; using pop we don't have to
753 # __name__ key was never set; using pop we don't have to
753 # worry about a possible KeyError.
754 # worry about a possible KeyError.
754 prog_ns.pop('__name__', None)
755 prog_ns.pop('__name__', None)
755
756
756 with preserve_keys(self.shell.user_ns, '__file__'):
757 with preserve_keys(self.shell.user_ns, '__file__'):
757 self.shell.user_ns.update(prog_ns)
758 self.shell.user_ns.update(prog_ns)
758 finally:
759 finally:
759 # It's a bit of a mystery why, but __builtins__ can change from
760 # It's a bit of a mystery why, but __builtins__ can change from
760 # being a module to becoming a dict missing some key data after
761 # being a module to becoming a dict missing some key data after
761 # %run. As best I can see, this is NOT something IPython is doing
762 # %run. As best I can see, this is NOT something IPython is doing
762 # at all, and similar problems have been reported before:
763 # at all, and similar problems have been reported before:
763 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
764 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
764 # Since this seems to be done by the interpreter itself, the best
765 # Since this seems to be done by the interpreter itself, the best
765 # we can do is to at least restore __builtins__ for the user on
766 # we can do is to at least restore __builtins__ for the user on
766 # exit.
767 # exit.
767 self.shell.user_ns['__builtins__'] = builtin_mod
768 self.shell.user_ns['__builtins__'] = builtin_mod
768
769
769 # Ensure key global structures are restored
770 # Ensure key global structures are restored
770 sys.argv = save_argv
771 sys.argv = save_argv
771 if restore_main:
772 if restore_main:
772 sys.modules['__main__'] = restore_main
773 sys.modules['__main__'] = restore_main
773 else:
774 else:
774 # Remove from sys.modules the reference to main_mod we'd
775 # Remove from sys.modules the reference to main_mod we'd
775 # added. Otherwise it will trap references to objects
776 # added. Otherwise it will trap references to objects
776 # contained therein.
777 # contained therein.
777 del sys.modules[main_mod_name]
778 del sys.modules[main_mod_name]
778
779
779 return stats
780 return stats
780
781
781 def _run_with_debugger(self, code, code_ns, filename=None,
782 def _run_with_debugger(self, code, code_ns, filename=None,
782 bp_line=None, bp_file=None):
783 bp_line=None, bp_file=None):
783 """
784 """
784 Run `code` in debugger with a break point.
785 Run `code` in debugger with a break point.
785
786
786 Parameters
787 Parameters
787 ----------
788 ----------
788 code : str
789 code : str
789 Code to execute.
790 Code to execute.
790 code_ns : dict
791 code_ns : dict
791 A namespace in which `code` is executed.
792 A namespace in which `code` is executed.
792 filename : str
793 filename : str
793 `code` is ran as if it is in `filename`.
794 `code` is ran as if it is in `filename`.
794 bp_line : int, optional
795 bp_line : int, optional
795 Line number of the break point.
796 Line number of the break point.
796 bp_file : str, optional
797 bp_file : str, optional
797 Path to the file in which break point is specified.
798 Path to the file in which break point is specified.
798 `filename` is used if not given.
799 `filename` is used if not given.
799
800
800 Raises
801 Raises
801 ------
802 ------
802 UsageError
803 UsageError
803 If the break point given by `bp_line` is not valid.
804 If the break point given by `bp_line` is not valid.
804
805
805 """
806 """
806 deb = debugger.Pdb(self.shell.colors)
807 deb = debugger.Pdb(self.shell.colors)
807 # reset Breakpoint state, which is moronically kept
808 # reset Breakpoint state, which is moronically kept
808 # in a class
809 # in a class
809 bdb.Breakpoint.next = 1
810 bdb.Breakpoint.next = 1
810 bdb.Breakpoint.bplist = {}
811 bdb.Breakpoint.bplist = {}
811 bdb.Breakpoint.bpbynumber = [None]
812 bdb.Breakpoint.bpbynumber = [None]
812 if bp_line is not None:
813 if bp_line is not None:
813 # Set an initial breakpoint to stop execution
814 # Set an initial breakpoint to stop execution
814 maxtries = 10
815 maxtries = 10
815 bp_file = bp_file or filename
816 bp_file = bp_file or filename
816 checkline = deb.checkline(bp_file, bp_line)
817 checkline = deb.checkline(bp_file, bp_line)
817 if not checkline:
818 if not checkline:
818 for bp in range(bp_line + 1, bp_line + maxtries + 1):
819 for bp in range(bp_line + 1, bp_line + maxtries + 1):
819 if deb.checkline(bp_file, bp):
820 if deb.checkline(bp_file, bp):
820 break
821 break
821 else:
822 else:
822 msg = ("\nI failed to find a valid line to set "
823 msg = ("\nI failed to find a valid line to set "
823 "a breakpoint\n"
824 "a breakpoint\n"
824 "after trying up to line: %s.\n"
825 "after trying up to line: %s.\n"
825 "Please set a valid breakpoint manually "
826 "Please set a valid breakpoint manually "
826 "with the -b option." % bp)
827 "with the -b option." % bp)
827 raise UsageError(msg)
828 raise UsageError(msg)
828 # if we find a good linenumber, set the breakpoint
829 # if we find a good linenumber, set the breakpoint
829 deb.do_break('%s:%s' % (bp_file, bp_line))
830 deb.do_break('%s:%s' % (bp_file, bp_line))
830
831
831 if filename:
832 if filename:
832 # Mimic Pdb._runscript(...)
833 # Mimic Pdb._runscript(...)
833 deb._wait_for_mainpyfile = True
834 deb._wait_for_mainpyfile = True
834 deb.mainpyfile = deb.canonic(filename)
835 deb.mainpyfile = deb.canonic(filename)
835
836
836 # Start file run
837 # Start file run
837 print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt)
838 print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt)
838 try:
839 try:
839 if filename:
840 if filename:
840 # save filename so it can be used by methods on the deb object
841 # save filename so it can be used by methods on the deb object
841 deb._exec_filename = filename
842 deb._exec_filename = filename
842 while True:
843 while True:
843 try:
844 try:
844 deb.run(code, code_ns)
845 deb.run(code, code_ns)
845 except Restart:
846 except Restart:
846 print("Restarting")
847 print("Restarting")
847 if filename:
848 if filename:
848 deb._wait_for_mainpyfile = True
849 deb._wait_for_mainpyfile = True
849 deb.mainpyfile = deb.canonic(filename)
850 deb.mainpyfile = deb.canonic(filename)
850 continue
851 continue
851 else:
852 else:
852 break
853 break
853
854
854
855
855 except:
856 except:
856 etype, value, tb = sys.exc_info()
857 etype, value, tb = sys.exc_info()
857 # Skip three frames in the traceback: the %run one,
858 # Skip three frames in the traceback: the %run one,
858 # one inside bdb.py, and the command-line typed by the
859 # one inside bdb.py, and the command-line typed by the
859 # user (run by exec in pdb itself).
860 # user (run by exec in pdb itself).
860 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
861 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
861
862
862 @staticmethod
863 @staticmethod
863 def _run_with_timing(run, nruns):
864 def _run_with_timing(run, nruns):
864 """
865 """
865 Run function `run` and print timing information.
866 Run function `run` and print timing information.
866
867
867 Parameters
868 Parameters
868 ----------
869 ----------
869 run : callable
870 run : callable
870 Any callable object which takes no argument.
871 Any callable object which takes no argument.
871 nruns : int
872 nruns : int
872 Number of times to execute `run`.
873 Number of times to execute `run`.
873
874
874 """
875 """
875 twall0 = time.time()
876 twall0 = time.time()
876 if nruns == 1:
877 if nruns == 1:
877 t0 = clock2()
878 t0 = clock2()
878 run()
879 run()
879 t1 = clock2()
880 t1 = clock2()
880 t_usr = t1[0] - t0[0]
881 t_usr = t1[0] - t0[0]
881 t_sys = t1[1] - t0[1]
882 t_sys = t1[1] - t0[1]
882 print("\nIPython CPU timings (estimated):")
883 print("\nIPython CPU timings (estimated):")
883 print(" User : %10.2f s." % t_usr)
884 print(" User : %10.2f s." % t_usr)
884 print(" System : %10.2f s." % t_sys)
885 print(" System : %10.2f s." % t_sys)
885 else:
886 else:
886 runs = range(nruns)
887 runs = range(nruns)
887 t0 = clock2()
888 t0 = clock2()
888 for nr in runs:
889 for nr in runs:
889 run()
890 run()
890 t1 = clock2()
891 t1 = clock2()
891 t_usr = t1[0] - t0[0]
892 t_usr = t1[0] - t0[0]
892 t_sys = t1[1] - t0[1]
893 t_sys = t1[1] - t0[1]
893 print("\nIPython CPU timings (estimated):")
894 print("\nIPython CPU timings (estimated):")
894 print("Total runs performed:", nruns)
895 print("Total runs performed:", nruns)
895 print(" Times : %10s %10s" % ('Total', 'Per run'))
896 print(" Times : %10s %10s" % ('Total', 'Per run'))
896 print(" User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns))
897 print(" User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns))
897 print(" System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns))
898 print(" System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns))
898 twall1 = time.time()
899 twall1 = time.time()
899 print("Wall time: %10.2f s." % (twall1 - twall0))
900 print("Wall time: %10.2f s." % (twall1 - twall0))
900
901
901 @skip_doctest
902 @skip_doctest
902 @line_cell_magic
903 @line_cell_magic
903 def timeit(self, line='', cell=None):
904 def timeit(self, line='', cell=None):
904 """Time execution of a Python statement or expression
905 """Time execution of a Python statement or expression
905
906
906 Usage, in line mode:
907 Usage, in line mode:
907 %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
908 %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
908 or in cell mode:
909 or in cell mode:
909 %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
910 %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
910 code
911 code
911 code...
912 code...
912
913
913 Time execution of a Python statement or expression using the timeit
914 Time execution of a Python statement or expression using the timeit
914 module. This function can be used both as a line and cell magic:
915 module. This function can be used both as a line and cell magic:
915
916
916 - In line mode you can time a single-line statement (though multiple
917 - In line mode you can time a single-line statement (though multiple
917 ones can be chained with using semicolons).
918 ones can be chained with using semicolons).
918
919
919 - In cell mode, the statement in the first line is used as setup code
920 - In cell mode, the statement in the first line is used as setup code
920 (executed but not timed) and the body of the cell is timed. The cell
921 (executed but not timed) and the body of the cell is timed. The cell
921 body has access to any variables created in the setup code.
922 body has access to any variables created in the setup code.
922
923
923 Options:
924 Options:
924 -n<N>: execute the given statement <N> times in a loop. If this value
925 -n<N>: execute the given statement <N> times in a loop. If this value
925 is not given, a fitting value is chosen.
926 is not given, a fitting value is chosen.
926
927
927 -r<R>: repeat the loop iteration <R> times and take the best result.
928 -r<R>: repeat the loop iteration <R> times and take the best result.
928 Default: 3
929 Default: 3
929
930
930 -t: use time.time to measure the time, which is the default on Unix.
931 -t: use time.time to measure the time, which is the default on Unix.
931 This function measures wall time.
932 This function measures wall time.
932
933
933 -c: use time.clock to measure the time, which is the default on
934 -c: use time.clock to measure the time, which is the default on
934 Windows and measures wall time. On Unix, resource.getrusage is used
935 Windows and measures wall time. On Unix, resource.getrusage is used
935 instead and returns the CPU user time.
936 instead and returns the CPU user time.
936
937
937 -p<P>: use a precision of <P> digits to display the timing result.
938 -p<P>: use a precision of <P> digits to display the timing result.
938 Default: 3
939 Default: 3
939
940
940 -q: Quiet, do not print result.
941 -q: Quiet, do not print result.
941
942
942 -o: return a TimeitResult that can be stored in a variable to inspect
943 -o: return a TimeitResult that can be stored in a variable to inspect
943 the result in more details.
944 the result in more details.
944
945
945
946
946 Examples
947 Examples
947 --------
948 --------
948 ::
949 ::
949
950
950 In [1]: %timeit pass
951 In [1]: %timeit pass
951 10000000 loops, best of 3: 53.3 ns per loop
952 10000000 loops, best of 3: 53.3 ns per loop
952
953
953 In [2]: u = None
954 In [2]: u = None
954
955
955 In [3]: %timeit u is None
956 In [3]: %timeit u is None
956 10000000 loops, best of 3: 184 ns per loop
957 10000000 loops, best of 3: 184 ns per loop
957
958
958 In [4]: %timeit -r 4 u == None
959 In [4]: %timeit -r 4 u == None
959 1000000 loops, best of 4: 242 ns per loop
960 1000000 loops, best of 4: 242 ns per loop
960
961
961 In [5]: import time
962 In [5]: import time
962
963
963 In [6]: %timeit -n1 time.sleep(2)
964 In [6]: %timeit -n1 time.sleep(2)
964 1 loop, best of 3: 2 s per loop
965 1 loop, best of 3: 2 s per loop
965
966
966
967
967 The times reported by %timeit will be slightly higher than those
968 The times reported by %timeit will be slightly higher than those
968 reported by the timeit.py script when variables are accessed. This is
969 reported by the timeit.py script when variables are accessed. This is
969 due to the fact that %timeit executes the statement in the namespace
970 due to the fact that %timeit executes the statement in the namespace
970 of the shell, compared with timeit.py, which uses a single setup
971 of the shell, compared with timeit.py, which uses a single setup
971 statement to import function or create variables. Generally, the bias
972 statement to import function or create variables. Generally, the bias
972 does not matter as long as results from timeit.py are not mixed with
973 does not matter as long as results from timeit.py are not mixed with
973 those from %timeit."""
974 those from %timeit."""
974
975
975 opts, stmt = self.parse_options(line,'n:r:tcp:qo',
976 opts, stmt = self.parse_options(line,'n:r:tcp:qo',
976 posix=False, strict=False)
977 posix=False, strict=False)
977 if stmt == "" and cell is None:
978 if stmt == "" and cell is None:
978 return
979 return
979
980
980 timefunc = timeit.default_timer
981 timefunc = timeit.default_timer
981 number = int(getattr(opts, "n", 0))
982 number = int(getattr(opts, "n", 0))
982 repeat = int(getattr(opts, "r", timeit.default_repeat))
983 repeat = int(getattr(opts, "r", timeit.default_repeat))
983 precision = int(getattr(opts, "p", 3))
984 precision = int(getattr(opts, "p", 3))
984 quiet = 'q' in opts
985 quiet = 'q' in opts
985 return_result = 'o' in opts
986 return_result = 'o' in opts
986 if hasattr(opts, "t"):
987 if hasattr(opts, "t"):
987 timefunc = time.time
988 timefunc = time.time
988 if hasattr(opts, "c"):
989 if hasattr(opts, "c"):
989 timefunc = clock
990 timefunc = clock
990
991
991 timer = Timer(timer=timefunc)
992 timer = Timer(timer=timefunc)
992 # this code has tight coupling to the inner workings of timeit.Timer,
993 # this code has tight coupling to the inner workings of timeit.Timer,
993 # but is there a better way to achieve that the code stmt has access
994 # but is there a better way to achieve that the code stmt has access
994 # to the shell namespace?
995 # to the shell namespace?
995 transform = self.shell.input_splitter.transform_cell
996 transform = self.shell.input_splitter.transform_cell
996
997
997 if cell is None:
998 if cell is None:
998 # called as line magic
999 # called as line magic
999 ast_setup = self.shell.compile.ast_parse("pass")
1000 ast_setup = self.shell.compile.ast_parse("pass")
1000 ast_stmt = self.shell.compile.ast_parse(transform(stmt))
1001 ast_stmt = self.shell.compile.ast_parse(transform(stmt))
1001 else:
1002 else:
1002 ast_setup = self.shell.compile.ast_parse(transform(stmt))
1003 ast_setup = self.shell.compile.ast_parse(transform(stmt))
1003 ast_stmt = self.shell.compile.ast_parse(transform(cell))
1004 ast_stmt = self.shell.compile.ast_parse(transform(cell))
1004
1005
1005 ast_setup = self.shell.transform_ast(ast_setup)
1006 ast_setup = self.shell.transform_ast(ast_setup)
1006 ast_stmt = self.shell.transform_ast(ast_stmt)
1007 ast_stmt = self.shell.transform_ast(ast_stmt)
1007
1008
1008 # This codestring is taken from timeit.template - we fill it in as an
1009 # This codestring is taken from timeit.template - we fill it in as an
1009 # AST, so that we can apply our AST transformations to the user code
1010 # AST, so that we can apply our AST transformations to the user code
1010 # without affecting the timing code.
1011 # without affecting the timing code.
1011 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
1012 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
1012 ' setup\n'
1013 ' setup\n'
1013 ' _t0 = _timer()\n'
1014 ' _t0 = _timer()\n'
1014 ' for _i in _it:\n'
1015 ' for _i in _it:\n'
1015 ' stmt\n'
1016 ' stmt\n'
1016 ' _t1 = _timer()\n'
1017 ' _t1 = _timer()\n'
1017 ' return _t1 - _t0\n')
1018 ' return _t1 - _t0\n')
1018
1019
1019 timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template)
1020 timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template)
1020 timeit_ast = ast.fix_missing_locations(timeit_ast)
1021 timeit_ast = ast.fix_missing_locations(timeit_ast)
1021
1022
1022 # Track compilation time so it can be reported if too long
1023 # Track compilation time so it can be reported if too long
1023 # Minimum time above which compilation time will be reported
1024 # Minimum time above which compilation time will be reported
1024 tc_min = 0.1
1025 tc_min = 0.1
1025
1026
1026 t0 = clock()
1027 t0 = clock()
1027 code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec")
1028 code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec")
1028 tc = clock()-t0
1029 tc = clock()-t0
1029
1030
1030 ns = {}
1031 ns = {}
1031 exec(code, self.shell.user_ns, ns)
1032 exec(code, self.shell.user_ns, ns)
1032 timer.inner = ns["inner"]
1033 timer.inner = ns["inner"]
1033
1034
1034 # This is used to check if there is a huge difference between the
1035 # This is used to check if there is a huge difference between the
1035 # best and worst timings.
1036 # best and worst timings.
1036 # Issue: https://github.com/ipython/ipython/issues/6471
1037 # Issue: https://github.com/ipython/ipython/issues/6471
1037 worst_tuning = 0
1038 worst_tuning = 0
1038 if number == 0:
1039 if number == 0:
1039 # determine number so that 0.2 <= total time < 2.0
1040 # determine number so that 0.2 <= total time < 2.0
1040 number = 1
1041 number = 1
1041 for _ in range(1, 10):
1042 for _ in range(1, 10):
1042 time_number = timer.timeit(number)
1043 time_number = timer.timeit(number)
1043 worst_tuning = max(worst_tuning, time_number / number)
1044 worst_tuning = max(worst_tuning, time_number / number)
1044 if time_number >= 0.2:
1045 if time_number >= 0.2:
1045 break
1046 break
1046 number *= 10
1047 number *= 10
1047 all_runs = timer.repeat(repeat, number)
1048 all_runs = timer.repeat(repeat, number)
1048 best = min(all_runs) / number
1049 best = min(all_runs) / number
1049
1050
1050 worst = max(all_runs) / number
1051 worst = max(all_runs) / number
1051 if worst_tuning:
1052 if worst_tuning:
1052 worst = max(worst, worst_tuning)
1053 worst = max(worst, worst_tuning)
1053
1054
1054 if not quiet :
1055 if not quiet :
1055 # Check best timing is greater than zero to avoid a
1056 # Check best timing is greater than zero to avoid a
1056 # ZeroDivisionError.
1057 # ZeroDivisionError.
1057 # In cases where the slowest timing is lesser than a micosecond
1058 # In cases where the slowest timing is lesser than a micosecond
1058 # we assume that it does not really matter if the fastest
1059 # we assume that it does not really matter if the fastest
1059 # timing is 4 times faster than the slowest timing or not.
1060 # timing is 4 times faster than the slowest timing or not.
1060 if worst > 4 * best and best > 0 and worst > 1e-6:
1061 if worst > 4 * best and best > 0 and worst > 1e-6:
1061 print("The slowest run took %0.2f times longer than the "
1062 print("The slowest run took %0.2f times longer than the "
1062 "fastest. This could mean that an intermediate result "
1063 "fastest. This could mean that an intermediate result "
1063 "is being cached." % (worst / best))
1064 "is being cached." % (worst / best))
1064 if number == 1: # No s at "loops" if only one loop
1065 if number == 1: # No s at "loops" if only one loop
1065 print(u"%d loop, best of %d: %s per loop" % (number, repeat,
1066 print(u"%d loop, best of %d: %s per loop" % (number, repeat,
1066 _format_time(best, precision)))
1067 _format_time(best, precision)))
1067 else:
1068 else:
1068 print(u"%d loops, best of %d: %s per loop" % (number, repeat,
1069 print(u"%d loops, best of %d: %s per loop" % (number, repeat,
1069 _format_time(best, precision)))
1070 _format_time(best, precision)))
1070 if tc > tc_min:
1071 if tc > tc_min:
1071 print("Compiler time: %.2f s" % tc)
1072 print("Compiler time: %.2f s" % tc)
1072 if return_result:
1073 if return_result:
1073 return TimeitResult(number, repeat, best, worst, all_runs, tc, precision)
1074 return TimeitResult(number, repeat, best, worst, all_runs, tc, precision)
1074
1075
1075 @skip_doctest
1076 @skip_doctest
1076 @needs_local_scope
1077 @needs_local_scope
1077 @line_cell_magic
1078 @line_cell_magic
1078 def time(self,line='', cell=None, local_ns=None):
1079 def time(self,line='', cell=None, local_ns=None):
1079 """Time execution of a Python statement or expression.
1080 """Time execution of a Python statement or expression.
1080
1081
1081 The CPU and wall clock times are printed, and the value of the
1082 The CPU and wall clock times are printed, and the value of the
1082 expression (if any) is returned. Note that under Win32, system time
1083 expression (if any) is returned. Note that under Win32, system time
1083 is always reported as 0, since it can not be measured.
1084 is always reported as 0, since it can not be measured.
1084
1085
1085 This function can be used both as a line and cell magic:
1086 This function can be used both as a line and cell magic:
1086
1087
1087 - In line mode you can time a single-line statement (though multiple
1088 - In line mode you can time a single-line statement (though multiple
1088 ones can be chained with using semicolons).
1089 ones can be chained with using semicolons).
1089
1090
1090 - In cell mode, you can time the cell body (a directly
1091 - In cell mode, you can time the cell body (a directly
1091 following statement raises an error).
1092 following statement raises an error).
1092
1093
1093 This function provides very basic timing functionality. Use the timeit
1094 This function provides very basic timing functionality. Use the timeit
1094 magic for more control over the measurement.
1095 magic for more control over the measurement.
1095
1096
1096 Examples
1097 Examples
1097 --------
1098 --------
1098 ::
1099 ::
1099
1100
1100 In [1]: %time 2**128
1101 In [1]: %time 2**128
1101 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1102 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1102 Wall time: 0.00
1103 Wall time: 0.00
1103 Out[1]: 340282366920938463463374607431768211456L
1104 Out[1]: 340282366920938463463374607431768211456L
1104
1105
1105 In [2]: n = 1000000
1106 In [2]: n = 1000000
1106
1107
1107 In [3]: %time sum(range(n))
1108 In [3]: %time sum(range(n))
1108 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1109 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1109 Wall time: 1.37
1110 Wall time: 1.37
1110 Out[3]: 499999500000L
1111 Out[3]: 499999500000L
1111
1112
1112 In [4]: %time print 'hello world'
1113 In [4]: %time print 'hello world'
1113 hello world
1114 hello world
1114 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1115 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1115 Wall time: 0.00
1116 Wall time: 0.00
1116
1117
1117 Note that the time needed by Python to compile the given expression
1118 Note that the time needed by Python to compile the given expression
1118 will be reported if it is more than 0.1s. In this example, the
1119 will be reported if it is more than 0.1s. In this example, the
1119 actual exponentiation is done by Python at compilation time, so while
1120 actual exponentiation is done by Python at compilation time, so while
1120 the expression can take a noticeable amount of time to compute, that
1121 the expression can take a noticeable amount of time to compute, that
1121 time is purely due to the compilation:
1122 time is purely due to the compilation:
1122
1123
1123 In [5]: %time 3**9999;
1124 In [5]: %time 3**9999;
1124 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1125 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1125 Wall time: 0.00 s
1126 Wall time: 0.00 s
1126
1127
1127 In [6]: %time 3**999999;
1128 In [6]: %time 3**999999;
1128 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1129 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1129 Wall time: 0.00 s
1130 Wall time: 0.00 s
1130 Compiler : 0.78 s
1131 Compiler : 0.78 s
1131 """
1132 """
1132
1133
1133 # fail immediately if the given expression can't be compiled
1134 # fail immediately if the given expression can't be compiled
1134
1135
1135 if line and cell:
1136 if line and cell:
1136 raise UsageError("Can't use statement directly after '%%time'!")
1137 raise UsageError("Can't use statement directly after '%%time'!")
1137
1138
1138 if cell:
1139 if cell:
1139 expr = self.shell.input_transformer_manager.transform_cell(cell)
1140 expr = self.shell.input_transformer_manager.transform_cell(cell)
1140 else:
1141 else:
1141 expr = self.shell.input_transformer_manager.transform_cell(line)
1142 expr = self.shell.input_transformer_manager.transform_cell(line)
1142
1143
1143 # Minimum time above which parse time will be reported
1144 # Minimum time above which parse time will be reported
1144 tp_min = 0.1
1145 tp_min = 0.1
1145
1146
1146 t0 = clock()
1147 t0 = clock()
1147 expr_ast = self.shell.compile.ast_parse(expr)
1148 expr_ast = self.shell.compile.ast_parse(expr)
1148 tp = clock()-t0
1149 tp = clock()-t0
1149
1150
1150 # Apply AST transformations
1151 # Apply AST transformations
1151 expr_ast = self.shell.transform_ast(expr_ast)
1152 expr_ast = self.shell.transform_ast(expr_ast)
1152
1153
1153 # Minimum time above which compilation time will be reported
1154 # Minimum time above which compilation time will be reported
1154 tc_min = 0.1
1155 tc_min = 0.1
1155
1156
1156 if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
1157 if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
1157 mode = 'eval'
1158 mode = 'eval'
1158 source = '<timed eval>'
1159 source = '<timed eval>'
1159 expr_ast = ast.Expression(expr_ast.body[0].value)
1160 expr_ast = ast.Expression(expr_ast.body[0].value)
1160 else:
1161 else:
1161 mode = 'exec'
1162 mode = 'exec'
1162 source = '<timed exec>'
1163 source = '<timed exec>'
1163 t0 = clock()
1164 t0 = clock()
1164 code = self.shell.compile(expr_ast, source, mode)
1165 code = self.shell.compile(expr_ast, source, mode)
1165 tc = clock()-t0
1166 tc = clock()-t0
1166
1167
1167 # skew measurement as little as possible
1168 # skew measurement as little as possible
1168 glob = self.shell.user_ns
1169 glob = self.shell.user_ns
1169 wtime = time.time
1170 wtime = time.time
1170 # time execution
1171 # time execution
1171 wall_st = wtime()
1172 wall_st = wtime()
1172 if mode=='eval':
1173 if mode=='eval':
1173 st = clock2()
1174 st = clock2()
1174 out = eval(code, glob, local_ns)
1175 out = eval(code, glob, local_ns)
1175 end = clock2()
1176 end = clock2()
1176 else:
1177 else:
1177 st = clock2()
1178 st = clock2()
1178 exec(code, glob, local_ns)
1179 exec(code, glob, local_ns)
1179 end = clock2()
1180 end = clock2()
1180 out = None
1181 out = None
1181 wall_end = wtime()
1182 wall_end = wtime()
1182 # Compute actual times and report
1183 # Compute actual times and report
1183 wall_time = wall_end-wall_st
1184 wall_time = wall_end-wall_st
1184 cpu_user = end[0]-st[0]
1185 cpu_user = end[0]-st[0]
1185 cpu_sys = end[1]-st[1]
1186 cpu_sys = end[1]-st[1]
1186 cpu_tot = cpu_user+cpu_sys
1187 cpu_tot = cpu_user+cpu_sys
1187 # On windows cpu_sys is always zero, so no new information to the next print
1188 # On windows cpu_sys is always zero, so no new information to the next print
1188 if sys.platform != 'win32':
1189 if sys.platform != 'win32':
1189 print("CPU times: user %s, sys: %s, total: %s" % \
1190 print("CPU times: user %s, sys: %s, total: %s" % \
1190 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)))
1191 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)))
1191 print("Wall time: %s" % _format_time(wall_time))
1192 print("Wall time: %s" % _format_time(wall_time))
1192 if tc > tc_min:
1193 if tc > tc_min:
1193 print("Compiler : %s" % _format_time(tc))
1194 print("Compiler : %s" % _format_time(tc))
1194 if tp > tp_min:
1195 if tp > tp_min:
1195 print("Parser : %s" % _format_time(tp))
1196 print("Parser : %s" % _format_time(tp))
1196 return out
1197 return out
1197
1198
1198 @skip_doctest
1199 @skip_doctest
1199 @line_magic
1200 @line_magic
1200 def macro(self, parameter_s=''):
1201 def macro(self, parameter_s=''):
1201 """Define a macro for future re-execution. It accepts ranges of history,
1202 """Define a macro for future re-execution. It accepts ranges of history,
1202 filenames or string objects.
1203 filenames or string objects.
1203
1204
1204 Usage:\\
1205 Usage:\\
1205 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1206 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1206
1207
1207 Options:
1208 Options:
1208
1209
1209 -r: use 'raw' input. By default, the 'processed' history is used,
1210 -r: use 'raw' input. By default, the 'processed' history is used,
1210 so that magics are loaded in their transformed version to valid
1211 so that magics are loaded in their transformed version to valid
1211 Python. If this option is given, the raw input as typed at the
1212 Python. If this option is given, the raw input as typed at the
1212 command line is used instead.
1213 command line is used instead.
1213
1214
1214 -q: quiet macro definition. By default, a tag line is printed
1215 -q: quiet macro definition. By default, a tag line is printed
1215 to indicate the macro has been created, and then the contents of
1216 to indicate the macro has been created, and then the contents of
1216 the macro are printed. If this option is given, then no printout
1217 the macro are printed. If this option is given, then no printout
1217 is produced once the macro is created.
1218 is produced once the macro is created.
1218
1219
1219 This will define a global variable called `name` which is a string
1220 This will define a global variable called `name` which is a string
1220 made of joining the slices and lines you specify (n1,n2,... numbers
1221 made of joining the slices and lines you specify (n1,n2,... numbers
1221 above) from your input history into a single string. This variable
1222 above) from your input history into a single string. This variable
1222 acts like an automatic function which re-executes those lines as if
1223 acts like an automatic function which re-executes those lines as if
1223 you had typed them. You just type 'name' at the prompt and the code
1224 you had typed them. You just type 'name' at the prompt and the code
1224 executes.
1225 executes.
1225
1226
1226 The syntax for indicating input ranges is described in %history.
1227 The syntax for indicating input ranges is described in %history.
1227
1228
1228 Note: as a 'hidden' feature, you can also use traditional python slice
1229 Note: as a 'hidden' feature, you can also use traditional python slice
1229 notation, where N:M means numbers N through M-1.
1230 notation, where N:M means numbers N through M-1.
1230
1231
1231 For example, if your history contains (print using %hist -n )::
1232 For example, if your history contains (print using %hist -n )::
1232
1233
1233 44: x=1
1234 44: x=1
1234 45: y=3
1235 45: y=3
1235 46: z=x+y
1236 46: z=x+y
1236 47: print x
1237 47: print x
1237 48: a=5
1238 48: a=5
1238 49: print 'x',x,'y',y
1239 49: print 'x',x,'y',y
1239
1240
1240 you can create a macro with lines 44 through 47 (included) and line 49
1241 you can create a macro with lines 44 through 47 (included) and line 49
1241 called my_macro with::
1242 called my_macro with::
1242
1243
1243 In [55]: %macro my_macro 44-47 49
1244 In [55]: %macro my_macro 44-47 49
1244
1245
1245 Now, typing `my_macro` (without quotes) will re-execute all this code
1246 Now, typing `my_macro` (without quotes) will re-execute all this code
1246 in one pass.
1247 in one pass.
1247
1248
1248 You don't need to give the line-numbers in order, and any given line
1249 You don't need to give the line-numbers in order, and any given line
1249 number can appear multiple times. You can assemble macros with any
1250 number can appear multiple times. You can assemble macros with any
1250 lines from your input history in any order.
1251 lines from your input history in any order.
1251
1252
1252 The macro is a simple object which holds its value in an attribute,
1253 The macro is a simple object which holds its value in an attribute,
1253 but IPython's display system checks for macros and executes them as
1254 but IPython's display system checks for macros and executes them as
1254 code instead of printing them when you type their name.
1255 code instead of printing them when you type their name.
1255
1256
1256 You can view a macro's contents by explicitly printing it with::
1257 You can view a macro's contents by explicitly printing it with::
1257
1258
1258 print macro_name
1259 print macro_name
1259
1260
1260 """
1261 """
1261 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1262 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1262 if not args: # List existing macros
1263 if not args: # List existing macros
1263 return sorted(k for k,v in iteritems(self.shell.user_ns) if\
1264 return sorted(k for k,v in iteritems(self.shell.user_ns) if\
1264 isinstance(v, Macro))
1265 isinstance(v, Macro))
1265 if len(args) == 1:
1266 if len(args) == 1:
1266 raise UsageError(
1267 raise UsageError(
1267 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1268 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1268 name, codefrom = args[0], " ".join(args[1:])
1269 name, codefrom = args[0], " ".join(args[1:])
1269
1270
1270 #print 'rng',ranges # dbg
1271 #print 'rng',ranges # dbg
1271 try:
1272 try:
1272 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1273 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1273 except (ValueError, TypeError) as e:
1274 except (ValueError, TypeError) as e:
1274 print(e.args[0])
1275 print(e.args[0])
1275 return
1276 return
1276 macro = Macro(lines)
1277 macro = Macro(lines)
1277 self.shell.define_macro(name, macro)
1278 self.shell.define_macro(name, macro)
1278 if not ( 'q' in opts) :
1279 if not ( 'q' in opts) :
1279 print('Macro `%s` created. To execute, type its name (without quotes).' % name)
1280 print('Macro `%s` created. To execute, type its name (without quotes).' % name)
1280 print('=== Macro contents: ===')
1281 print('=== Macro contents: ===')
1281 print(macro, end=' ')
1282 print(macro, end=' ')
1282
1283
1283 @magic_arguments.magic_arguments()
1284 @magic_arguments.magic_arguments()
1284 @magic_arguments.argument('output', type=str, default='', nargs='?',
1285 @magic_arguments.argument('output', type=str, default='', nargs='?',
1285 help="""The name of the variable in which to store output.
1286 help="""The name of the variable in which to store output.
1286 This is a utils.io.CapturedIO object with stdout/err attributes
1287 This is a utils.io.CapturedIO object with stdout/err attributes
1287 for the text of the captured output.
1288 for the text of the captured output.
1288
1289
1289 CapturedOutput also has a show() method for displaying the output,
1290 CapturedOutput also has a show() method for displaying the output,
1290 and __call__ as well, so you can use that to quickly display the
1291 and __call__ as well, so you can use that to quickly display the
1291 output.
1292 output.
1292
1293
1293 If unspecified, captured output is discarded.
1294 If unspecified, captured output is discarded.
1294 """
1295 """
1295 )
1296 )
1296 @magic_arguments.argument('--no-stderr', action="store_true",
1297 @magic_arguments.argument('--no-stderr', action="store_true",
1297 help="""Don't capture stderr."""
1298 help="""Don't capture stderr."""
1298 )
1299 )
1299 @magic_arguments.argument('--no-stdout', action="store_true",
1300 @magic_arguments.argument('--no-stdout', action="store_true",
1300 help="""Don't capture stdout."""
1301 help="""Don't capture stdout."""
1301 )
1302 )
1302 @magic_arguments.argument('--no-display', action="store_true",
1303 @magic_arguments.argument('--no-display', action="store_true",
1303 help="""Don't capture IPython's rich display."""
1304 help="""Don't capture IPython's rich display."""
1304 )
1305 )
1305 @cell_magic
1306 @cell_magic
1306 def capture(self, line, cell):
1307 def capture(self, line, cell):
1307 """run the cell, capturing stdout, stderr, and IPython's rich display() calls."""
1308 """run the cell, capturing stdout, stderr, and IPython's rich display() calls."""
1308 args = magic_arguments.parse_argstring(self.capture, line)
1309 args = magic_arguments.parse_argstring(self.capture, line)
1309 out = not args.no_stdout
1310 out = not args.no_stdout
1310 err = not args.no_stderr
1311 err = not args.no_stderr
1311 disp = not args.no_display
1312 disp = not args.no_display
1312 with capture_output(out, err, disp) as io:
1313 with capture_output(out, err, disp) as io:
1313 self.shell.run_cell(cell)
1314 self.shell.run_cell(cell)
1314 if args.output:
1315 if args.output:
1315 self.shell.user_ns[args.output] = io
1316 self.shell.user_ns[args.output] = io
1316
1317
1317 def parse_breakpoint(text, current_file):
1318 def parse_breakpoint(text, current_file):
1318 '''Returns (file, line) for file:line and (current_file, line) for line'''
1319 '''Returns (file, line) for file:line and (current_file, line) for line'''
1319 colon = text.find(':')
1320 colon = text.find(':')
1320 if colon == -1:
1321 if colon == -1:
1321 return current_file, int(text)
1322 return current_file, int(text)
1322 else:
1323 else:
1323 return text[:colon], int(text[colon+1:])
1324 return text[:colon], int(text[colon+1:])
1324
1325
1325 def _format_time(timespan, precision=3):
1326 def _format_time(timespan, precision=3):
1326 """Formats the timespan in a human readable form"""
1327 """Formats the timespan in a human readable form"""
1327 import math
1328 import math
1328
1329
1329 if timespan >= 60.0:
1330 if timespan >= 60.0:
1330 # we have more than a minute, format that in a human readable form
1331 # we have more than a minute, format that in a human readable form
1331 # Idea from http://snipplr.com/view/5713/
1332 # Idea from http://snipplr.com/view/5713/
1332 parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
1333 parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
1333 time = []
1334 time = []
1334 leftover = timespan
1335 leftover = timespan
1335 for suffix, length in parts:
1336 for suffix, length in parts:
1336 value = int(leftover / length)
1337 value = int(leftover / length)
1337 if value > 0:
1338 if value > 0:
1338 leftover = leftover % length
1339 leftover = leftover % length
1339 time.append(u'%s%s' % (str(value), suffix))
1340 time.append(u'%s%s' % (str(value), suffix))
1340 if leftover < 1:
1341 if leftover < 1:
1341 break
1342 break
1342 return " ".join(time)
1343 return " ".join(time)
1343
1344
1344
1345
1345 # Unfortunately the unicode 'micro' symbol can cause problems in
1346 # Unfortunately the unicode 'micro' symbol can cause problems in
1346 # certain terminals.
1347 # certain terminals.
1347 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1348 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1348 # Try to prevent crashes by being more secure than it needs to
1349 # Try to prevent crashes by being more secure than it needs to
1349 # E.g. eclipse is able to print a µ, but has no sys.stdout.encoding set.
1350 # E.g. eclipse is able to print a µ, but has no sys.stdout.encoding set.
1350 units = [u"s", u"ms",u'us',"ns"] # the save value
1351 units = [u"s", u"ms",u'us',"ns"] # the save value
1351 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
1352 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
1352 try:
1353 try:
1353 u'\xb5'.encode(sys.stdout.encoding)
1354 u'\xb5'.encode(sys.stdout.encoding)
1354 units = [u"s", u"ms",u'\xb5s',"ns"]
1355 units = [u"s", u"ms",u'\xb5s',"ns"]
1355 except:
1356 except:
1356 pass
1357 pass
1357 scaling = [1, 1e3, 1e6, 1e9]
1358 scaling = [1, 1e3, 1e6, 1e9]
1358
1359
1359 if timespan > 0.0:
1360 if timespan > 0.0:
1360 order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
1361 order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
1361 else:
1362 else:
1362 order = 3
1363 order = 3
1363 return u"%.*g %s" % (precision, timespan * scaling[order], units[order])
1364 return u"%.*g %s" % (precision, timespan * scaling[order], units[order])
General Comments 0
You need to be logged in to leave comments. Login now