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