Show More
@@ -1,600 +1,596 | |||||
1 | """Implementation of basic magic functions.""" |
|
1 | """Implementation of basic magic functions.""" | |
2 |
|
2 | |||
3 |
|
3 | |||
4 | import argparse |
|
4 | import argparse | |
5 | import textwrap |
|
5 | import textwrap | |
6 | import io |
|
6 | import io | |
7 | import sys |
|
7 | import sys | |
8 | from pprint import pformat |
|
8 | from pprint import pformat | |
9 |
|
9 | |||
10 | from IPython.core import magic_arguments, page |
|
10 | from IPython.core import magic_arguments, page | |
11 | from IPython.core.error import UsageError |
|
11 | from IPython.core.error import UsageError | |
12 | 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 | |
13 | from IPython.utils.text import format_screen, dedent, indent |
|
13 | from IPython.utils.text import format_screen, dedent, indent | |
14 | from IPython.testing.skipdoctest import skip_doctest |
|
14 | from IPython.testing.skipdoctest import skip_doctest | |
15 | from IPython.utils.ipstruct import Struct |
|
15 | from IPython.utils.ipstruct import Struct | |
16 | from warnings import warn |
|
16 | from warnings import warn | |
17 | from logging import error |
|
17 | from logging import error | |
18 |
|
18 | |||
19 |
|
19 | |||
20 | class MagicsDisplay(object): |
|
20 | class MagicsDisplay(object): | |
21 | def __init__(self, magics_manager, ignore=None): |
|
21 | def __init__(self, magics_manager, ignore=None): | |
22 | self.ignore = ignore if ignore else [] |
|
22 | self.ignore = ignore if ignore else [] | |
23 | self.magics_manager = magics_manager |
|
23 | self.magics_manager = magics_manager | |
24 |
|
24 | |||
25 | def _lsmagic(self): |
|
25 | def _lsmagic(self): | |
26 | """The main implementation of the %lsmagic""" |
|
26 | """The main implementation of the %lsmagic""" | |
27 | mesc = magic_escapes['line'] |
|
27 | mesc = magic_escapes['line'] | |
28 | cesc = magic_escapes['cell'] |
|
28 | cesc = magic_escapes['cell'] | |
29 | mman = self.magics_manager |
|
29 | mman = self.magics_manager | |
30 | magics = mman.lsmagic() |
|
30 | magics = mman.lsmagic() | |
31 | out = ['Available line magics:', |
|
31 | out = ['Available line magics:', | |
32 | mesc + (' '+mesc).join(sorted([m for m,v in magics['line'].items() if (v not in self.ignore)])), |
|
32 | mesc + (' '+mesc).join(sorted([m for m,v in magics['line'].items() if (v not in self.ignore)])), | |
33 | '', |
|
33 | '', | |
34 | 'Available cell magics:', |
|
34 | 'Available cell magics:', | |
35 | cesc + (' '+cesc).join(sorted([m for m,v in magics['cell'].items() if (v not in self.ignore)])), |
|
35 | cesc + (' '+cesc).join(sorted([m for m,v in magics['cell'].items() if (v not in self.ignore)])), | |
36 | '', |
|
36 | '', | |
37 | mman.auto_status()] |
|
37 | mman.auto_status()] | |
38 | return '\n'.join(out) |
|
38 | return '\n'.join(out) | |
39 |
|
39 | |||
40 | def _repr_pretty_(self, p, cycle): |
|
40 | def _repr_pretty_(self, p, cycle): | |
41 | p.text(self._lsmagic()) |
|
41 | p.text(self._lsmagic()) | |
42 |
|
42 | |||
43 | def __str__(self): |
|
43 | def __str__(self): | |
44 | return self._lsmagic() |
|
44 | return self._lsmagic() | |
45 |
|
45 | |||
46 | def _jsonable(self): |
|
46 | def _jsonable(self): | |
47 | """turn magics dict into jsonable dict of the same structure |
|
47 | """turn magics dict into jsonable dict of the same structure | |
48 |
|
48 | |||
49 | replaces object instances with their class names as strings |
|
49 | replaces object instances with their class names as strings | |
50 | """ |
|
50 | """ | |
51 | magic_dict = {} |
|
51 | magic_dict = {} | |
52 | mman = self.magics_manager |
|
52 | mman = self.magics_manager | |
53 | magics = mman.lsmagic() |
|
53 | magics = mman.lsmagic() | |
54 | for key, subdict in magics.items(): |
|
54 | for key, subdict in magics.items(): | |
55 | d = {} |
|
55 | d = {} | |
56 | magic_dict[key] = d |
|
56 | magic_dict[key] = d | |
57 | for name, obj in subdict.items(): |
|
57 | for name, obj in subdict.items(): | |
58 | try: |
|
58 | try: | |
59 | classname = obj.__self__.__class__.__name__ |
|
59 | classname = obj.__self__.__class__.__name__ | |
60 | except AttributeError: |
|
60 | except AttributeError: | |
61 | classname = 'Other' |
|
61 | classname = 'Other' | |
62 |
|
62 | |||
63 | d[name] = classname |
|
63 | d[name] = classname | |
64 | return magic_dict |
|
64 | return magic_dict | |
65 |
|
65 | |||
66 | def _repr_json_(self): |
|
66 | def _repr_json_(self): | |
67 | return self._jsonable() |
|
67 | return self._jsonable() | |
68 |
|
68 | |||
69 |
|
69 | |||
70 | @magics_class |
|
70 | @magics_class | |
71 | class BasicMagics(Magics): |
|
71 | class BasicMagics(Magics): | |
72 | """Magics that provide central IPython functionality. |
|
72 | """Magics that provide central IPython functionality. | |
73 |
|
73 | |||
74 | These are various magics that don't fit into specific categories but that |
|
74 | These are various magics that don't fit into specific categories but that | |
75 | are all part of the base 'IPython experience'.""" |
|
75 | are all part of the base 'IPython experience'.""" | |
76 |
|
76 | |||
77 | @magic_arguments.magic_arguments() |
|
77 | @magic_arguments.magic_arguments() | |
78 | @magic_arguments.argument( |
|
78 | @magic_arguments.argument( | |
79 | '-l', '--line', action='store_true', |
|
79 | '-l', '--line', action='store_true', | |
80 | help="""Create a line magic alias.""" |
|
80 | help="""Create a line magic alias.""" | |
81 | ) |
|
81 | ) | |
82 | @magic_arguments.argument( |
|
82 | @magic_arguments.argument( | |
83 | '-c', '--cell', action='store_true', |
|
83 | '-c', '--cell', action='store_true', | |
84 | help="""Create a cell magic alias.""" |
|
84 | help="""Create a cell magic alias.""" | |
85 | ) |
|
85 | ) | |
86 | @magic_arguments.argument( |
|
86 | @magic_arguments.argument( | |
87 | 'name', |
|
87 | 'name', | |
88 | help="""Name of the magic to be created.""" |
|
88 | help="""Name of the magic to be created.""" | |
89 | ) |
|
89 | ) | |
90 | @magic_arguments.argument( |
|
90 | @magic_arguments.argument( | |
91 | 'target', |
|
91 | 'target', | |
92 | help="""Name of the existing line or cell magic.""" |
|
92 | help="""Name of the existing line or cell magic.""" | |
93 | ) |
|
93 | ) | |
94 | @line_magic |
|
94 | @line_magic | |
95 | def alias_magic(self, line=''): |
|
95 | def alias_magic(self, line=''): | |
96 | """Create an alias for an existing line or cell magic. |
|
96 | """Create an alias for an existing line or cell magic. | |
97 |
|
97 | |||
98 | Examples |
|
98 | Examples | |
99 | -------- |
|
99 | -------- | |
100 | :: |
|
100 | :: | |
101 |
|
101 | |||
102 | In [1]: %alias_magic t timeit |
|
102 | In [1]: %alias_magic t timeit | |
103 | Created `%t` as an alias for `%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 |
|
105 | |||
106 | In [2]: %t -n1 pass |
|
106 | In [2]: %t -n1 pass | |
107 | 1 loops, best of 3: 954 ns per loop |
|
107 | 1 loops, best of 3: 954 ns per loop | |
108 |
|
108 | |||
109 | In [3]: %%t -n1 |
|
109 | In [3]: %%t -n1 | |
110 | ...: pass |
|
110 | ...: pass | |
111 | ...: |
|
111 | ...: | |
112 | 1 loops, best of 3: 954 ns per loop |
|
112 | 1 loops, best of 3: 954 ns per loop | |
113 |
|
113 | |||
114 | In [4]: %alias_magic --cell whereami pwd |
|
114 | In [4]: %alias_magic --cell whereami pwd | |
115 | UsageError: Cell magic function `%%pwd` not found. |
|
115 | UsageError: Cell magic function `%%pwd` not found. | |
116 | In [5]: %alias_magic --line whereami pwd |
|
116 | In [5]: %alias_magic --line whereami pwd | |
117 | Created `%whereami` as an alias for `%pwd`. |
|
117 | Created `%whereami` as an alias for `%pwd`. | |
118 |
|
118 | |||
119 | In [6]: %whereami |
|
119 | In [6]: %whereami | |
120 | Out[6]: u'/home/testuser' |
|
120 | Out[6]: u'/home/testuser' | |
121 | """ |
|
121 | """ | |
122 | args = magic_arguments.parse_argstring(self.alias_magic, line) |
|
122 | args = magic_arguments.parse_argstring(self.alias_magic, line) | |
123 | shell = self.shell |
|
123 | shell = self.shell | |
124 | mman = self.shell.magics_manager |
|
124 | mman = self.shell.magics_manager | |
125 | escs = ''.join(magic_escapes.values()) |
|
125 | escs = ''.join(magic_escapes.values()) | |
126 |
|
126 | |||
127 | target = args.target.lstrip(escs) |
|
127 | target = args.target.lstrip(escs) | |
128 | name = args.name.lstrip(escs) |
|
128 | name = args.name.lstrip(escs) | |
129 |
|
129 | |||
130 | # Find the requested magics. |
|
130 | # Find the requested magics. | |
131 | m_line = shell.find_magic(target, 'line') |
|
131 | m_line = shell.find_magic(target, 'line') | |
132 | m_cell = shell.find_magic(target, 'cell') |
|
132 | m_cell = shell.find_magic(target, 'cell') | |
133 | if args.line and m_line is None: |
|
133 | if args.line and m_line is None: | |
134 | raise UsageError('Line magic function `%s%s` not found.' % |
|
134 | raise UsageError('Line magic function `%s%s` not found.' % | |
135 | (magic_escapes['line'], target)) |
|
135 | (magic_escapes['line'], target)) | |
136 | if args.cell and m_cell is None: |
|
136 | if args.cell and m_cell is None: | |
137 | raise UsageError('Cell magic function `%s%s` not found.' % |
|
137 | raise UsageError('Cell magic function `%s%s` not found.' % | |
138 | (magic_escapes['cell'], target)) |
|
138 | (magic_escapes['cell'], target)) | |
139 |
|
139 | |||
140 | # If --line and --cell are not specified, default to the ones |
|
140 | # If --line and --cell are not specified, default to the ones | |
141 | # that are available. |
|
141 | # that are available. | |
142 | if not args.line and not args.cell: |
|
142 | if not args.line and not args.cell: | |
143 | if not m_line and not m_cell: |
|
143 | if not m_line and not m_cell: | |
144 | raise UsageError( |
|
144 | raise UsageError( | |
145 | 'No line or cell magic with name `%s` found.' % target |
|
145 | 'No line or cell magic with name `%s` found.' % target | |
146 | ) |
|
146 | ) | |
147 | args.line = bool(m_line) |
|
147 | args.line = bool(m_line) | |
148 | args.cell = bool(m_cell) |
|
148 | args.cell = bool(m_cell) | |
149 |
|
149 | |||
150 | if args.line: |
|
150 | if args.line: | |
151 | mman.register_alias(name, target, 'line') |
|
151 | mman.register_alias(name, target, 'line') | |
152 | print('Created `%s%s` as an alias for `%s%s`.' % ( |
|
152 | print('Created `%s%s` as an alias for `%s%s`.' % ( | |
153 | magic_escapes['line'], name, |
|
153 | magic_escapes['line'], name, | |
154 | magic_escapes['line'], target)) |
|
154 | magic_escapes['line'], target)) | |
155 |
|
155 | |||
156 | if args.cell: |
|
156 | if args.cell: | |
157 | mman.register_alias(name, target, 'cell') |
|
157 | mman.register_alias(name, target, 'cell') | |
158 | print('Created `%s%s` as an alias for `%s%s`.' % ( |
|
158 | print('Created `%s%s` as an alias for `%s%s`.' % ( | |
159 | magic_escapes['cell'], name, |
|
159 | magic_escapes['cell'], name, | |
160 | magic_escapes['cell'], target)) |
|
160 | magic_escapes['cell'], target)) | |
161 |
|
161 | |||
162 | @line_magic |
|
162 | @line_magic | |
163 | def lsmagic(self, parameter_s=''): |
|
163 | def lsmagic(self, parameter_s=''): | |
164 | """List currently available magic functions.""" |
|
164 | """List currently available magic functions.""" | |
165 | return MagicsDisplay(self.shell.magics_manager, ignore=[self.pip]) |
|
165 | return MagicsDisplay(self.shell.magics_manager, ignore=[self.pip]) | |
166 |
|
166 | |||
167 | def _magic_docs(self, brief=False, rest=False): |
|
167 | def _magic_docs(self, brief=False, rest=False): | |
168 | """Return docstrings from magic functions.""" |
|
168 | """Return docstrings from magic functions.""" | |
169 | mman = self.shell.magics_manager |
|
169 | mman = self.shell.magics_manager | |
170 | docs = mman.lsmagic_docs(brief, missing='No documentation') |
|
170 | docs = mman.lsmagic_docs(brief, missing='No documentation') | |
171 |
|
171 | |||
172 | if rest: |
|
172 | if rest: | |
173 | format_string = '**%s%s**::\n\n%s\n\n' |
|
173 | format_string = '**%s%s**::\n\n%s\n\n' | |
174 | else: |
|
174 | else: | |
175 | format_string = '%s%s:\n%s\n' |
|
175 | format_string = '%s%s:\n%s\n' | |
176 |
|
176 | |||
177 | return ''.join( |
|
177 | return ''.join( | |
178 | [format_string % (magic_escapes['line'], fname, |
|
178 | [format_string % (magic_escapes['line'], fname, | |
179 | indent(dedent(fndoc))) |
|
179 | indent(dedent(fndoc))) | |
180 | for fname, fndoc in sorted(docs['line'].items())] |
|
180 | for fname, fndoc in sorted(docs['line'].items())] | |
181 | + |
|
181 | + | |
182 | [format_string % (magic_escapes['cell'], fname, |
|
182 | [format_string % (magic_escapes['cell'], fname, | |
183 | indent(dedent(fndoc))) |
|
183 | indent(dedent(fndoc))) | |
184 | for fname, fndoc in sorted(docs['cell'].items())] |
|
184 | for fname, fndoc in sorted(docs['cell'].items())] | |
185 | ) |
|
185 | ) | |
186 |
|
186 | |||
187 | @line_magic |
|
187 | @line_magic | |
188 | def magic(self, parameter_s=''): |
|
188 | def magic(self, parameter_s=''): | |
189 | """Print information about the magic function system. |
|
189 | """Print information about the magic function system. | |
190 |
|
190 | |||
191 | Supported formats: -latex, -brief, -rest |
|
191 | Supported formats: -latex, -brief, -rest | |
192 | """ |
|
192 | """ | |
193 |
|
193 | |||
194 | mode = '' |
|
194 | mode = '' | |
195 | try: |
|
195 | try: | |
196 | mode = parameter_s.split()[0][1:] |
|
196 | mode = parameter_s.split()[0][1:] | |
197 | except IndexError: |
|
197 | except IndexError: | |
198 | pass |
|
198 | pass | |
199 |
|
199 | |||
200 | brief = (mode == 'brief') |
|
200 | brief = (mode == 'brief') | |
201 | rest = (mode == 'rest') |
|
201 | rest = (mode == 'rest') | |
202 | magic_docs = self._magic_docs(brief, rest) |
|
202 | magic_docs = self._magic_docs(brief, rest) | |
203 |
|
203 | |||
204 | if mode == 'latex': |
|
204 | if mode == 'latex': | |
205 | print(self.format_latex(magic_docs)) |
|
205 | print(self.format_latex(magic_docs)) | |
206 | return |
|
206 | return | |
207 | else: |
|
207 | else: | |
208 | magic_docs = format_screen(magic_docs) |
|
208 | magic_docs = format_screen(magic_docs) | |
209 |
|
209 | |||
210 | out = [""" |
|
210 | out = [""" | |
211 | IPython's 'magic' functions |
|
211 | IPython's 'magic' functions | |
212 | =========================== |
|
212 | =========================== | |
213 |
|
213 | |||
214 | The magic function system provides a series of functions which allow you to |
|
214 | 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 |
|
215 | 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. |
|
216 | features. There are two kinds of magics, line-oriented and cell-oriented. | |
217 |
|
217 | |||
218 | Line magics are prefixed with the % character and work much like OS |
|
218 | 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 |
|
219 | 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 |
|
220 | arguments are passed without parentheses or quotes. For example, this will | |
221 | time the given statement:: |
|
221 | time the given statement:: | |
222 |
|
222 | |||
223 | %timeit range(1000) |
|
223 | %timeit range(1000) | |
224 |
|
224 | |||
225 | Cell magics are prefixed with a double %%, and they are functions that get as |
|
225 | 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 |
|
226 | 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 |
|
227 | 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. |
|
228 | call line and the body of the cell, consisting of the lines below the first. | |
229 | For example:: |
|
229 | For example:: | |
230 |
|
230 | |||
231 | %%timeit x = numpy.random.randn((100, 100)) |
|
231 | %%timeit x = numpy.random.randn((100, 100)) | |
232 | numpy.linalg.svd(x) |
|
232 | numpy.linalg.svd(x) | |
233 |
|
233 | |||
234 | will time the execution of the numpy svd routine, running the assignment of x |
|
234 | 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. |
|
235 | as part of the setup phase, which is not timed. | |
236 |
|
236 | |||
237 | In a line-oriented client (the terminal or Qt console IPython), starting a new |
|
237 | 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 |
|
238 | 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 |
|
239 | 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 |
|
240 | whole cell as one entity, but keep in mind that the %% escape can only be at | |
241 | the very start of the cell. |
|
241 | the very start of the cell. | |
242 |
|
242 | |||
243 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
243 | 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 |
|
244 | %automagic function), you don't need to type in the % explicitly for line | |
245 | magics; cell magics always require an explicit '%%' escape. By default, |
|
245 | magics; cell magics always require an explicit '%%' escape. By default, | |
246 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
246 | IPython ships with automagic on, so you should only rarely need the % escape. | |
247 |
|
247 | |||
248 | Example: typing '%cd mydir' (without the quotes) changes your working directory |
|
248 | Example: typing '%cd mydir' (without the quotes) changes your working directory | |
249 | to 'mydir', if it exists. |
|
249 | to 'mydir', if it exists. | |
250 |
|
250 | |||
251 | For a list of the available magic functions, use %lsmagic. For a description |
|
251 | For a list of the available magic functions, use %lsmagic. For a description | |
252 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
252 | of any of them, type %magic_name?, e.g. '%cd?'. | |
253 |
|
253 | |||
254 | Currently the magic system has the following functions:""", |
|
254 | Currently the magic system has the following functions:""", | |
255 | magic_docs, |
|
255 | magic_docs, | |
256 | "Summary of magic functions (from %slsmagic):" % magic_escapes['line'], |
|
256 | "Summary of magic functions (from %slsmagic):" % magic_escapes['line'], | |
257 | str(self.lsmagic()), |
|
257 | str(self.lsmagic()), | |
258 | ] |
|
258 | ] | |
259 | page.page('\n'.join(out)) |
|
259 | page.page('\n'.join(out)) | |
260 |
|
260 | |||
261 |
|
261 | |||
262 | @line_magic |
|
262 | @line_magic | |
263 | def page(self, parameter_s=''): |
|
263 | def page(self, parameter_s=''): | |
264 | """Pretty print the object and display it through a pager. |
|
264 | """Pretty print the object and display it through a pager. | |
265 |
|
265 | |||
266 | %page [options] OBJECT |
|
266 | %page [options] OBJECT | |
267 |
|
267 | |||
268 | If no object is given, use _ (last output). |
|
268 | If no object is given, use _ (last output). | |
269 |
|
269 | |||
270 | Options: |
|
270 | Options: | |
271 |
|
271 | |||
272 | -r: page str(object), don't pretty-print it.""" |
|
272 | -r: page str(object), don't pretty-print it.""" | |
273 |
|
273 | |||
274 | # After a function contributed by Olivier Aubert, slightly modified. |
|
274 | # After a function contributed by Olivier Aubert, slightly modified. | |
275 |
|
275 | |||
276 | # Process options/args |
|
276 | # Process options/args | |
277 | opts, args = self.parse_options(parameter_s, 'r') |
|
277 | opts, args = self.parse_options(parameter_s, 'r') | |
278 | raw = 'r' in opts |
|
278 | raw = 'r' in opts | |
279 |
|
279 | |||
280 | oname = args and args or '_' |
|
280 | oname = args and args or '_' | |
281 | info = self.shell._ofind(oname) |
|
281 | info = self.shell._ofind(oname) | |
282 | if info['found']: |
|
282 | if info['found']: | |
283 | txt = (raw and str or pformat)( info['obj'] ) |
|
283 | txt = (raw and str or pformat)( info['obj'] ) | |
284 | page.page(txt) |
|
284 | page.page(txt) | |
285 | else: |
|
285 | else: | |
286 | print('Object `%s` not found' % oname) |
|
286 | print('Object `%s` not found' % oname) | |
287 |
|
287 | |||
288 | @line_magic |
|
288 | @line_magic | |
289 | def profile(self, parameter_s=''): |
|
289 | def profile(self, parameter_s=''): | |
290 | """Print your currently active IPython profile. |
|
290 | """Print your currently active IPython profile. | |
291 |
|
291 | |||
292 | See Also |
|
292 | See Also | |
293 | -------- |
|
293 | -------- | |
294 | prun : run code using the Python profiler |
|
294 | prun : run code using the Python profiler | |
295 | (:meth:`~IPython.core.magics.execution.ExecutionMagics.prun`) |
|
295 | (:meth:`~IPython.core.magics.execution.ExecutionMagics.prun`) | |
296 | """ |
|
296 | """ | |
297 |
|
|
297 | raise UsageError("The `%profile` magic has been deprecated since IPython 2.0. " | |
298 |
|
|
298 | "and removed in IPython 6.0. Please use the value of `get_ipython().profile` instead " | |
299 | from IPython.core.application import BaseIPythonApplication |
|
299 | "to see current profile in use. Perhaps you meant to use `%prun` to profile code?") | |
300 | if BaseIPythonApplication.initialized(): |
|
|||
301 | print(BaseIPythonApplication.instance().profile) |
|
|||
302 | else: |
|
|||
303 | error("profile is an application-level value, but you don't appear to be in an IPython application") |
|
|||
304 |
|
300 | |||
305 | @line_magic |
|
301 | @line_magic | |
306 | def pprint(self, parameter_s=''): |
|
302 | def pprint(self, parameter_s=''): | |
307 | """Toggle pretty printing on/off.""" |
|
303 | """Toggle pretty printing on/off.""" | |
308 | ptformatter = self.shell.display_formatter.formatters['text/plain'] |
|
304 | ptformatter = self.shell.display_formatter.formatters['text/plain'] | |
309 | ptformatter.pprint = bool(1 - ptformatter.pprint) |
|
305 | ptformatter.pprint = bool(1 - ptformatter.pprint) | |
310 | print('Pretty printing has been turned', |
|
306 | print('Pretty printing has been turned', | |
311 | ['OFF','ON'][ptformatter.pprint]) |
|
307 | ['OFF','ON'][ptformatter.pprint]) | |
312 |
|
308 | |||
313 | @line_magic |
|
309 | @line_magic | |
314 | def colors(self, parameter_s=''): |
|
310 | def colors(self, parameter_s=''): | |
315 | """Switch color scheme for prompts, info system and exception handlers. |
|
311 | """Switch color scheme for prompts, info system and exception handlers. | |
316 |
|
312 | |||
317 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
313 | Currently implemented schemes: NoColor, Linux, LightBG. | |
318 |
|
314 | |||
319 | Color scheme names are not case-sensitive. |
|
315 | Color scheme names are not case-sensitive. | |
320 |
|
316 | |||
321 | Examples |
|
317 | Examples | |
322 | -------- |
|
318 | -------- | |
323 | To get a plain black and white terminal:: |
|
319 | To get a plain black and white terminal:: | |
324 |
|
320 | |||
325 | %colors nocolor |
|
321 | %colors nocolor | |
326 | """ |
|
322 | """ | |
327 | def color_switch_err(name): |
|
323 | def color_switch_err(name): | |
328 | warn('Error changing %s color schemes.\n%s' % |
|
324 | warn('Error changing %s color schemes.\n%s' % | |
329 | (name, sys.exc_info()[1]), stacklevel=2) |
|
325 | (name, sys.exc_info()[1]), stacklevel=2) | |
330 |
|
326 | |||
331 |
|
327 | |||
332 | new_scheme = parameter_s.strip() |
|
328 | new_scheme = parameter_s.strip() | |
333 | if not new_scheme: |
|
329 | if not new_scheme: | |
334 | raise UsageError( |
|
330 | raise UsageError( | |
335 | "%colors: you must specify a color scheme. See '%colors?'") |
|
331 | "%colors: you must specify a color scheme. See '%colors?'") | |
336 | # local shortcut |
|
332 | # local shortcut | |
337 | shell = self.shell |
|
333 | shell = self.shell | |
338 |
|
334 | |||
339 | # Set shell colour scheme |
|
335 | # Set shell colour scheme | |
340 | try: |
|
336 | try: | |
341 | shell.colors = new_scheme |
|
337 | shell.colors = new_scheme | |
342 | shell.refresh_style() |
|
338 | shell.refresh_style() | |
343 | except: |
|
339 | except: | |
344 | color_switch_err('shell') |
|
340 | color_switch_err('shell') | |
345 |
|
341 | |||
346 | # Set exception colors |
|
342 | # Set exception colors | |
347 | try: |
|
343 | try: | |
348 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
344 | shell.InteractiveTB.set_colors(scheme = new_scheme) | |
349 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
345 | shell.SyntaxTB.set_colors(scheme = new_scheme) | |
350 | except: |
|
346 | except: | |
351 | color_switch_err('exception') |
|
347 | color_switch_err('exception') | |
352 |
|
348 | |||
353 | # Set info (for 'object?') colors |
|
349 | # Set info (for 'object?') colors | |
354 | if shell.color_info: |
|
350 | if shell.color_info: | |
355 | try: |
|
351 | try: | |
356 | shell.inspector.set_active_scheme(new_scheme) |
|
352 | shell.inspector.set_active_scheme(new_scheme) | |
357 | except: |
|
353 | except: | |
358 | color_switch_err('object inspector') |
|
354 | color_switch_err('object inspector') | |
359 | else: |
|
355 | else: | |
360 | shell.inspector.set_active_scheme('NoColor') |
|
356 | shell.inspector.set_active_scheme('NoColor') | |
361 |
|
357 | |||
362 | @line_magic |
|
358 | @line_magic | |
363 | def xmode(self, parameter_s=''): |
|
359 | def xmode(self, parameter_s=''): | |
364 | """Switch modes for the exception handlers. |
|
360 | """Switch modes for the exception handlers. | |
365 |
|
361 | |||
366 | Valid modes: Plain, Context and Verbose. |
|
362 | Valid modes: Plain, Context and Verbose. | |
367 |
|
363 | |||
368 | If called without arguments, acts as a toggle.""" |
|
364 | If called without arguments, acts as a toggle.""" | |
369 |
|
365 | |||
370 | def xmode_switch_err(name): |
|
366 | def xmode_switch_err(name): | |
371 | warn('Error changing %s exception modes.\n%s' % |
|
367 | warn('Error changing %s exception modes.\n%s' % | |
372 | (name,sys.exc_info()[1])) |
|
368 | (name,sys.exc_info()[1])) | |
373 |
|
369 | |||
374 | shell = self.shell |
|
370 | shell = self.shell | |
375 | new_mode = parameter_s.strip().capitalize() |
|
371 | new_mode = parameter_s.strip().capitalize() | |
376 | try: |
|
372 | try: | |
377 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
373 | shell.InteractiveTB.set_mode(mode=new_mode) | |
378 | print('Exception reporting mode:',shell.InteractiveTB.mode) |
|
374 | print('Exception reporting mode:',shell.InteractiveTB.mode) | |
379 | except: |
|
375 | except: | |
380 | xmode_switch_err('user') |
|
376 | xmode_switch_err('user') | |
381 |
|
377 | |||
382 | @line_magic |
|
378 | @line_magic | |
383 | def pip(self, args=''): |
|
379 | def pip(self, args=''): | |
384 | """ |
|
380 | """ | |
385 | Intercept usage of ``pip`` in IPython and direct user to run command outside of IPython. |
|
381 | Intercept usage of ``pip`` in IPython and direct user to run command outside of IPython. | |
386 | """ |
|
382 | """ | |
387 | print(textwrap.dedent(''' |
|
383 | print(textwrap.dedent(''' | |
388 | The following command must be run outside of the IPython shell: |
|
384 | The following command must be run outside of the IPython shell: | |
389 |
|
385 | |||
390 | $ pip {args} |
|
386 | $ pip {args} | |
391 |
|
387 | |||
392 | The Python package manager (pip) can only be used from outside of IPython. |
|
388 | The Python package manager (pip) can only be used from outside of IPython. | |
393 | Please reissue the `pip` command in a separate terminal or command prompt. |
|
389 | Please reissue the `pip` command in a separate terminal or command prompt. | |
394 |
|
390 | |||
395 | See the Python documentation for more informations on how to install packages: |
|
391 | See the Python documentation for more informations on how to install packages: | |
396 |
|
392 | |||
397 | https://docs.python.org/3/installing/'''.format(args=args))) |
|
393 | https://docs.python.org/3/installing/'''.format(args=args))) | |
398 |
|
394 | |||
399 | @line_magic |
|
395 | @line_magic | |
400 | def quickref(self, arg): |
|
396 | def quickref(self, arg): | |
401 | """ Show a quick reference sheet """ |
|
397 | """ Show a quick reference sheet """ | |
402 | from IPython.core.usage import quick_reference |
|
398 | from IPython.core.usage import quick_reference | |
403 | qr = quick_reference + self._magic_docs(brief=True) |
|
399 | qr = quick_reference + self._magic_docs(brief=True) | |
404 | page.page(qr) |
|
400 | page.page(qr) | |
405 |
|
401 | |||
406 | @line_magic |
|
402 | @line_magic | |
407 | def doctest_mode(self, parameter_s=''): |
|
403 | def doctest_mode(self, parameter_s=''): | |
408 | """Toggle doctest mode on and off. |
|
404 | """Toggle doctest mode on and off. | |
409 |
|
405 | |||
410 | This mode is intended to make IPython behave as much as possible like a |
|
406 | This mode is intended to make IPython behave as much as possible like a | |
411 | plain Python shell, from the perspective of how its prompts, exceptions |
|
407 | plain Python shell, from the perspective of how its prompts, exceptions | |
412 | and output look. This makes it easy to copy and paste parts of a |
|
408 | and output look. This makes it easy to copy and paste parts of a | |
413 | session into doctests. It does so by: |
|
409 | session into doctests. It does so by: | |
414 |
|
410 | |||
415 | - Changing the prompts to the classic ``>>>`` ones. |
|
411 | - Changing the prompts to the classic ``>>>`` ones. | |
416 | - Changing the exception reporting mode to 'Plain'. |
|
412 | - Changing the exception reporting mode to 'Plain'. | |
417 | - Disabling pretty-printing of output. |
|
413 | - Disabling pretty-printing of output. | |
418 |
|
414 | |||
419 | Note that IPython also supports the pasting of code snippets that have |
|
415 | Note that IPython also supports the pasting of code snippets that have | |
420 | leading '>>>' and '...' prompts in them. This means that you can paste |
|
416 | leading '>>>' and '...' prompts in them. This means that you can paste | |
421 | doctests from files or docstrings (even if they have leading |
|
417 | doctests from files or docstrings (even if they have leading | |
422 | whitespace), and the code will execute correctly. You can then use |
|
418 | whitespace), and the code will execute correctly. You can then use | |
423 | '%history -t' to see the translated history; this will give you the |
|
419 | '%history -t' to see the translated history; this will give you the | |
424 | input after removal of all the leading prompts and whitespace, which |
|
420 | input after removal of all the leading prompts and whitespace, which | |
425 | can be pasted back into an editor. |
|
421 | can be pasted back into an editor. | |
426 |
|
422 | |||
427 | With these features, you can switch into this mode easily whenever you |
|
423 | With these features, you can switch into this mode easily whenever you | |
428 | need to do testing and changes to doctests, without having to leave |
|
424 | need to do testing and changes to doctests, without having to leave | |
429 | your existing IPython session. |
|
425 | your existing IPython session. | |
430 | """ |
|
426 | """ | |
431 |
|
427 | |||
432 | # Shorthands |
|
428 | # Shorthands | |
433 | shell = self.shell |
|
429 | shell = self.shell | |
434 | meta = shell.meta |
|
430 | meta = shell.meta | |
435 | disp_formatter = self.shell.display_formatter |
|
431 | disp_formatter = self.shell.display_formatter | |
436 | ptformatter = disp_formatter.formatters['text/plain'] |
|
432 | ptformatter = disp_formatter.formatters['text/plain'] | |
437 | # dstore is a data store kept in the instance metadata bag to track any |
|
433 | # dstore is a data store kept in the instance metadata bag to track any | |
438 | # changes we make, so we can undo them later. |
|
434 | # changes we make, so we can undo them later. | |
439 | dstore = meta.setdefault('doctest_mode',Struct()) |
|
435 | dstore = meta.setdefault('doctest_mode',Struct()) | |
440 | save_dstore = dstore.setdefault |
|
436 | save_dstore = dstore.setdefault | |
441 |
|
437 | |||
442 | # save a few values we'll need to recover later |
|
438 | # save a few values we'll need to recover later | |
443 | mode = save_dstore('mode',False) |
|
439 | mode = save_dstore('mode',False) | |
444 | save_dstore('rc_pprint',ptformatter.pprint) |
|
440 | save_dstore('rc_pprint',ptformatter.pprint) | |
445 | save_dstore('xmode',shell.InteractiveTB.mode) |
|
441 | save_dstore('xmode',shell.InteractiveTB.mode) | |
446 | save_dstore('rc_separate_out',shell.separate_out) |
|
442 | save_dstore('rc_separate_out',shell.separate_out) | |
447 | save_dstore('rc_separate_out2',shell.separate_out2) |
|
443 | save_dstore('rc_separate_out2',shell.separate_out2) | |
448 | save_dstore('rc_separate_in',shell.separate_in) |
|
444 | save_dstore('rc_separate_in',shell.separate_in) | |
449 | save_dstore('rc_active_types',disp_formatter.active_types) |
|
445 | save_dstore('rc_active_types',disp_formatter.active_types) | |
450 |
|
446 | |||
451 | if not mode: |
|
447 | if not mode: | |
452 | # turn on |
|
448 | # turn on | |
453 |
|
449 | |||
454 | # Prompt separators like plain python |
|
450 | # Prompt separators like plain python | |
455 | shell.separate_in = '' |
|
451 | shell.separate_in = '' | |
456 | shell.separate_out = '' |
|
452 | shell.separate_out = '' | |
457 | shell.separate_out2 = '' |
|
453 | shell.separate_out2 = '' | |
458 |
|
454 | |||
459 |
|
455 | |||
460 | ptformatter.pprint = False |
|
456 | ptformatter.pprint = False | |
461 | disp_formatter.active_types = ['text/plain'] |
|
457 | disp_formatter.active_types = ['text/plain'] | |
462 |
|
458 | |||
463 | shell.magic('xmode Plain') |
|
459 | shell.magic('xmode Plain') | |
464 | else: |
|
460 | else: | |
465 | # turn off |
|
461 | # turn off | |
466 | shell.separate_in = dstore.rc_separate_in |
|
462 | shell.separate_in = dstore.rc_separate_in | |
467 |
|
463 | |||
468 | shell.separate_out = dstore.rc_separate_out |
|
464 | shell.separate_out = dstore.rc_separate_out | |
469 | shell.separate_out2 = dstore.rc_separate_out2 |
|
465 | shell.separate_out2 = dstore.rc_separate_out2 | |
470 |
|
466 | |||
471 | ptformatter.pprint = dstore.rc_pprint |
|
467 | ptformatter.pprint = dstore.rc_pprint | |
472 | disp_formatter.active_types = dstore.rc_active_types |
|
468 | disp_formatter.active_types = dstore.rc_active_types | |
473 |
|
469 | |||
474 | shell.magic('xmode ' + dstore.xmode) |
|
470 | shell.magic('xmode ' + dstore.xmode) | |
475 |
|
471 | |||
476 | # mode here is the state before we switch; switch_doctest_mode takes |
|
472 | # mode here is the state before we switch; switch_doctest_mode takes | |
477 | # the mode we're switching to. |
|
473 | # the mode we're switching to. | |
478 | shell.switch_doctest_mode(not mode) |
|
474 | shell.switch_doctest_mode(not mode) | |
479 |
|
475 | |||
480 | # Store new mode and inform |
|
476 | # Store new mode and inform | |
481 | dstore.mode = bool(not mode) |
|
477 | dstore.mode = bool(not mode) | |
482 | mode_label = ['OFF','ON'][dstore.mode] |
|
478 | mode_label = ['OFF','ON'][dstore.mode] | |
483 | print('Doctest mode is:', mode_label) |
|
479 | print('Doctest mode is:', mode_label) | |
484 |
|
480 | |||
485 | @line_magic |
|
481 | @line_magic | |
486 | def gui(self, parameter_s=''): |
|
482 | def gui(self, parameter_s=''): | |
487 | """Enable or disable IPython GUI event loop integration. |
|
483 | """Enable or disable IPython GUI event loop integration. | |
488 |
|
484 | |||
489 | %gui [GUINAME] |
|
485 | %gui [GUINAME] | |
490 |
|
486 | |||
491 | This magic replaces IPython's threaded shells that were activated |
|
487 | This magic replaces IPython's threaded shells that were activated | |
492 | using the (pylab/wthread/etc.) command line flags. GUI toolkits |
|
488 | using the (pylab/wthread/etc.) command line flags. GUI toolkits | |
493 | can now be enabled at runtime and keyboard |
|
489 | can now be enabled at runtime and keyboard | |
494 | interrupts should work without any problems. The following toolkits |
|
490 | interrupts should work without any problems. The following toolkits | |
495 | are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX):: |
|
491 | are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX):: | |
496 |
|
492 | |||
497 | %gui wx # enable wxPython event loop integration |
|
493 | %gui wx # enable wxPython event loop integration | |
498 | %gui qt4|qt # enable PyQt4 event loop integration |
|
494 | %gui qt4|qt # enable PyQt4 event loop integration | |
499 | %gui qt5 # enable PyQt5 event loop integration |
|
495 | %gui qt5 # enable PyQt5 event loop integration | |
500 | %gui gtk # enable PyGTK event loop integration |
|
496 | %gui gtk # enable PyGTK event loop integration | |
501 | %gui gtk3 # enable Gtk3 event loop integration |
|
497 | %gui gtk3 # enable Gtk3 event loop integration | |
502 | %gui tk # enable Tk event loop integration |
|
498 | %gui tk # enable Tk event loop integration | |
503 | %gui osx # enable Cocoa event loop integration |
|
499 | %gui osx # enable Cocoa event loop integration | |
504 | # (requires %matplotlib 1.1) |
|
500 | # (requires %matplotlib 1.1) | |
505 | %gui # disable all event loop integration |
|
501 | %gui # disable all event loop integration | |
506 |
|
502 | |||
507 | WARNING: after any of these has been called you can simply create |
|
503 | WARNING: after any of these has been called you can simply create | |
508 | an application object, but DO NOT start the event loop yourself, as |
|
504 | an application object, but DO NOT start the event loop yourself, as | |
509 | we have already handled that. |
|
505 | we have already handled that. | |
510 | """ |
|
506 | """ | |
511 | opts, arg = self.parse_options(parameter_s, '') |
|
507 | opts, arg = self.parse_options(parameter_s, '') | |
512 | if arg=='': arg = None |
|
508 | if arg=='': arg = None | |
513 | try: |
|
509 | try: | |
514 | return self.shell.enable_gui(arg) |
|
510 | return self.shell.enable_gui(arg) | |
515 | except Exception as e: |
|
511 | except Exception as e: | |
516 | # print simple error message, rather than traceback if we can't |
|
512 | # print simple error message, rather than traceback if we can't | |
517 | # hook up the GUI |
|
513 | # hook up the GUI | |
518 | error(str(e)) |
|
514 | error(str(e)) | |
519 |
|
515 | |||
520 | @skip_doctest |
|
516 | @skip_doctest | |
521 | @line_magic |
|
517 | @line_magic | |
522 | def precision(self, s=''): |
|
518 | def precision(self, s=''): | |
523 | """Set floating point precision for pretty printing. |
|
519 | """Set floating point precision for pretty printing. | |
524 |
|
520 | |||
525 | Can set either integer precision or a format string. |
|
521 | Can set either integer precision or a format string. | |
526 |
|
522 | |||
527 | If numpy has been imported and precision is an int, |
|
523 | If numpy has been imported and precision is an int, | |
528 | numpy display precision will also be set, via ``numpy.set_printoptions``. |
|
524 | numpy display precision will also be set, via ``numpy.set_printoptions``. | |
529 |
|
525 | |||
530 | If no argument is given, defaults will be restored. |
|
526 | If no argument is given, defaults will be restored. | |
531 |
|
527 | |||
532 | Examples |
|
528 | Examples | |
533 | -------- |
|
529 | -------- | |
534 | :: |
|
530 | :: | |
535 |
|
531 | |||
536 | In [1]: from math import pi |
|
532 | In [1]: from math import pi | |
537 |
|
533 | |||
538 | In [2]: %precision 3 |
|
534 | In [2]: %precision 3 | |
539 | Out[2]: u'%.3f' |
|
535 | Out[2]: u'%.3f' | |
540 |
|
536 | |||
541 | In [3]: pi |
|
537 | In [3]: pi | |
542 | Out[3]: 3.142 |
|
538 | Out[3]: 3.142 | |
543 |
|
539 | |||
544 | In [4]: %precision %i |
|
540 | In [4]: %precision %i | |
545 | Out[4]: u'%i' |
|
541 | Out[4]: u'%i' | |
546 |
|
542 | |||
547 | In [5]: pi |
|
543 | In [5]: pi | |
548 | Out[5]: 3 |
|
544 | Out[5]: 3 | |
549 |
|
545 | |||
550 | In [6]: %precision %e |
|
546 | In [6]: %precision %e | |
551 | Out[6]: u'%e' |
|
547 | Out[6]: u'%e' | |
552 |
|
548 | |||
553 | In [7]: pi**10 |
|
549 | In [7]: pi**10 | |
554 | Out[7]: 9.364805e+04 |
|
550 | Out[7]: 9.364805e+04 | |
555 |
|
551 | |||
556 | In [8]: %precision |
|
552 | In [8]: %precision | |
557 | Out[8]: u'%r' |
|
553 | Out[8]: u'%r' | |
558 |
|
554 | |||
559 | In [9]: pi**10 |
|
555 | In [9]: pi**10 | |
560 | Out[9]: 93648.047476082982 |
|
556 | Out[9]: 93648.047476082982 | |
561 | """ |
|
557 | """ | |
562 | ptformatter = self.shell.display_formatter.formatters['text/plain'] |
|
558 | ptformatter = self.shell.display_formatter.formatters['text/plain'] | |
563 | ptformatter.float_precision = s |
|
559 | ptformatter.float_precision = s | |
564 | return ptformatter.float_format |
|
560 | return ptformatter.float_format | |
565 |
|
561 | |||
566 | @magic_arguments.magic_arguments() |
|
562 | @magic_arguments.magic_arguments() | |
567 | @magic_arguments.argument( |
|
563 | @magic_arguments.argument( | |
568 | '-e', '--export', action='store_true', default=False, |
|
564 | '-e', '--export', action='store_true', default=False, | |
569 | help=argparse.SUPPRESS |
|
565 | help=argparse.SUPPRESS | |
570 | ) |
|
566 | ) | |
571 | @magic_arguments.argument( |
|
567 | @magic_arguments.argument( | |
572 | 'filename', type=str, |
|
568 | 'filename', type=str, | |
573 | help='Notebook name or filename' |
|
569 | help='Notebook name or filename' | |
574 | ) |
|
570 | ) | |
575 | @line_magic |
|
571 | @line_magic | |
576 | def notebook(self, s): |
|
572 | def notebook(self, s): | |
577 | """Export and convert IPython notebooks. |
|
573 | """Export and convert IPython notebooks. | |
578 |
|
574 | |||
579 | This function can export the current IPython history to a notebook file. |
|
575 | This function can export the current IPython history to a notebook file. | |
580 | For example, to export the history to "foo.ipynb" do "%notebook foo.ipynb". |
|
576 | For example, to export the history to "foo.ipynb" do "%notebook foo.ipynb". | |
581 |
|
577 | |||
582 | The -e or --export flag is deprecated in IPython 5.2, and will be |
|
578 | The -e or --export flag is deprecated in IPython 5.2, and will be | |
583 | removed in the future. |
|
579 | removed in the future. | |
584 | """ |
|
580 | """ | |
585 | args = magic_arguments.parse_argstring(self.notebook, s) |
|
581 | args = magic_arguments.parse_argstring(self.notebook, s) | |
586 |
|
582 | |||
587 | from nbformat import write, v4 |
|
583 | from nbformat import write, v4 | |
588 |
|
584 | |||
589 | cells = [] |
|
585 | cells = [] | |
590 | hist = list(self.shell.history_manager.get_range()) |
|
586 | hist = list(self.shell.history_manager.get_range()) | |
591 | if(len(hist)<=1): |
|
587 | if(len(hist)<=1): | |
592 | raise ValueError('History is empty, cannot export') |
|
588 | raise ValueError('History is empty, cannot export') | |
593 | for session, execution_count, source in hist[:-1]: |
|
589 | for session, execution_count, source in hist[:-1]: | |
594 | cells.append(v4.new_code_cell( |
|
590 | cells.append(v4.new_code_cell( | |
595 | execution_count=execution_count, |
|
591 | execution_count=execution_count, | |
596 | source=source |
|
592 | source=source | |
597 | )) |
|
593 | )) | |
598 | nb = v4.new_notebook(cells=cells) |
|
594 | nb = v4.new_notebook(cells=cells) | |
599 | with io.open(args.filename, 'w', encoding='utf-8') as f: |
|
595 | with io.open(args.filename, 'w', encoding='utf-8') as f: | |
600 | write(nb, f, version=4) |
|
596 | write(nb, f, version=4) |
@@ -1,176 +1,181 | |||||
1 | ===================== |
|
1 | ===================== | |
2 | Development version |
|
2 | Development version | |
3 | ===================== |
|
3 | ===================== | |
4 |
|
4 | |||
5 | This document describes in-flight development work. |
|
5 | This document describes in-flight development work. | |
6 |
|
6 | |||
7 | .. warning:: |
|
7 | .. warning:: | |
8 |
|
8 | |||
9 | Please do not edit this file by hand (doing so will likely cause merge |
|
9 | Please do not edit this file by hand (doing so will likely cause merge | |
10 | conflicts for other Pull Requests). Instead, create a new file in the |
|
10 | conflicts for other Pull Requests). Instead, create a new file in the | |
11 | `docs/source/whatsnew/pr` folder |
|
11 | `docs/source/whatsnew/pr` folder | |
12 |
|
12 | |||
13 | IPython 6.0 |
|
13 | IPython 6.0 | |
14 | =========== |
|
14 | =========== | |
15 |
|
15 | |||
16 | Released .... ...., 2017 |
|
16 | Released .... ...., 2017 | |
17 |
|
17 | |||
18 | IPython 6 feature a major improvement in the completion machinery which is now |
|
18 | IPython 6 feature a major improvement in the completion machinery which is now | |
19 | capable of completing non-executed code. It is also the first version of IPython |
|
19 | capable of completing non-executed code. It is also the first version of IPython | |
20 | to stop compatibility with Python 2, which is still supported on the bugfix only |
|
20 | to stop compatibility with Python 2, which is still supported on the bugfix only | |
21 | 5.x branch. Read below to have a non-exhaustive list of new features. |
|
21 | 5.x branch. Read below to have a non-exhaustive list of new features. | |
22 |
|
22 | |||
23 | Make sure you have pip > 9.0 before upgrading. |
|
23 | Make sure you have pip > 9.0 before upgrading. | |
24 | You should be able to update by using: |
|
24 | You should be able to update by using: | |
25 |
|
25 | |||
26 | .. code:: |
|
26 | .. code:: | |
27 |
|
27 | |||
28 | pip install ipython --upgrade |
|
28 | pip install ipython --upgrade | |
29 |
|
29 | |||
30 | New completion API and Interface |
|
30 | New completion API and Interface | |
31 | -------------------------------- |
|
31 | -------------------------------- | |
32 |
|
32 | |||
33 | The completer Completion API has seen an overhaul, and the new completer have |
|
33 | The completer Completion API has seen an overhaul, and the new completer have | |
34 | plenty of improvement both from the end users of terminal IPython or for |
|
34 | plenty of improvement both from the end users of terminal IPython or for | |
35 | consumers of the API. |
|
35 | consumers of the API. | |
36 |
|
36 | |||
37 | This new API is capable of pulling completions from :any:`jedi`, thus allowing |
|
37 | This new API is capable of pulling completions from :any:`jedi`, thus allowing | |
38 | type inference on non-executed code. If :any:`jedi` is installed completion like |
|
38 | type inference on non-executed code. If :any:`jedi` is installed completion like | |
39 | the following are now becoming possible without code evaluation: |
|
39 | the following are now becoming possible without code evaluation: | |
40 |
|
40 | |||
41 | >>> data = ['Number of users', 123_456] |
|
41 | >>> data = ['Number of users', 123_456] | |
42 | ... data[0].<tab> |
|
42 | ... data[0].<tab> | |
43 |
|
43 | |||
44 | That is to say, IPython is now capable of inferring that `data[0]` is a string, |
|
44 | That is to say, IPython is now capable of inferring that `data[0]` is a string, | |
45 | and will suggest completions like `.capitalize`. The completion power of IPython |
|
45 | and will suggest completions like `.capitalize`. The completion power of IPython | |
46 | will increase with new Jedi releases, and a number of bugs and more completions |
|
46 | will increase with new Jedi releases, and a number of bugs and more completions | |
47 | are already available on development version of :any:`jedi` if you are curious. |
|
47 | are already available on development version of :any:`jedi` if you are curious. | |
48 |
|
48 | |||
49 | With the help of prompt toolkit, types of completions can be shown in the |
|
49 | With the help of prompt toolkit, types of completions can be shown in the | |
50 | completer interface: |
|
50 | completer interface: | |
51 |
|
51 | |||
52 | .. image:: ../_images/jedi_type_inference_60.png |
|
52 | .. image:: ../_images/jedi_type_inference_60.png | |
53 | :alt: Jedi showing ability to do type inference |
|
53 | :alt: Jedi showing ability to do type inference | |
54 | :align: center |
|
54 | :align: center | |
55 | :width: 400px |
|
55 | :width: 400px | |
56 | :target: ../_images/jedi_type_inference_60.png |
|
56 | :target: ../_images/jedi_type_inference_60.png | |
57 |
|
57 | |||
58 | The appearance of the completer is controlled by the |
|
58 | The appearance of the completer is controlled by the | |
59 | ``c.TerminalInteractiveShell.display_completions`` option that will show the |
|
59 | ``c.TerminalInteractiveShell.display_completions`` option that will show the | |
60 | type differently depending on the value among ``'column'``, ``'multicolumn'`` |
|
60 | type differently depending on the value among ``'column'``, ``'multicolumn'`` | |
61 | and ``'readlinelike'`` |
|
61 | and ``'readlinelike'`` | |
62 |
|
62 | |||
63 | The use of Jedi also full fill a number of request and fix a number of bugs |
|
63 | The use of Jedi also full fill a number of request and fix a number of bugs | |
64 | like case insensitive completion, completion after division operator: See |
|
64 | like case insensitive completion, completion after division operator: See | |
65 | :ghpull:`10182`. |
|
65 | :ghpull:`10182`. | |
66 |
|
66 | |||
67 | Extra patches and updates will be needed to the :mod:`ipykernel` package for |
|
67 | Extra patches and updates will be needed to the :mod:`ipykernel` package for | |
68 | this feature to be available to other clients like jupyter Notebook, Lab, |
|
68 | this feature to be available to other clients like jupyter Notebook, Lab, | |
69 | Nteract, Hydrogen... |
|
69 | Nteract, Hydrogen... | |
70 |
|
70 | |||
71 | The use of Jedi can is barely noticeable on recent enough machines, but can be |
|
71 | The use of Jedi can is barely noticeable on recent enough machines, but can be | |
72 | feel on older ones, in cases were Jedi behavior need to be adjusted, the amount |
|
72 | feel on older ones, in cases were Jedi behavior need to be adjusted, the amount | |
73 | of time given to Jedi to compute type inference can be adjusted with |
|
73 | of time given to Jedi to compute type inference can be adjusted with | |
74 | ``c.IPCompleter.jedi_compute_type_timeout``, with object whose type were not |
|
74 | ``c.IPCompleter.jedi_compute_type_timeout``, with object whose type were not | |
75 | inferred will be shown as ``<unknown>``. Jedi can also be completely deactivated |
|
75 | inferred will be shown as ``<unknown>``. Jedi can also be completely deactivated | |
76 | by using the ``c.Completer.use_jedi=False`` option. |
|
76 | by using the ``c.Completer.use_jedi=False`` option. | |
77 |
|
77 | |||
78 |
|
78 | |||
79 | The old ``Completer.complete()`` API is waiting deprecation and should be |
|
79 | The old ``Completer.complete()`` API is waiting deprecation and should be | |
80 | replaced replaced by ``Completer.completions()`` in a near future. Feedback on |
|
80 | replaced replaced by ``Completer.completions()`` in a near future. Feedback on | |
81 | the current state of the API and suggestions welcome. |
|
81 | the current state of the API and suggestions welcome. | |
82 |
|
82 | |||
83 | Python 3 only codebase |
|
83 | Python 3 only codebase | |
84 | ---------------------- |
|
84 | ---------------------- | |
85 |
|
85 | |||
86 | One of the large challenges in IPython 6.0 has been the adoption of a pure |
|
86 | One of the large challenges in IPython 6.0 has been the adoption of a pure | |
87 | Python 3 code base, which lead us to great length to upstream patches in pip, |
|
87 | Python 3 code base, which lead us to great length to upstream patches in pip, | |
88 | pypi and warehouse to make sure Python 2 system still upgrade to the latest |
|
88 | pypi and warehouse to make sure Python 2 system still upgrade to the latest | |
89 | compatible Python version compatible. |
|
89 | compatible Python version compatible. | |
90 |
|
90 | |||
91 | We remind our Python 2 users that IPython 5 is still compatible with Python 2.7, |
|
91 | We remind our Python 2 users that IPython 5 is still compatible with Python 2.7, | |
92 | still maintained and get regular releases. Using pip 9+, upgrading IPython will |
|
92 | still maintained and get regular releases. Using pip 9+, upgrading IPython will | |
93 | automatically upgrade to the latest version compatible with your system. |
|
93 | automatically upgrade to the latest version compatible with your system. | |
94 |
|
94 | |||
95 | .. warning:: |
|
95 | .. warning:: | |
96 |
|
96 | |||
97 | If you are on a system using an older verison of pip on Python 2, pip may |
|
97 | If you are on a system using an older verison of pip on Python 2, pip may | |
98 | still install IPython 6.0 on your system, and IPython will refuse to start. |
|
98 | still install IPython 6.0 on your system, and IPython will refuse to start. | |
99 | You can fix this by ugrading pip, and reinstalling ipython, or forcing pip to |
|
99 | You can fix this by ugrading pip, and reinstalling ipython, or forcing pip to | |
100 | install an earlier version: ``pip install 'ipython<6'`` |
|
100 | install an earlier version: ``pip install 'ipython<6'`` | |
101 |
|
101 | |||
102 | The ability to use only Python 3 on the code base of IPython has bring a number |
|
102 | The ability to use only Python 3 on the code base of IPython has bring a number | |
103 | of advantage. Most of the newly written code make use of `optional function type |
|
103 | of advantage. Most of the newly written code make use of `optional function type | |
104 | anotation <https://www.python.org/dev/peps/pep-0484/>`_ leading to clearer code |
|
104 | anotation <https://www.python.org/dev/peps/pep-0484/>`_ leading to clearer code | |
105 | and better documentation. |
|
105 | and better documentation. | |
106 |
|
106 | |||
107 | The total size of the repository has also for a first time between releases |
|
107 | The total size of the repository has also for a first time between releases | |
108 | (excluding the big split for 4.0) decreased by about 1500 lines, potentially |
|
108 | (excluding the big split for 4.0) decreased by about 1500 lines, potentially | |
109 | quite a bit more codewide as some documents like this one are append only and |
|
109 | quite a bit more codewide as some documents like this one are append only and | |
110 | are about 300 lines long. |
|
110 | are about 300 lines long. | |
111 |
|
111 | |||
112 | The removal as of Python2/Python3 shim layer has made the code quite clearer and |
|
112 | The removal as of Python2/Python3 shim layer has made the code quite clearer and | |
113 | more idiomatic in a number of location, and much friendlier to work with and |
|
113 | more idiomatic in a number of location, and much friendlier to work with and | |
114 | understand. We hope to further embrace Python 3 capability in the next release |
|
114 | understand. We hope to further embrace Python 3 capability in the next release | |
115 | cycle and introduce more of the Python 3 only idioms (yield from, kwarg only, |
|
115 | cycle and introduce more of the Python 3 only idioms (yield from, kwarg only, | |
116 | general unpacking) in the code base of IPython, and see if we can take advantage |
|
116 | general unpacking) in the code base of IPython, and see if we can take advantage | |
117 | of these as well to improve user experience with better error messages and |
|
117 | of these as well to improve user experience with better error messages and | |
118 | hints. |
|
118 | hints. | |
119 |
|
119 | |||
120 |
|
120 | |||
121 | Miscs improvements |
|
121 | Miscs improvements | |
122 | ------------------ |
|
122 | ------------------ | |
123 |
|
123 | |||
124 |
|
124 | |||
125 | - The :cellmagic:`capture` magic can now capture the result of a cell (from an |
|
125 | - The :cellmagic:`capture` magic can now capture the result of a cell (from an | |
126 | expression on the last line), as well as printed and displayed output. |
|
126 | expression on the last line), as well as printed and displayed output. | |
127 | :ghpull:`9851`. |
|
127 | :ghpull:`9851`. | |
128 |
|
128 | |||
129 | - Pressing Ctrl-Z in the terminal debugger now suspends IPython, as it already |
|
129 | - Pressing Ctrl-Z in the terminal debugger now suspends IPython, as it already | |
130 | does in the main terminal prompt. |
|
130 | does in the main terminal prompt. | |
131 |
|
131 | |||
132 | - autoreload can now reload ``Enum``. See :ghissue:`10232` and :ghpull:`10316` |
|
132 | - autoreload can now reload ``Enum``. See :ghissue:`10232` and :ghpull:`10316` | |
133 |
|
133 | |||
134 | - IPython.display has gained a :any:`GeoJSON <IPython.display.GeoJSON>` object. |
|
134 | - IPython.display has gained a :any:`GeoJSON <IPython.display.GeoJSON>` object. | |
135 | :ghpull:`10288` and :ghpull:`10253` |
|
135 | :ghpull:`10288` and :ghpull:`10253` | |
136 |
|
136 | |||
137 | .. DO NOT EDIT THIS LINE BEFORE RELEASE. FEATURE INSERTION POINT. |
|
137 | .. DO NOT EDIT THIS LINE BEFORE RELEASE. FEATURE INSERTION POINT. | |
138 |
|
138 | |||
139 |
|
139 | |||
140 | Functions Deprecated in 6.x Development cycle |
|
140 | Functions Deprecated in 6.x Development cycle | |
141 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
|
141 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | |
142 |
|
142 | |||
143 | - Loading extensions from ``ipython_extension_dir`` print a warning that this |
|
143 | - Loading extensions from ``ipython_extension_dir`` print a warning that this | |
144 | location is pending deprecation. This should only affect users still having |
|
144 | location is pending deprecation. This should only affect users still having | |
145 | extensions installed with ``%install_ext`` which has been deprecated since |
|
145 | extensions installed with ``%install_ext`` which has been deprecated since | |
146 | IPython 4.0, and removed in 5.0. Extensions still present in |
|
146 | IPython 4.0, and removed in 5.0. Extensions still present in | |
147 | ``ipython_extension_dir`` may shadow more recently installed versions using |
|
147 | ``ipython_extension_dir`` may shadow more recently installed versions using | |
148 | pip. It is thus recommended to clean ``ipython_extension_dir`` of any |
|
148 | pip. It is thus recommended to clean ``ipython_extension_dir`` of any | |
149 | extension now available as a package. |
|
149 | extension now available as a package. | |
150 |
|
150 | |||
151 |
|
151 | |||
152 | - ``IPython.utils.warn`` was deprecated in IPython 4.0, and has now been removed. |
|
152 | - ``IPython.utils.warn`` was deprecated in IPython 4.0, and has now been removed. | |
153 | instead of ``IPython.utils.warn`` inbuilt :any:`warnings` module is used. |
|
153 | instead of ``IPython.utils.warn`` inbuilt :any:`warnings` module is used. | |
154 |
|
154 | |||
155 |
|
155 | |||
156 | - The function `IPython.core.oinspect.py:call_tip` is unused, was marked as |
|
156 | - The function `IPython.core.oinspect.py:call_tip` is unused, was marked as | |
157 | Deprecated (raising a Deprecation Warning) and marked for later removal |
|
157 | Deprecated (raising a Deprecation Warning) and marked for later removal | |
158 | :ghpull:`10104` |
|
158 | :ghpull:`10104` | |
159 |
|
159 | |||
160 | Backwards incompatible changes |
|
160 | Backwards incompatible changes | |
161 | ------------------------------ |
|
161 | ------------------------------ | |
162 |
|
162 | |||
163 | Functions Removed in 6.x Development cycle |
|
163 | Functions Removed in 6.x Development cycle | |
164 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
|
164 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | |
165 |
|
165 | |||
166 | The following functions have been removed in the |
|
166 | The following functions have been removed in the | |
167 | development cycle marked for Milestone 6.0. |
|
167 | development cycle marked for Milestone 6.0. | |
168 |
|
168 | |||
169 | - ``IPython/utils/process.py`` - ``is_cmd_found`` |
|
169 | - ``IPython/utils/process.py`` - ``is_cmd_found`` | |
170 | - ``IPython/utils/process.py`` - ``pycmd2argv`` |
|
170 | - ``IPython/utils/process.py`` - ``pycmd2argv`` | |
171 |
|
171 | |||
172 | - The `--deep-reload` flag and the corresponding options to inject `dreload` or |
|
172 | - The `--deep-reload` flag and the corresponding options to inject `dreload` or | |
173 | `reload` into the interactive namespace have been removed. You have to |
|
173 | `reload` into the interactive namespace have been removed. You have to | |
174 | explicitly import `reload` from `IPython.lib.deepreload` to use it. |
|
174 | explicitly import `reload` from `IPython.lib.deepreload` to use it. | |
175 |
|
175 | |||
|
176 | - the :magic:`profile` used to print current IPython profile in use, and which | |||
|
177 | was deprecated in IPython 2.0 does now raise a `DeprecationWarning` error when | |||
|
178 | used. It is often confused with the :magic:`prun` and the deprecation remove | |||
|
179 | should free up the ``profile`` name in future versions. | |||
|
180 | ||||
176 | .. DO NOT EDIT THIS LINE BEFORE RELEASE. INCOMPAT INSERTION POINT. |
|
181 | .. DO NOT EDIT THIS LINE BEFORE RELEASE. INCOMPAT INSERTION POINT. |
General Comments 0
You need to be logged in to leave comments.
Login now