Show More
@@ -1,528 +1,526 b'' | |||||
1 | """Implementation of basic magic functions. |
|
1 | """Implementation of basic magic functions. | |
2 | """ |
|
2 | """ | |
3 | #----------------------------------------------------------------------------- |
|
3 | #----------------------------------------------------------------------------- | |
4 | # Copyright (c) 2012 The IPython Development Team. |
|
4 | # Copyright (c) 2012 The IPython Development Team. | |
5 | # |
|
5 | # | |
6 | # Distributed under the terms of the Modified BSD License. |
|
6 | # Distributed under the terms of the Modified BSD License. | |
7 | # |
|
7 | # | |
8 | # The full license is in the file COPYING.txt, distributed with this software. |
|
8 | # The full license is in the file COPYING.txt, distributed with this software. | |
9 | #----------------------------------------------------------------------------- |
|
9 | #----------------------------------------------------------------------------- | |
10 |
|
10 | |||
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 | # Imports |
|
12 | # Imports | |
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 | from __future__ import print_function |
|
14 | from __future__ import print_function | |
15 |
|
15 | |||
16 | # Stdlib |
|
16 | # Stdlib | |
17 | import io |
|
17 | import io | |
18 | import sys |
|
18 | import sys | |
19 | from pprint import pformat |
|
19 | from pprint import pformat | |
20 |
|
20 | |||
21 | # Our own packages |
|
21 | # Our own packages | |
22 | from IPython.core.error import UsageError |
|
22 | from IPython.core.error import UsageError | |
23 | from IPython.core.inputsplitter import ESC_MAGIC |
|
23 | from IPython.core.inputsplitter import ESC_MAGIC | |
24 | from IPython.core.magic import Magics, magics_class, line_magic |
|
24 | from IPython.core.magic import Magics, magics_class, line_magic | |
25 | from IPython.utils.text import format_screen |
|
25 | from IPython.utils.text import format_screen | |
26 | from IPython.core import magic_arguments, page |
|
26 | from IPython.core import magic_arguments, page | |
27 | from IPython.testing.skipdoctest import skip_doctest |
|
27 | from IPython.testing.skipdoctest import skip_doctest | |
28 | from IPython.utils.ipstruct import Struct |
|
28 | from IPython.utils.ipstruct import Struct | |
29 | from IPython.utils.path import unquote_filename |
|
29 | from IPython.utils.path import unquote_filename | |
30 | from IPython.utils.warn import warn, error |
|
30 | from IPython.utils.warn import warn, error | |
31 |
|
31 | |||
32 | #----------------------------------------------------------------------------- |
|
32 | #----------------------------------------------------------------------------- | |
33 | # Magics class implementation |
|
33 | # Magics class implementation | |
34 | #----------------------------------------------------------------------------- |
|
34 | #----------------------------------------------------------------------------- | |
35 |
|
35 | |||
36 | @magics_class |
|
36 | @magics_class | |
37 | class BasicMagics(Magics): |
|
37 | class BasicMagics(Magics): | |
38 | """Magics that provide central IPython functionality. |
|
38 | """Magics that provide central IPython functionality. | |
39 |
|
39 | |||
40 | These are various magics that don't fit into specific categories but that |
|
40 | These are various magics that don't fit into specific categories but that | |
41 | are all part of the base 'IPython experience'.""" |
|
41 | are all part of the base 'IPython experience'.""" | |
42 |
|
42 | |||
43 | def _lsmagic(self): |
|
43 | def _lsmagic(self): | |
44 | mesc = ESC_MAGIC |
|
44 | mesc = ESC_MAGIC | |
45 | cesc = mesc*2 |
|
45 | cesc = mesc*2 | |
46 | mman = self.shell.magics_manager |
|
46 | mman = self.shell.magics_manager | |
47 | magics = mman.lsmagic() |
|
47 | magics = mman.lsmagic() | |
48 | out = ['Available line magics:', |
|
48 | out = ['Available line magics:', | |
49 | mesc + (' '+mesc).join(sorted(magics['line'])), |
|
49 | mesc + (' '+mesc).join(sorted(magics['line'])), | |
50 | '', |
|
50 | '', | |
51 | 'Available cell magics:', |
|
51 | 'Available cell magics:', | |
52 | cesc + (' '+cesc).join(sorted(magics['cell'])), |
|
52 | cesc + (' '+cesc).join(sorted(magics['cell'])), | |
53 | '', |
|
53 | '', | |
54 | mman.auto_status()] |
|
54 | mman.auto_status()] | |
55 | return '\n'.join(out) |
|
55 | return '\n'.join(out) | |
56 |
|
56 | |||
57 | @line_magic |
|
57 | @line_magic | |
58 | def lsmagic(self, parameter_s=''): |
|
58 | def lsmagic(self, parameter_s=''): | |
59 | """List currently available magic functions.""" |
|
59 | """List currently available magic functions.""" | |
60 | print(self._lsmagic()) |
|
60 | print(self._lsmagic()) | |
61 |
|
61 | |||
62 | def _magic_docs(self, brief=False, rest=False): |
|
62 | def _magic_docs(self, brief=False, rest=False): | |
63 | """Return docstrings from magic functions.""" |
|
63 | """Return docstrings from magic functions.""" | |
64 | mman = self.shell.magics_manager |
|
64 | mman = self.shell.magics_manager | |
65 | docs = mman.lsmagic_docs(brief, missing='No documentation') |
|
65 | docs = mman.lsmagic_docs(brief, missing='No documentation') | |
66 |
|
66 | |||
67 | if rest: |
|
67 | if rest: | |
68 | format_string = '**%s%s**::\n\n\t%s\n\n' |
|
68 | format_string = '**%s%s**::\n\n\t%s\n\n' | |
69 | else: |
|
69 | else: | |
70 | format_string = '%s%s:\n\t%s\n' |
|
70 | format_string = '%s%s:\n\t%s\n' | |
71 |
|
71 | |||
72 | return ''.join( |
|
72 | return ''.join( | |
73 | [format_string % (ESC_MAGIC, fname, fndoc) |
|
73 | [format_string % (ESC_MAGIC, fname, fndoc) | |
74 | for fname, fndoc in sorted(docs['line'].items())] |
|
74 | for fname, fndoc in sorted(docs['line'].items())] | |
75 | + |
|
75 | + | |
76 | [format_string % (ESC_MAGIC*2, fname, fndoc) |
|
76 | [format_string % (ESC_MAGIC*2, fname, fndoc) | |
77 | for fname, fndoc in sorted(docs['cell'].items())] |
|
77 | for fname, fndoc in sorted(docs['cell'].items())] | |
78 | ) |
|
78 | ) | |
79 |
|
79 | |||
80 | @line_magic |
|
80 | @line_magic | |
81 | def magic(self, parameter_s=''): |
|
81 | def magic(self, parameter_s=''): | |
82 | """Print information about the magic function system. |
|
82 | """Print information about the magic function system. | |
83 |
|
83 | |||
84 | Supported formats: -latex, -brief, -rest |
|
84 | Supported formats: -latex, -brief, -rest | |
85 | """ |
|
85 | """ | |
86 |
|
86 | |||
87 | mode = '' |
|
87 | mode = '' | |
88 | try: |
|
88 | try: | |
89 | mode = parameter_s.split()[0][1:] |
|
89 | mode = parameter_s.split()[0][1:] | |
90 | if mode == 'rest': |
|
90 | if mode == 'rest': | |
91 | rest_docs = [] |
|
91 | rest_docs = [] | |
92 | except IndexError: |
|
92 | except IndexError: | |
93 | pass |
|
93 | pass | |
94 |
|
94 | |||
95 | brief = (mode == 'brief') |
|
95 | brief = (mode == 'brief') | |
96 | rest = (mode == 'rest') |
|
96 | rest = (mode == 'rest') | |
97 | magic_docs = self._magic_docs(brief, rest) |
|
97 | magic_docs = self._magic_docs(brief, rest) | |
98 |
|
98 | |||
99 | if mode == 'latex': |
|
99 | if mode == 'latex': | |
100 | print(self.format_latex(magic_docs)) |
|
100 | print(self.format_latex(magic_docs)) | |
101 | return |
|
101 | return | |
102 | else: |
|
102 | else: | |
103 | magic_docs = format_screen(magic_docs) |
|
103 | magic_docs = format_screen(magic_docs) | |
104 | if mode == 'brief': |
|
|||
105 | return magic_docs |
|
|||
106 |
|
104 | |||
107 | out = [""" |
|
105 | out = [""" | |
108 | IPython's 'magic' functions |
|
106 | IPython's 'magic' functions | |
109 | =========================== |
|
107 | =========================== | |
110 |
|
108 | |||
111 | The magic function system provides a series of functions which allow you to |
|
109 | The magic function system provides a series of functions which allow you to | |
112 | control the behavior of IPython itself, plus a lot of system-type |
|
110 | control the behavior of IPython itself, plus a lot of system-type | |
113 | features. There are two kinds of magics, line-oriented and cell-oriented. |
|
111 | features. There are two kinds of magics, line-oriented and cell-oriented. | |
114 |
|
112 | |||
115 | Line magics are prefixed with the % character and work much like OS |
|
113 | Line magics are prefixed with the % character and work much like OS | |
116 | command-line calls: they get as an argument the rest of the line, where |
|
114 | command-line calls: they get as an argument the rest of the line, where | |
117 | arguments are passed without parentheses or quotes. For example, this will |
|
115 | arguments are passed without parentheses or quotes. For example, this will | |
118 | time the given statement:: |
|
116 | time the given statement:: | |
119 |
|
117 | |||
120 | %timeit range(1000) |
|
118 | %timeit range(1000) | |
121 |
|
119 | |||
122 | Cell magics are prefixed with a double %%, and they are functions that get as |
|
120 | Cell magics are prefixed with a double %%, and they are functions that get as | |
123 | an argument not only the rest of the line, but also the lines below it in a |
|
121 | an argument not only the rest of the line, but also the lines below it in a | |
124 | separate argument. These magics are called with two arguments: the rest of the |
|
122 | separate argument. These magics are called with two arguments: the rest of the | |
125 | call line and the body of the cell, consisting of the lines below the first. |
|
123 | call line and the body of the cell, consisting of the lines below the first. | |
126 | For example:: |
|
124 | For example:: | |
127 |
|
125 | |||
128 | %%timeit x = numpy.random.randn((100, 100)) |
|
126 | %%timeit x = numpy.random.randn((100, 100)) | |
129 | numpy.linalg.svd(x) |
|
127 | numpy.linalg.svd(x) | |
130 |
|
128 | |||
131 | will time the execution of the numpy svd routine, running the assignment of x |
|
129 | will time the execution of the numpy svd routine, running the assignment of x | |
132 | as part of the setup phase, which is not timed. |
|
130 | as part of the setup phase, which is not timed. | |
133 |
|
131 | |||
134 | In a line-oriented client (the terminal or Qt console IPython), starting a new |
|
132 | In a line-oriented client (the terminal or Qt console IPython), starting a new | |
135 | input with %% will automatically enter cell mode, and IPython will continue |
|
133 | input with %% will automatically enter cell mode, and IPython will continue | |
136 | reading input until a blank line is given. In the notebook, simply type the |
|
134 | reading input until a blank line is given. In the notebook, simply type the | |
137 | whole cell as one entity, but keep in mind that the %% escape can only be at |
|
135 | whole cell as one entity, but keep in mind that the %% escape can only be at | |
138 | the very start of the cell. |
|
136 | the very start of the cell. | |
139 |
|
137 | |||
140 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
138 | NOTE: If you have 'automagic' enabled (via the command line option or with the | |
141 | %automagic function), you don't need to type in the % explicitly for line |
|
139 | %automagic function), you don't need to type in the % explicitly for line | |
142 | magics; cell magics always require an explicit '%%' escape. By default, |
|
140 | magics; cell magics always require an explicit '%%' escape. By default, | |
143 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
141 | IPython ships with automagic on, so you should only rarely need the % escape. | |
144 |
|
142 | |||
145 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
143 | Example: typing '%cd mydir' (without the quotes) changes you working directory | |
146 | to 'mydir', if it exists. |
|
144 | to 'mydir', if it exists. | |
147 |
|
145 | |||
148 | For a list of the available magic functions, use %lsmagic. For a description |
|
146 | For a list of the available magic functions, use %lsmagic. For a description | |
149 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
147 | of any of them, type %magic_name?, e.g. '%cd?'. | |
150 |
|
148 | |||
151 | Currently the magic system has the following functions:""", |
|
149 | Currently the magic system has the following functions:""", | |
152 | magic_docs, |
|
150 | magic_docs, | |
153 | "Summary of magic functions (from %slsmagic):", |
|
151 | "Summary of magic functions (from %slsmagic):", | |
154 | self._lsmagic(), |
|
152 | self._lsmagic(), | |
155 | ] |
|
153 | ] | |
156 | page.page('\n'.join(out)) |
|
154 | page.page('\n'.join(out)) | |
157 |
|
155 | |||
158 |
|
156 | |||
159 | @line_magic |
|
157 | @line_magic | |
160 | def page(self, parameter_s=''): |
|
158 | def page(self, parameter_s=''): | |
161 | """Pretty print the object and display it through a pager. |
|
159 | """Pretty print the object and display it through a pager. | |
162 |
|
160 | |||
163 | %page [options] OBJECT |
|
161 | %page [options] OBJECT | |
164 |
|
162 | |||
165 | If no object is given, use _ (last output). |
|
163 | If no object is given, use _ (last output). | |
166 |
|
164 | |||
167 | Options: |
|
165 | Options: | |
168 |
|
166 | |||
169 | -r: page str(object), don't pretty-print it.""" |
|
167 | -r: page str(object), don't pretty-print it.""" | |
170 |
|
168 | |||
171 | # After a function contributed by Olivier Aubert, slightly modified. |
|
169 | # After a function contributed by Olivier Aubert, slightly modified. | |
172 |
|
170 | |||
173 | # Process options/args |
|
171 | # Process options/args | |
174 | opts, args = self.parse_options(parameter_s, 'r') |
|
172 | opts, args = self.parse_options(parameter_s, 'r') | |
175 | raw = 'r' in opts |
|
173 | raw = 'r' in opts | |
176 |
|
174 | |||
177 | oname = args and args or '_' |
|
175 | oname = args and args or '_' | |
178 | info = self.shell._ofind(oname) |
|
176 | info = self.shell._ofind(oname) | |
179 | if info['found']: |
|
177 | if info['found']: | |
180 | txt = (raw and str or pformat)( info['obj'] ) |
|
178 | txt = (raw and str or pformat)( info['obj'] ) | |
181 | page.page(txt) |
|
179 | page.page(txt) | |
182 | else: |
|
180 | else: | |
183 | print('Object `%s` not found' % oname) |
|
181 | print('Object `%s` not found' % oname) | |
184 |
|
182 | |||
185 | @line_magic |
|
183 | @line_magic | |
186 | def profile(self, parameter_s=''): |
|
184 | def profile(self, parameter_s=''): | |
187 | """Print your currently active IPython profile.""" |
|
185 | """Print your currently active IPython profile.""" | |
188 | from IPython.core.application import BaseIPythonApplication |
|
186 | from IPython.core.application import BaseIPythonApplication | |
189 | if BaseIPythonApplication.initialized(): |
|
187 | if BaseIPythonApplication.initialized(): | |
190 | print(BaseIPythonApplication.instance().profile) |
|
188 | print(BaseIPythonApplication.instance().profile) | |
191 | else: |
|
189 | else: | |
192 | error("profile is an application-level value, but you don't appear to be in an IPython application") |
|
190 | error("profile is an application-level value, but you don't appear to be in an IPython application") | |
193 |
|
191 | |||
194 | @line_magic |
|
192 | @line_magic | |
195 | def pprint(self, parameter_s=''): |
|
193 | def pprint(self, parameter_s=''): | |
196 | """Toggle pretty printing on/off.""" |
|
194 | """Toggle pretty printing on/off.""" | |
197 | ptformatter = self.shell.display_formatter.formatters['text/plain'] |
|
195 | ptformatter = self.shell.display_formatter.formatters['text/plain'] | |
198 | ptformatter.pprint = bool(1 - ptformatter.pprint) |
|
196 | ptformatter.pprint = bool(1 - ptformatter.pprint) | |
199 | print('Pretty printing has been turned', |
|
197 | print('Pretty printing has been turned', | |
200 | ['OFF','ON'][ptformatter.pprint]) |
|
198 | ['OFF','ON'][ptformatter.pprint]) | |
201 |
|
199 | |||
202 | @line_magic |
|
200 | @line_magic | |
203 | def colors(self, parameter_s=''): |
|
201 | def colors(self, parameter_s=''): | |
204 | """Switch color scheme for prompts, info system and exception handlers. |
|
202 | """Switch color scheme for prompts, info system and exception handlers. | |
205 |
|
203 | |||
206 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
204 | Currently implemented schemes: NoColor, Linux, LightBG. | |
207 |
|
205 | |||
208 | Color scheme names are not case-sensitive. |
|
206 | Color scheme names are not case-sensitive. | |
209 |
|
207 | |||
210 | Examples |
|
208 | Examples | |
211 | -------- |
|
209 | -------- | |
212 | To get a plain black and white terminal:: |
|
210 | To get a plain black and white terminal:: | |
213 |
|
211 | |||
214 | %colors nocolor |
|
212 | %colors nocolor | |
215 | """ |
|
213 | """ | |
216 | def color_switch_err(name): |
|
214 | def color_switch_err(name): | |
217 | warn('Error changing %s color schemes.\n%s' % |
|
215 | warn('Error changing %s color schemes.\n%s' % | |
218 | (name, sys.exc_info()[1])) |
|
216 | (name, sys.exc_info()[1])) | |
219 |
|
217 | |||
220 |
|
218 | |||
221 | new_scheme = parameter_s.strip() |
|
219 | new_scheme = parameter_s.strip() | |
222 | if not new_scheme: |
|
220 | if not new_scheme: | |
223 | raise UsageError( |
|
221 | raise UsageError( | |
224 | "%colors: you must specify a color scheme. See '%colors?'") |
|
222 | "%colors: you must specify a color scheme. See '%colors?'") | |
225 | return |
|
223 | return | |
226 | # local shortcut |
|
224 | # local shortcut | |
227 | shell = self.shell |
|
225 | shell = self.shell | |
228 |
|
226 | |||
229 | import IPython.utils.rlineimpl as readline |
|
227 | import IPython.utils.rlineimpl as readline | |
230 |
|
228 | |||
231 | if not shell.colors_force and \ |
|
229 | if not shell.colors_force and \ | |
232 | not readline.have_readline and sys.platform == "win32": |
|
230 | not readline.have_readline and sys.platform == "win32": | |
233 | msg = """\ |
|
231 | msg = """\ | |
234 | Proper color support under MS Windows requires the pyreadline library. |
|
232 | Proper color support under MS Windows requires the pyreadline library. | |
235 | You can find it at: |
|
233 | You can find it at: | |
236 | http://ipython.org/pyreadline.html |
|
234 | http://ipython.org/pyreadline.html | |
237 | Gary's readline needs the ctypes module, from: |
|
235 | Gary's readline needs the ctypes module, from: | |
238 | http://starship.python.net/crew/theller/ctypes |
|
236 | http://starship.python.net/crew/theller/ctypes | |
239 | (Note that ctypes is already part of Python versions 2.5 and newer). |
|
237 | (Note that ctypes is already part of Python versions 2.5 and newer). | |
240 |
|
238 | |||
241 | Defaulting color scheme to 'NoColor'""" |
|
239 | Defaulting color scheme to 'NoColor'""" | |
242 | new_scheme = 'NoColor' |
|
240 | new_scheme = 'NoColor' | |
243 | warn(msg) |
|
241 | warn(msg) | |
244 |
|
242 | |||
245 | # readline option is 0 |
|
243 | # readline option is 0 | |
246 | if not shell.colors_force and not shell.has_readline: |
|
244 | if not shell.colors_force and not shell.has_readline: | |
247 | new_scheme = 'NoColor' |
|
245 | new_scheme = 'NoColor' | |
248 |
|
246 | |||
249 | # Set prompt colors |
|
247 | # Set prompt colors | |
250 | try: |
|
248 | try: | |
251 | shell.prompt_manager.color_scheme = new_scheme |
|
249 | shell.prompt_manager.color_scheme = new_scheme | |
252 | except: |
|
250 | except: | |
253 | color_switch_err('prompt') |
|
251 | color_switch_err('prompt') | |
254 | else: |
|
252 | else: | |
255 | shell.colors = \ |
|
253 | shell.colors = \ | |
256 | shell.prompt_manager.color_scheme_table.active_scheme_name |
|
254 | shell.prompt_manager.color_scheme_table.active_scheme_name | |
257 | # Set exception colors |
|
255 | # Set exception colors | |
258 | try: |
|
256 | try: | |
259 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
257 | shell.InteractiveTB.set_colors(scheme = new_scheme) | |
260 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
258 | shell.SyntaxTB.set_colors(scheme = new_scheme) | |
261 | except: |
|
259 | except: | |
262 | color_switch_err('exception') |
|
260 | color_switch_err('exception') | |
263 |
|
261 | |||
264 | # Set info (for 'object?') colors |
|
262 | # Set info (for 'object?') colors | |
265 | if shell.color_info: |
|
263 | if shell.color_info: | |
266 | try: |
|
264 | try: | |
267 | shell.inspector.set_active_scheme(new_scheme) |
|
265 | shell.inspector.set_active_scheme(new_scheme) | |
268 | except: |
|
266 | except: | |
269 | color_switch_err('object inspector') |
|
267 | color_switch_err('object inspector') | |
270 | else: |
|
268 | else: | |
271 | shell.inspector.set_active_scheme('NoColor') |
|
269 | shell.inspector.set_active_scheme('NoColor') | |
272 |
|
270 | |||
273 | @line_magic |
|
271 | @line_magic | |
274 | def xmode(self, parameter_s=''): |
|
272 | def xmode(self, parameter_s=''): | |
275 | """Switch modes for the exception handlers. |
|
273 | """Switch modes for the exception handlers. | |
276 |
|
274 | |||
277 | Valid modes: Plain, Context and Verbose. |
|
275 | Valid modes: Plain, Context and Verbose. | |
278 |
|
276 | |||
279 | If called without arguments, acts as a toggle.""" |
|
277 | If called without arguments, acts as a toggle.""" | |
280 |
|
278 | |||
281 | def xmode_switch_err(name): |
|
279 | def xmode_switch_err(name): | |
282 | warn('Error changing %s exception modes.\n%s' % |
|
280 | warn('Error changing %s exception modes.\n%s' % | |
283 | (name,sys.exc_info()[1])) |
|
281 | (name,sys.exc_info()[1])) | |
284 |
|
282 | |||
285 | shell = self.shell |
|
283 | shell = self.shell | |
286 | new_mode = parameter_s.strip().capitalize() |
|
284 | new_mode = parameter_s.strip().capitalize() | |
287 | try: |
|
285 | try: | |
288 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
286 | shell.InteractiveTB.set_mode(mode=new_mode) | |
289 | print('Exception reporting mode:',shell.InteractiveTB.mode) |
|
287 | print('Exception reporting mode:',shell.InteractiveTB.mode) | |
290 | except: |
|
288 | except: | |
291 | xmode_switch_err('user') |
|
289 | xmode_switch_err('user') | |
292 |
|
290 | |||
293 | @line_magic |
|
291 | @line_magic | |
294 | def quickref(self,arg): |
|
292 | def quickref(self,arg): | |
295 | """ Show a quick reference sheet """ |
|
293 | """ Show a quick reference sheet """ | |
296 | from IPython.core.usage import quick_reference |
|
294 | from IPython.core.usage import quick_reference | |
297 |
qr = quick_reference + self.magic( |
|
295 | qr = quick_reference + self._magic_docs(brief=True) | |
298 | page.page(qr) |
|
296 | page.page(qr) | |
299 |
|
297 | |||
300 | @line_magic |
|
298 | @line_magic | |
301 | def doctest_mode(self, parameter_s=''): |
|
299 | def doctest_mode(self, parameter_s=''): | |
302 | """Toggle doctest mode on and off. |
|
300 | """Toggle doctest mode on and off. | |
303 |
|
301 | |||
304 | This mode is intended to make IPython behave as much as possible like a |
|
302 | This mode is intended to make IPython behave as much as possible like a | |
305 | plain Python shell, from the perspective of how its prompts, exceptions |
|
303 | plain Python shell, from the perspective of how its prompts, exceptions | |
306 | and output look. This makes it easy to copy and paste parts of a |
|
304 | and output look. This makes it easy to copy and paste parts of a | |
307 | session into doctests. It does so by: |
|
305 | session into doctests. It does so by: | |
308 |
|
306 | |||
309 | - Changing the prompts to the classic ``>>>`` ones. |
|
307 | - Changing the prompts to the classic ``>>>`` ones. | |
310 | - Changing the exception reporting mode to 'Plain'. |
|
308 | - Changing the exception reporting mode to 'Plain'. | |
311 | - Disabling pretty-printing of output. |
|
309 | - Disabling pretty-printing of output. | |
312 |
|
310 | |||
313 | Note that IPython also supports the pasting of code snippets that have |
|
311 | Note that IPython also supports the pasting of code snippets that have | |
314 | leading '>>>' and '...' prompts in them. This means that you can paste |
|
312 | leading '>>>' and '...' prompts in them. This means that you can paste | |
315 | doctests from files or docstrings (even if they have leading |
|
313 | doctests from files or docstrings (even if they have leading | |
316 | whitespace), and the code will execute correctly. You can then use |
|
314 | whitespace), and the code will execute correctly. You can then use | |
317 | '%history -t' to see the translated history; this will give you the |
|
315 | '%history -t' to see the translated history; this will give you the | |
318 | input after removal of all the leading prompts and whitespace, which |
|
316 | input after removal of all the leading prompts and whitespace, which | |
319 | can be pasted back into an editor. |
|
317 | can be pasted back into an editor. | |
320 |
|
318 | |||
321 | With these features, you can switch into this mode easily whenever you |
|
319 | With these features, you can switch into this mode easily whenever you | |
322 | need to do testing and changes to doctests, without having to leave |
|
320 | need to do testing and changes to doctests, without having to leave | |
323 | your existing IPython session. |
|
321 | your existing IPython session. | |
324 | """ |
|
322 | """ | |
325 |
|
323 | |||
326 | # Shorthands |
|
324 | # Shorthands | |
327 | shell = self.shell |
|
325 | shell = self.shell | |
328 | pm = shell.prompt_manager |
|
326 | pm = shell.prompt_manager | |
329 | meta = shell.meta |
|
327 | meta = shell.meta | |
330 | disp_formatter = self.shell.display_formatter |
|
328 | disp_formatter = self.shell.display_formatter | |
331 | ptformatter = disp_formatter.formatters['text/plain'] |
|
329 | ptformatter = disp_formatter.formatters['text/plain'] | |
332 | # dstore is a data store kept in the instance metadata bag to track any |
|
330 | # dstore is a data store kept in the instance metadata bag to track any | |
333 | # changes we make, so we can undo them later. |
|
331 | # changes we make, so we can undo them later. | |
334 | dstore = meta.setdefault('doctest_mode',Struct()) |
|
332 | dstore = meta.setdefault('doctest_mode',Struct()) | |
335 | save_dstore = dstore.setdefault |
|
333 | save_dstore = dstore.setdefault | |
336 |
|
334 | |||
337 | # save a few values we'll need to recover later |
|
335 | # save a few values we'll need to recover later | |
338 | mode = save_dstore('mode',False) |
|
336 | mode = save_dstore('mode',False) | |
339 | save_dstore('rc_pprint',ptformatter.pprint) |
|
337 | save_dstore('rc_pprint',ptformatter.pprint) | |
340 | save_dstore('xmode',shell.InteractiveTB.mode) |
|
338 | save_dstore('xmode',shell.InteractiveTB.mode) | |
341 | save_dstore('rc_separate_out',shell.separate_out) |
|
339 | save_dstore('rc_separate_out',shell.separate_out) | |
342 | save_dstore('rc_separate_out2',shell.separate_out2) |
|
340 | save_dstore('rc_separate_out2',shell.separate_out2) | |
343 | save_dstore('rc_prompts_pad_left',pm.justify) |
|
341 | save_dstore('rc_prompts_pad_left',pm.justify) | |
344 | save_dstore('rc_separate_in',shell.separate_in) |
|
342 | save_dstore('rc_separate_in',shell.separate_in) | |
345 | save_dstore('rc_plain_text_only',disp_formatter.plain_text_only) |
|
343 | save_dstore('rc_plain_text_only',disp_formatter.plain_text_only) | |
346 | save_dstore('prompt_templates',(pm.in_template, pm.in2_template, pm.out_template)) |
|
344 | save_dstore('prompt_templates',(pm.in_template, pm.in2_template, pm.out_template)) | |
347 |
|
345 | |||
348 | if mode == False: |
|
346 | if mode == False: | |
349 | # turn on |
|
347 | # turn on | |
350 | pm.in_template = '>>> ' |
|
348 | pm.in_template = '>>> ' | |
351 | pm.in2_template = '... ' |
|
349 | pm.in2_template = '... ' | |
352 | pm.out_template = '' |
|
350 | pm.out_template = '' | |
353 |
|
351 | |||
354 | # Prompt separators like plain python |
|
352 | # Prompt separators like plain python | |
355 | shell.separate_in = '' |
|
353 | shell.separate_in = '' | |
356 | shell.separate_out = '' |
|
354 | shell.separate_out = '' | |
357 | shell.separate_out2 = '' |
|
355 | shell.separate_out2 = '' | |
358 |
|
356 | |||
359 | pm.justify = False |
|
357 | pm.justify = False | |
360 |
|
358 | |||
361 | ptformatter.pprint = False |
|
359 | ptformatter.pprint = False | |
362 | disp_formatter.plain_text_only = True |
|
360 | disp_formatter.plain_text_only = True | |
363 |
|
361 | |||
364 | shell.magic('xmode Plain') |
|
362 | shell.magic('xmode Plain') | |
365 | else: |
|
363 | else: | |
366 | # turn off |
|
364 | # turn off | |
367 | pm.in_template, pm.in2_template, pm.out_template = dstore.prompt_templates |
|
365 | pm.in_template, pm.in2_template, pm.out_template = dstore.prompt_templates | |
368 |
|
366 | |||
369 | shell.separate_in = dstore.rc_separate_in |
|
367 | shell.separate_in = dstore.rc_separate_in | |
370 |
|
368 | |||
371 | shell.separate_out = dstore.rc_separate_out |
|
369 | shell.separate_out = dstore.rc_separate_out | |
372 | shell.separate_out2 = dstore.rc_separate_out2 |
|
370 | shell.separate_out2 = dstore.rc_separate_out2 | |
373 |
|
371 | |||
374 | pm.justify = dstore.rc_prompts_pad_left |
|
372 | pm.justify = dstore.rc_prompts_pad_left | |
375 |
|
373 | |||
376 | ptformatter.pprint = dstore.rc_pprint |
|
374 | ptformatter.pprint = dstore.rc_pprint | |
377 | disp_formatter.plain_text_only = dstore.rc_plain_text_only |
|
375 | disp_formatter.plain_text_only = dstore.rc_plain_text_only | |
378 |
|
376 | |||
379 | shell.magic('xmode ' + dstore.xmode) |
|
377 | shell.magic('xmode ' + dstore.xmode) | |
380 |
|
378 | |||
381 | # Store new mode and inform |
|
379 | # Store new mode and inform | |
382 | dstore.mode = bool(1-int(mode)) |
|
380 | dstore.mode = bool(1-int(mode)) | |
383 | mode_label = ['OFF','ON'][dstore.mode] |
|
381 | mode_label = ['OFF','ON'][dstore.mode] | |
384 | print('Doctest mode is:', mode_label) |
|
382 | print('Doctest mode is:', mode_label) | |
385 |
|
383 | |||
386 | @line_magic |
|
384 | @line_magic | |
387 | def gui(self, parameter_s=''): |
|
385 | def gui(self, parameter_s=''): | |
388 | """Enable or disable IPython GUI event loop integration. |
|
386 | """Enable or disable IPython GUI event loop integration. | |
389 |
|
387 | |||
390 | %gui [GUINAME] |
|
388 | %gui [GUINAME] | |
391 |
|
389 | |||
392 | This magic replaces IPython's threaded shells that were activated |
|
390 | This magic replaces IPython's threaded shells that were activated | |
393 | using the (pylab/wthread/etc.) command line flags. GUI toolkits |
|
391 | using the (pylab/wthread/etc.) command line flags. GUI toolkits | |
394 | can now be enabled at runtime and keyboard |
|
392 | can now be enabled at runtime and keyboard | |
395 | interrupts should work without any problems. The following toolkits |
|
393 | interrupts should work without any problems. The following toolkits | |
396 | are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX):: |
|
394 | are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX):: | |
397 |
|
395 | |||
398 | %gui wx # enable wxPython event loop integration |
|
396 | %gui wx # enable wxPython event loop integration | |
399 | %gui qt4|qt # enable PyQt4 event loop integration |
|
397 | %gui qt4|qt # enable PyQt4 event loop integration | |
400 | %gui gtk # enable PyGTK event loop integration |
|
398 | %gui gtk # enable PyGTK event loop integration | |
401 | %gui gtk3 # enable Gtk3 event loop integration |
|
399 | %gui gtk3 # enable Gtk3 event loop integration | |
402 | %gui tk # enable Tk event loop integration |
|
400 | %gui tk # enable Tk event loop integration | |
403 | %gui osx # enable Cocoa event loop integration |
|
401 | %gui osx # enable Cocoa event loop integration | |
404 | # (requires %matplotlib 1.1) |
|
402 | # (requires %matplotlib 1.1) | |
405 | %gui # disable all event loop integration |
|
403 | %gui # disable all event loop integration | |
406 |
|
404 | |||
407 | WARNING: after any of these has been called you can simply create |
|
405 | WARNING: after any of these has been called you can simply create | |
408 | an application object, but DO NOT start the event loop yourself, as |
|
406 | an application object, but DO NOT start the event loop yourself, as | |
409 | we have already handled that. |
|
407 | we have already handled that. | |
410 | """ |
|
408 | """ | |
411 | opts, arg = self.parse_options(parameter_s, '') |
|
409 | opts, arg = self.parse_options(parameter_s, '') | |
412 | if arg=='': arg = None |
|
410 | if arg=='': arg = None | |
413 | try: |
|
411 | try: | |
414 | return self.shell.enable_gui(arg) |
|
412 | return self.shell.enable_gui(arg) | |
415 | except Exception as e: |
|
413 | except Exception as e: | |
416 | # print simple error message, rather than traceback if we can't |
|
414 | # print simple error message, rather than traceback if we can't | |
417 | # hook up the GUI |
|
415 | # hook up the GUI | |
418 | error(str(e)) |
|
416 | error(str(e)) | |
419 |
|
417 | |||
420 | @skip_doctest |
|
418 | @skip_doctest | |
421 | @line_magic |
|
419 | @line_magic | |
422 | def precision(self, s=''): |
|
420 | def precision(self, s=''): | |
423 | """Set floating point precision for pretty printing. |
|
421 | """Set floating point precision for pretty printing. | |
424 |
|
422 | |||
425 | Can set either integer precision or a format string. |
|
423 | Can set either integer precision or a format string. | |
426 |
|
424 | |||
427 | If numpy has been imported and precision is an int, |
|
425 | If numpy has been imported and precision is an int, | |
428 | numpy display precision will also be set, via ``numpy.set_printoptions``. |
|
426 | numpy display precision will also be set, via ``numpy.set_printoptions``. | |
429 |
|
427 | |||
430 | If no argument is given, defaults will be restored. |
|
428 | If no argument is given, defaults will be restored. | |
431 |
|
429 | |||
432 | Examples |
|
430 | Examples | |
433 | -------- |
|
431 | -------- | |
434 | :: |
|
432 | :: | |
435 |
|
433 | |||
436 | In [1]: from math import pi |
|
434 | In [1]: from math import pi | |
437 |
|
435 | |||
438 | In [2]: %precision 3 |
|
436 | In [2]: %precision 3 | |
439 | Out[2]: u'%.3f' |
|
437 | Out[2]: u'%.3f' | |
440 |
|
438 | |||
441 | In [3]: pi |
|
439 | In [3]: pi | |
442 | Out[3]: 3.142 |
|
440 | Out[3]: 3.142 | |
443 |
|
441 | |||
444 | In [4]: %precision %i |
|
442 | In [4]: %precision %i | |
445 | Out[4]: u'%i' |
|
443 | Out[4]: u'%i' | |
446 |
|
444 | |||
447 | In [5]: pi |
|
445 | In [5]: pi | |
448 | Out[5]: 3 |
|
446 | Out[5]: 3 | |
449 |
|
447 | |||
450 | In [6]: %precision %e |
|
448 | In [6]: %precision %e | |
451 | Out[6]: u'%e' |
|
449 | Out[6]: u'%e' | |
452 |
|
450 | |||
453 | In [7]: pi**10 |
|
451 | In [7]: pi**10 | |
454 | Out[7]: 9.364805e+04 |
|
452 | Out[7]: 9.364805e+04 | |
455 |
|
453 | |||
456 | In [8]: %precision |
|
454 | In [8]: %precision | |
457 | Out[8]: u'%r' |
|
455 | Out[8]: u'%r' | |
458 |
|
456 | |||
459 | In [9]: pi**10 |
|
457 | In [9]: pi**10 | |
460 | Out[9]: 93648.047476082982 |
|
458 | Out[9]: 93648.047476082982 | |
461 | """ |
|
459 | """ | |
462 | ptformatter = self.shell.display_formatter.formatters['text/plain'] |
|
460 | ptformatter = self.shell.display_formatter.formatters['text/plain'] | |
463 | ptformatter.float_precision = s |
|
461 | ptformatter.float_precision = s | |
464 | return ptformatter.float_format |
|
462 | return ptformatter.float_format | |
465 |
|
463 | |||
466 | @magic_arguments.magic_arguments() |
|
464 | @magic_arguments.magic_arguments() | |
467 | @magic_arguments.argument( |
|
465 | @magic_arguments.argument( | |
468 | '-e', '--export', action='store_true', default=False, |
|
466 | '-e', '--export', action='store_true', default=False, | |
469 | help='Export IPython history as a notebook. The filename argument ' |
|
467 | help='Export IPython history as a notebook. The filename argument ' | |
470 | 'is used to specify the notebook name and format. For example ' |
|
468 | 'is used to specify the notebook name and format. For example ' | |
471 | 'a filename of notebook.ipynb will result in a notebook name ' |
|
469 | 'a filename of notebook.ipynb will result in a notebook name ' | |
472 | 'of "notebook" and a format of "xml". Likewise using a ".json" ' |
|
470 | 'of "notebook" and a format of "xml". Likewise using a ".json" ' | |
473 | 'or ".py" file extension will write the notebook in the json ' |
|
471 | 'or ".py" file extension will write the notebook in the json ' | |
474 | 'or py formats.' |
|
472 | 'or py formats.' | |
475 | ) |
|
473 | ) | |
476 | @magic_arguments.argument( |
|
474 | @magic_arguments.argument( | |
477 | '-f', '--format', |
|
475 | '-f', '--format', | |
478 | help='Convert an existing IPython notebook to a new format. This option ' |
|
476 | help='Convert an existing IPython notebook to a new format. This option ' | |
479 | 'specifies the new format and can have the values: xml, json, py. ' |
|
477 | 'specifies the new format and can have the values: xml, json, py. ' | |
480 | 'The target filename is chosen automatically based on the new ' |
|
478 | 'The target filename is chosen automatically based on the new ' | |
481 | 'format. The filename argument gives the name of the source file.' |
|
479 | 'format. The filename argument gives the name of the source file.' | |
482 | ) |
|
480 | ) | |
483 | @magic_arguments.argument( |
|
481 | @magic_arguments.argument( | |
484 | 'filename', type=unicode, |
|
482 | 'filename', type=unicode, | |
485 | help='Notebook name or filename' |
|
483 | help='Notebook name or filename' | |
486 | ) |
|
484 | ) | |
487 | @line_magic |
|
485 | @line_magic | |
488 | def notebook(self, s): |
|
486 | def notebook(self, s): | |
489 | """Export and convert IPython notebooks. |
|
487 | """Export and convert IPython notebooks. | |
490 |
|
488 | |||
491 | This function can export the current IPython history to a notebook file |
|
489 | This function can export the current IPython history to a notebook file | |
492 | or can convert an existing notebook file into a different format. For |
|
490 | or can convert an existing notebook file into a different format. For | |
493 | example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb". |
|
491 | example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb". | |
494 | To export the history to "foo.py" do "%notebook -e foo.py". To convert |
|
492 | To export the history to "foo.py" do "%notebook -e foo.py". To convert | |
495 | "foo.ipynb" to "foo.json" do "%notebook -f json foo.ipynb". Possible |
|
493 | "foo.ipynb" to "foo.json" do "%notebook -f json foo.ipynb". Possible | |
496 | formats include (json/ipynb, py). |
|
494 | formats include (json/ipynb, py). | |
497 | """ |
|
495 | """ | |
498 | args = magic_arguments.parse_argstring(self.notebook, s) |
|
496 | args = magic_arguments.parse_argstring(self.notebook, s) | |
499 |
|
497 | |||
500 | from IPython.nbformat import current |
|
498 | from IPython.nbformat import current | |
501 | args.filename = unquote_filename(args.filename) |
|
499 | args.filename = unquote_filename(args.filename) | |
502 | if args.export: |
|
500 | if args.export: | |
503 | fname, name, format = current.parse_filename(args.filename) |
|
501 | fname, name, format = current.parse_filename(args.filename) | |
504 | cells = [] |
|
502 | cells = [] | |
505 | hist = list(self.shell.history_manager.get_range()) |
|
503 | hist = list(self.shell.history_manager.get_range()) | |
506 | for session, prompt_number, input in hist[:-1]: |
|
504 | for session, prompt_number, input in hist[:-1]: | |
507 | cells.append(current.new_code_cell(prompt_number=prompt_number, |
|
505 | cells.append(current.new_code_cell(prompt_number=prompt_number, | |
508 | input=input)) |
|
506 | input=input)) | |
509 | worksheet = current.new_worksheet(cells=cells) |
|
507 | worksheet = current.new_worksheet(cells=cells) | |
510 | nb = current.new_notebook(name=name,worksheets=[worksheet]) |
|
508 | nb = current.new_notebook(name=name,worksheets=[worksheet]) | |
511 | with io.open(fname, 'w', encoding='utf-8') as f: |
|
509 | with io.open(fname, 'w', encoding='utf-8') as f: | |
512 | current.write(nb, f, format); |
|
510 | current.write(nb, f, format); | |
513 | elif args.format is not None: |
|
511 | elif args.format is not None: | |
514 | old_fname, old_name, old_format = current.parse_filename(args.filename) |
|
512 | old_fname, old_name, old_format = current.parse_filename(args.filename) | |
515 | new_format = args.format |
|
513 | new_format = args.format | |
516 | if new_format == u'xml': |
|
514 | if new_format == u'xml': | |
517 | raise ValueError('Notebooks cannot be written as xml.') |
|
515 | raise ValueError('Notebooks cannot be written as xml.') | |
518 | elif new_format == u'ipynb' or new_format == u'json': |
|
516 | elif new_format == u'ipynb' or new_format == u'json': | |
519 | new_fname = old_name + u'.ipynb' |
|
517 | new_fname = old_name + u'.ipynb' | |
520 | new_format = u'json' |
|
518 | new_format = u'json' | |
521 | elif new_format == u'py': |
|
519 | elif new_format == u'py': | |
522 | new_fname = old_name + u'.py' |
|
520 | new_fname = old_name + u'.py' | |
523 | else: |
|
521 | else: | |
524 | raise ValueError('Invalid notebook format: %s' % new_format) |
|
522 | raise ValueError('Invalid notebook format: %s' % new_format) | |
525 | with io.open(old_fname, 'r', encoding='utf-8') as f: |
|
523 | with io.open(old_fname, 'r', encoding='utf-8') as f: | |
526 | nb = current.read(f, old_format) |
|
524 | nb = current.read(f, old_format) | |
527 | with io.open(new_fname, 'w', encoding='utf-8') as f: |
|
525 | with io.open(new_fname, 'w', encoding='utf-8') as f: | |
528 | current.write(nb, f, new_format) |
|
526 | current.write(nb, f, new_format) |
General Comments 0
You need to be logged in to leave comments.
Login now