Show More
@@ -1,661 +1,663 b'' | |||
|
1 | 1 | """Implementation of basic magic functions.""" |
|
2 | 2 | |
|
3 | 3 | |
|
4 | 4 | from logging import error |
|
5 | 5 | import io |
|
6 | 6 | import os |
|
7 | 7 | from pprint import pformat |
|
8 | 8 | import sys |
|
9 | 9 | from warnings import warn |
|
10 | 10 | |
|
11 | 11 | from traitlets.utils.importstring import import_item |
|
12 | 12 | from IPython.core import magic_arguments, page |
|
13 | 13 | from IPython.core.error import UsageError |
|
14 | 14 | from IPython.core.magic import Magics, magics_class, line_magic, magic_escapes |
|
15 | 15 | from IPython.utils.text import format_screen, dedent, indent |
|
16 | 16 | from IPython.testing.skipdoctest import skip_doctest |
|
17 | 17 | from IPython.utils.ipstruct import Struct |
|
18 | 18 | |
|
19 | 19 | |
|
20 | 20 | class MagicsDisplay(object): |
|
21 | 21 | def __init__(self, magics_manager, ignore=None): |
|
22 | 22 | self.ignore = ignore if ignore else [] |
|
23 | 23 | self.magics_manager = magics_manager |
|
24 | 24 | |
|
25 | 25 | def _lsmagic(self): |
|
26 | 26 | """The main implementation of the %lsmagic""" |
|
27 | 27 | mesc = magic_escapes['line'] |
|
28 | 28 | cesc = magic_escapes['cell'] |
|
29 | 29 | mman = self.magics_manager |
|
30 | 30 | magics = mman.lsmagic() |
|
31 | 31 | out = ['Available line magics:', |
|
32 | 32 | mesc + (' '+mesc).join(sorted([m for m,v in magics['line'].items() if (v not in self.ignore)])), |
|
33 | 33 | '', |
|
34 | 34 | 'Available cell magics:', |
|
35 | 35 | cesc + (' '+cesc).join(sorted([m for m,v in magics['cell'].items() if (v not in self.ignore)])), |
|
36 | 36 | '', |
|
37 | 37 | mman.auto_status()] |
|
38 | 38 | return '\n'.join(out) |
|
39 | 39 | |
|
40 | 40 | def _repr_pretty_(self, p, cycle): |
|
41 | 41 | p.text(self._lsmagic()) |
|
42 | 42 | |
|
43 | 43 | def __str__(self): |
|
44 | 44 | return self._lsmagic() |
|
45 | 45 | |
|
46 | 46 | def _jsonable(self): |
|
47 | 47 | """turn magics dict into jsonable dict of the same structure |
|
48 | 48 | |
|
49 | 49 | replaces object instances with their class names as strings |
|
50 | 50 | """ |
|
51 | 51 | magic_dict = {} |
|
52 | 52 | mman = self.magics_manager |
|
53 | 53 | magics = mman.lsmagic() |
|
54 | 54 | for key, subdict in magics.items(): |
|
55 | 55 | d = {} |
|
56 | 56 | magic_dict[key] = d |
|
57 | 57 | for name, obj in subdict.items(): |
|
58 | 58 | try: |
|
59 | 59 | classname = obj.__self__.__class__.__name__ |
|
60 | 60 | except AttributeError: |
|
61 | 61 | classname = 'Other' |
|
62 | 62 | |
|
63 | 63 | d[name] = classname |
|
64 | 64 | return magic_dict |
|
65 | 65 | |
|
66 | 66 | def _repr_json_(self): |
|
67 | 67 | return self._jsonable() |
|
68 | 68 | |
|
69 | 69 | |
|
70 | 70 | @magics_class |
|
71 | 71 | class BasicMagics(Magics): |
|
72 | 72 | """Magics that provide central IPython functionality. |
|
73 | 73 | |
|
74 | 74 | These are various magics that don't fit into specific categories but that |
|
75 | 75 | are all part of the base 'IPython experience'.""" |
|
76 | 76 | |
|
77 | 77 | @skip_doctest |
|
78 | 78 | @magic_arguments.magic_arguments() |
|
79 | 79 | @magic_arguments.argument( |
|
80 | 80 | '-l', '--line', action='store_true', |
|
81 | 81 | help="""Create a line magic alias.""" |
|
82 | 82 | ) |
|
83 | 83 | @magic_arguments.argument( |
|
84 | 84 | '-c', '--cell', action='store_true', |
|
85 | 85 | help="""Create a cell magic alias.""" |
|
86 | 86 | ) |
|
87 | 87 | @magic_arguments.argument( |
|
88 | 88 | 'name', |
|
89 | 89 | help="""Name of the magic to be created.""" |
|
90 | 90 | ) |
|
91 | 91 | @magic_arguments.argument( |
|
92 | 92 | 'target', |
|
93 | 93 | help="""Name of the existing line or cell magic.""" |
|
94 | 94 | ) |
|
95 | 95 | @magic_arguments.argument( |
|
96 | 96 | '-p', '--params', default=None, |
|
97 | 97 | help="""Parameters passed to the magic function.""" |
|
98 | 98 | ) |
|
99 | 99 | @line_magic |
|
100 | 100 | def alias_magic(self, line=''): |
|
101 | 101 | """Create an alias for an existing line or cell magic. |
|
102 | 102 | |
|
103 | 103 | Examples |
|
104 | 104 | -------- |
|
105 | 105 | :: |
|
106 | 106 | |
|
107 | 107 | In [1]: %alias_magic t timeit |
|
108 | 108 | Created `%t` as an alias for `%timeit`. |
|
109 | 109 | Created `%%t` as an alias for `%%timeit`. |
|
110 | 110 | |
|
111 | 111 | In [2]: %t -n1 pass |
|
112 | 112 | 1 loops, best of 3: 954 ns per loop |
|
113 | 113 | |
|
114 | 114 | In [3]: %%t -n1 |
|
115 | 115 | ...: pass |
|
116 | 116 | ...: |
|
117 | 117 | 1 loops, best of 3: 954 ns per loop |
|
118 | 118 | |
|
119 | 119 | In [4]: %alias_magic --cell whereami pwd |
|
120 | 120 | UsageError: Cell magic function `%%pwd` not found. |
|
121 | 121 | In [5]: %alias_magic --line whereami pwd |
|
122 | 122 | Created `%whereami` as an alias for `%pwd`. |
|
123 | 123 | |
|
124 | 124 | In [6]: %whereami |
|
125 | 125 | Out[6]: u'/home/testuser' |
|
126 | 126 | |
|
127 | 127 | In [7]: %alias_magic h history "-p -l 30" --line |
|
128 | 128 | Created `%h` as an alias for `%history -l 30`. |
|
129 | 129 | """ |
|
130 | 130 | |
|
131 | 131 | args = magic_arguments.parse_argstring(self.alias_magic, line) |
|
132 | 132 | shell = self.shell |
|
133 | 133 | mman = self.shell.magics_manager |
|
134 | 134 | escs = ''.join(magic_escapes.values()) |
|
135 | 135 | |
|
136 | 136 | target = args.target.lstrip(escs) |
|
137 | 137 | name = args.name.lstrip(escs) |
|
138 | 138 | |
|
139 | 139 | params = args.params |
|
140 | 140 | if (params and |
|
141 | 141 | ((params.startswith('"') and params.endswith('"')) |
|
142 | 142 | or (params.startswith("'") and params.endswith("'")))): |
|
143 | 143 | params = params[1:-1] |
|
144 | 144 | |
|
145 | 145 | # Find the requested magics. |
|
146 | 146 | m_line = shell.find_magic(target, 'line') |
|
147 | 147 | m_cell = shell.find_magic(target, 'cell') |
|
148 | 148 | if args.line and m_line is None: |
|
149 | 149 | raise UsageError('Line magic function `%s%s` not found.' % |
|
150 | 150 | (magic_escapes['line'], target)) |
|
151 | 151 | if args.cell and m_cell is None: |
|
152 | 152 | raise UsageError('Cell magic function `%s%s` not found.' % |
|
153 | 153 | (magic_escapes['cell'], target)) |
|
154 | 154 | |
|
155 | 155 | # If --line and --cell are not specified, default to the ones |
|
156 | 156 | # that are available. |
|
157 | 157 | if not args.line and not args.cell: |
|
158 | 158 | if not m_line and not m_cell: |
|
159 | 159 | raise UsageError( |
|
160 | 160 | 'No line or cell magic with name `%s` found.' % target |
|
161 | 161 | ) |
|
162 | 162 | args.line = bool(m_line) |
|
163 | 163 | args.cell = bool(m_cell) |
|
164 | 164 | |
|
165 | 165 | params_str = "" if params is None else " " + params |
|
166 | 166 | |
|
167 | 167 | if args.line: |
|
168 | 168 | mman.register_alias(name, target, 'line', params) |
|
169 | 169 | print('Created `%s%s` as an alias for `%s%s%s`.' % ( |
|
170 | 170 | magic_escapes['line'], name, |
|
171 | 171 | magic_escapes['line'], target, params_str)) |
|
172 | 172 | |
|
173 | 173 | if args.cell: |
|
174 | 174 | mman.register_alias(name, target, 'cell', params) |
|
175 | 175 | print('Created `%s%s` as an alias for `%s%s%s`.' % ( |
|
176 | 176 | magic_escapes['cell'], name, |
|
177 | 177 | magic_escapes['cell'], target, params_str)) |
|
178 | 178 | |
|
179 | 179 | @line_magic |
|
180 | 180 | def lsmagic(self, parameter_s=''): |
|
181 | 181 | """List currently available magic functions.""" |
|
182 | 182 | return MagicsDisplay(self.shell.magics_manager, ignore=[]) |
|
183 | 183 | |
|
184 | 184 | def _magic_docs(self, brief=False, rest=False): |
|
185 | 185 | """Return docstrings from magic functions.""" |
|
186 | 186 | mman = self.shell.magics_manager |
|
187 | 187 | docs = mman.lsmagic_docs(brief, missing='No documentation') |
|
188 | 188 | |
|
189 | 189 | if rest: |
|
190 | 190 | format_string = '**%s%s**::\n\n%s\n\n' |
|
191 | 191 | else: |
|
192 | 192 | format_string = '%s%s:\n%s\n' |
|
193 | 193 | |
|
194 | 194 | return ''.join( |
|
195 | 195 | [format_string % (magic_escapes['line'], fname, |
|
196 | 196 | indent(dedent(fndoc))) |
|
197 | 197 | for fname, fndoc in sorted(docs['line'].items())] |
|
198 | 198 | + |
|
199 | 199 | [format_string % (magic_escapes['cell'], fname, |
|
200 | 200 | indent(dedent(fndoc))) |
|
201 | 201 | for fname, fndoc in sorted(docs['cell'].items())] |
|
202 | 202 | ) |
|
203 | 203 | |
|
204 | 204 | @line_magic |
|
205 | 205 | def magic(self, parameter_s=''): |
|
206 | 206 | """Print information about the magic function system. |
|
207 | 207 | |
|
208 | 208 | Supported formats: -latex, -brief, -rest |
|
209 | 209 | """ |
|
210 | 210 | |
|
211 | 211 | mode = '' |
|
212 | 212 | try: |
|
213 | 213 | mode = parameter_s.split()[0][1:] |
|
214 | 214 | except IndexError: |
|
215 | 215 | pass |
|
216 | 216 | |
|
217 | 217 | brief = (mode == 'brief') |
|
218 | 218 | rest = (mode == 'rest') |
|
219 | 219 | magic_docs = self._magic_docs(brief, rest) |
|
220 | 220 | |
|
221 | 221 | if mode == 'latex': |
|
222 | 222 | print(self.format_latex(magic_docs)) |
|
223 | 223 | return |
|
224 | 224 | else: |
|
225 | 225 | magic_docs = format_screen(magic_docs) |
|
226 | 226 | |
|
227 | 227 | out = [""" |
|
228 | 228 | IPython's 'magic' functions |
|
229 | 229 | =========================== |
|
230 | 230 | |
|
231 | 231 | The magic function system provides a series of functions which allow you to |
|
232 | 232 | control the behavior of IPython itself, plus a lot of system-type |
|
233 | 233 | features. There are two kinds of magics, line-oriented and cell-oriented. |
|
234 | 234 | |
|
235 | 235 | Line magics are prefixed with the % character and work much like OS |
|
236 | 236 | command-line calls: they get as an argument the rest of the line, where |
|
237 | 237 | arguments are passed without parentheses or quotes. For example, this will |
|
238 | 238 | time the given statement:: |
|
239 | 239 | |
|
240 | 240 | %timeit range(1000) |
|
241 | 241 | |
|
242 | 242 | Cell magics are prefixed with a double %%, and they are functions that get as |
|
243 | 243 | an argument not only the rest of the line, but also the lines below it in a |
|
244 | 244 | separate argument. These magics are called with two arguments: the rest of the |
|
245 | 245 | call line and the body of the cell, consisting of the lines below the first. |
|
246 | 246 | For example:: |
|
247 | 247 | |
|
248 | 248 | %%timeit x = numpy.random.randn((100, 100)) |
|
249 | 249 | numpy.linalg.svd(x) |
|
250 | 250 | |
|
251 | 251 | will time the execution of the numpy svd routine, running the assignment of x |
|
252 | 252 | as part of the setup phase, which is not timed. |
|
253 | 253 | |
|
254 | 254 | In a line-oriented client (the terminal or Qt console IPython), starting a new |
|
255 | 255 | input with %% will automatically enter cell mode, and IPython will continue |
|
256 | 256 | reading input until a blank line is given. In the notebook, simply type the |
|
257 | 257 | whole cell as one entity, but keep in mind that the %% escape can only be at |
|
258 | 258 | the very start of the cell. |
|
259 | 259 | |
|
260 | 260 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
261 | 261 | %automagic function), you don't need to type in the % explicitly for line |
|
262 | 262 | magics; cell magics always require an explicit '%%' escape. By default, |
|
263 | 263 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
264 | 264 | |
|
265 | 265 | Example: typing '%cd mydir' (without the quotes) changes your working directory |
|
266 | 266 | to 'mydir', if it exists. |
|
267 | 267 | |
|
268 | 268 | For a list of the available magic functions, use %lsmagic. For a description |
|
269 | 269 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
270 | 270 | |
|
271 | 271 | Currently the magic system has the following functions:""", |
|
272 | 272 | magic_docs, |
|
273 | 273 | "Summary of magic functions (from %slsmagic):" % magic_escapes['line'], |
|
274 | 274 | str(self.lsmagic()), |
|
275 | 275 | ] |
|
276 | 276 | page.page('\n'.join(out)) |
|
277 | 277 | |
|
278 | 278 | |
|
279 | 279 | @line_magic |
|
280 | 280 | def page(self, parameter_s=''): |
|
281 | 281 | """Pretty print the object and display it through a pager. |
|
282 | 282 | |
|
283 | 283 | %page [options] OBJECT |
|
284 | 284 | |
|
285 | 285 | If no object is given, use _ (last output). |
|
286 | 286 | |
|
287 | 287 | Options: |
|
288 | 288 | |
|
289 | 289 | -r: page str(object), don't pretty-print it.""" |
|
290 | 290 | |
|
291 | 291 | # After a function contributed by Olivier Aubert, slightly modified. |
|
292 | 292 | |
|
293 | 293 | # Process options/args |
|
294 | 294 | opts, args = self.parse_options(parameter_s, 'r') |
|
295 | 295 | raw = 'r' in opts |
|
296 | 296 | |
|
297 | 297 | oname = args and args or '_' |
|
298 | 298 | info = self.shell._ofind(oname) |
|
299 | 299 | if info['found']: |
|
300 | 300 | if raw: |
|
301 | 301 | txt = str(info["obj"]) |
|
302 | 302 | else: |
|
303 | 303 | txt = pformat(info["obj"]) |
|
304 | 304 | page.page(txt) |
|
305 | 305 | else: |
|
306 | 306 | print('Object `%s` not found' % oname) |
|
307 | 307 | |
|
308 | 308 | @line_magic |
|
309 | 309 | def pprint(self, parameter_s=''): |
|
310 | 310 | """Toggle pretty printing on/off.""" |
|
311 | 311 | ptformatter = self.shell.display_formatter.formatters['text/plain'] |
|
312 | 312 | ptformatter.pprint = bool(1 - ptformatter.pprint) |
|
313 | 313 | print('Pretty printing has been turned', |
|
314 | 314 | ['OFF','ON'][ptformatter.pprint]) |
|
315 | 315 | |
|
316 | 316 | @line_magic |
|
317 | 317 | def colors(self, parameter_s=''): |
|
318 | 318 | """Switch color scheme for prompts, info system and exception handlers. |
|
319 | 319 | |
|
320 | 320 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
321 | 321 | |
|
322 | 322 | Color scheme names are not case-sensitive. |
|
323 | 323 | |
|
324 | 324 | Examples |
|
325 | 325 | -------- |
|
326 | 326 | To get a plain black and white terminal:: |
|
327 | 327 | |
|
328 | 328 | %colors nocolor |
|
329 | 329 | """ |
|
330 | 330 | def color_switch_err(name): |
|
331 | 331 | warn('Error changing %s color schemes.\n%s' % |
|
332 | 332 | (name, sys.exc_info()[1]), stacklevel=2) |
|
333 | 333 | |
|
334 | 334 | |
|
335 | 335 | new_scheme = parameter_s.strip() |
|
336 | 336 | if not new_scheme: |
|
337 | 337 | raise UsageError( |
|
338 | 338 | "%colors: you must specify a color scheme. See '%colors?'") |
|
339 | 339 | # local shortcut |
|
340 | 340 | shell = self.shell |
|
341 | 341 | |
|
342 | 342 | # Set shell colour scheme |
|
343 | 343 | try: |
|
344 | 344 | shell.colors = new_scheme |
|
345 | 345 | shell.refresh_style() |
|
346 | 346 | except: |
|
347 | 347 | color_switch_err('shell') |
|
348 | 348 | |
|
349 | 349 | # Set exception colors |
|
350 | 350 | try: |
|
351 | 351 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
352 | 352 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
353 | 353 | except: |
|
354 | 354 | color_switch_err('exception') |
|
355 | 355 | |
|
356 | 356 | # Set info (for 'object?') colors |
|
357 | 357 | if shell.color_info: |
|
358 | 358 | try: |
|
359 | 359 | shell.inspector.set_active_scheme(new_scheme) |
|
360 | 360 | except: |
|
361 | 361 | color_switch_err('object inspector') |
|
362 | 362 | else: |
|
363 | 363 | shell.inspector.set_active_scheme('NoColor') |
|
364 | 364 | |
|
365 | 365 | @line_magic |
|
366 | 366 | def xmode(self, parameter_s=''): |
|
367 | 367 | """Switch modes for the exception handlers. |
|
368 | 368 | |
|
369 | 369 | Valid modes: Plain, Context, Verbose, and Minimal. |
|
370 | 370 | |
|
371 | 371 | If called without arguments, acts as a toggle. |
|
372 | 372 | |
|
373 | 373 | When in verbose mode the value `--show` (and `--hide`) |
|
374 | 374 | will respectively show (or hide) frames with ``__tracebackhide__ = |
|
375 | 375 | True`` value set. |
|
376 | 376 | """ |
|
377 | 377 | |
|
378 | 378 | def xmode_switch_err(name): |
|
379 | 379 | warn('Error changing %s exception modes.\n%s' % |
|
380 | 380 | (name,sys.exc_info()[1])) |
|
381 | 381 | |
|
382 | 382 | shell = self.shell |
|
383 | 383 | if parameter_s.strip() == "--show": |
|
384 | 384 | shell.InteractiveTB.skip_hidden = False |
|
385 | 385 | return |
|
386 | 386 | if parameter_s.strip() == "--hide": |
|
387 | 387 | shell.InteractiveTB.skip_hidden = True |
|
388 | 388 | return |
|
389 | 389 | |
|
390 | 390 | new_mode = parameter_s.strip().capitalize() |
|
391 | 391 | try: |
|
392 | 392 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
393 | 393 | print('Exception reporting mode:',shell.InteractiveTB.mode) |
|
394 | 394 | except: |
|
395 | 395 | xmode_switch_err('user') |
|
396 | 396 | |
|
397 | 397 | @line_magic |
|
398 | 398 | def quickref(self, arg): |
|
399 | 399 | """ Show a quick reference sheet """ |
|
400 | 400 | from IPython.core.usage import quick_reference |
|
401 | 401 | qr = quick_reference + self._magic_docs(brief=True) |
|
402 | 402 | page.page(qr) |
|
403 | 403 | |
|
404 | 404 | @line_magic |
|
405 | 405 | def doctest_mode(self, parameter_s=''): |
|
406 | 406 | """Toggle doctest mode on and off. |
|
407 | 407 | |
|
408 | 408 | This mode is intended to make IPython behave as much as possible like a |
|
409 | 409 | plain Python shell, from the perspective of how its prompts, exceptions |
|
410 | 410 | and output look. This makes it easy to copy and paste parts of a |
|
411 | 411 | session into doctests. It does so by: |
|
412 | 412 | |
|
413 | 413 | - Changing the prompts to the classic ``>>>`` ones. |
|
414 | 414 | - Changing the exception reporting mode to 'Plain'. |
|
415 | 415 | - Disabling pretty-printing of output. |
|
416 | 416 | |
|
417 | 417 | Note that IPython also supports the pasting of code snippets that have |
|
418 | 418 | leading '>>>' and '...' prompts in them. This means that you can paste |
|
419 | 419 | doctests from files or docstrings (even if they have leading |
|
420 | 420 | whitespace), and the code will execute correctly. You can then use |
|
421 | 421 | '%history -t' to see the translated history; this will give you the |
|
422 | 422 | input after removal of all the leading prompts and whitespace, which |
|
423 | 423 | can be pasted back into an editor. |
|
424 | 424 | |
|
425 | 425 | With these features, you can switch into this mode easily whenever you |
|
426 | 426 | need to do testing and changes to doctests, without having to leave |
|
427 | 427 | your existing IPython session. |
|
428 | 428 | """ |
|
429 | 429 | |
|
430 | 430 | # Shorthands |
|
431 | 431 | shell = self.shell |
|
432 | 432 | meta = shell.meta |
|
433 | 433 | disp_formatter = self.shell.display_formatter |
|
434 | 434 | ptformatter = disp_formatter.formatters['text/plain'] |
|
435 | 435 | # dstore is a data store kept in the instance metadata bag to track any |
|
436 | 436 | # changes we make, so we can undo them later. |
|
437 | 437 | dstore = meta.setdefault('doctest_mode',Struct()) |
|
438 | 438 | save_dstore = dstore.setdefault |
|
439 | 439 | |
|
440 | 440 | # save a few values we'll need to recover later |
|
441 | 441 | mode = save_dstore('mode',False) |
|
442 | 442 | save_dstore('rc_pprint',ptformatter.pprint) |
|
443 | 443 | save_dstore('xmode',shell.InteractiveTB.mode) |
|
444 | 444 | save_dstore('rc_separate_out',shell.separate_out) |
|
445 | 445 | save_dstore('rc_separate_out2',shell.separate_out2) |
|
446 | 446 | save_dstore('rc_separate_in',shell.separate_in) |
|
447 | 447 | save_dstore('rc_active_types',disp_formatter.active_types) |
|
448 | 448 | |
|
449 | 449 | if not mode: |
|
450 | 450 | # turn on |
|
451 | 451 | |
|
452 | 452 | # Prompt separators like plain python |
|
453 | 453 | shell.separate_in = '' |
|
454 | 454 | shell.separate_out = '' |
|
455 | 455 | shell.separate_out2 = '' |
|
456 | 456 | |
|
457 | 457 | |
|
458 | 458 | ptformatter.pprint = False |
|
459 | 459 | disp_formatter.active_types = ['text/plain'] |
|
460 | 460 | |
|
461 | 461 | shell.magic('xmode Plain') |
|
462 | 462 | else: |
|
463 | 463 | # turn off |
|
464 | 464 | shell.separate_in = dstore.rc_separate_in |
|
465 | 465 | |
|
466 | 466 | shell.separate_out = dstore.rc_separate_out |
|
467 | 467 | shell.separate_out2 = dstore.rc_separate_out2 |
|
468 | 468 | |
|
469 | 469 | ptformatter.pprint = dstore.rc_pprint |
|
470 | 470 | disp_formatter.active_types = dstore.rc_active_types |
|
471 | 471 | |
|
472 | 472 | shell.magic('xmode ' + dstore.xmode) |
|
473 | 473 | |
|
474 | 474 | # mode here is the state before we switch; switch_doctest_mode takes |
|
475 | 475 | # the mode we're switching to. |
|
476 | 476 | shell.switch_doctest_mode(not mode) |
|
477 | 477 | |
|
478 | 478 | # Store new mode and inform |
|
479 | 479 | dstore.mode = bool(not mode) |
|
480 | 480 | mode_label = ['OFF','ON'][dstore.mode] |
|
481 | 481 | print('Doctest mode is:', mode_label) |
|
482 | 482 | |
|
483 | 483 | @line_magic |
|
484 | 484 | def gui(self, parameter_s=''): |
|
485 | 485 | """Enable or disable IPython GUI event loop integration. |
|
486 | 486 | |
|
487 | 487 | %gui [GUINAME] |
|
488 | 488 | |
|
489 | 489 | This magic replaces IPython's threaded shells that were activated |
|
490 | 490 | using the (pylab/wthread/etc.) command line flags. GUI toolkits |
|
491 | 491 | can now be enabled at runtime and keyboard |
|
492 | 492 | interrupts should work without any problems. The following toolkits |
|
493 | 493 | are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX):: |
|
494 | 494 | |
|
495 | 495 | %gui wx # enable wxPython event loop integration |
|
496 |
%gui qt |
|
|
497 | %gui qt5 # enable PyQt5 event loop integration | |
|
496 | %gui qt # enable PyQt/PySide event loop integration | |
|
497 | # with the latest version available. | |
|
498 | %gui qt6 # enable PyQt6/PySide6 event loop integration | |
|
499 | %gui qt5 # enable PyQt5/PySide2 event loop integration | |
|
498 | 500 | %gui gtk # enable PyGTK event loop integration |
|
499 | 501 | %gui gtk3 # enable Gtk3 event loop integration |
|
500 | 502 | %gui gtk4 # enable Gtk4 event loop integration |
|
501 | 503 | %gui tk # enable Tk event loop integration |
|
502 | 504 | %gui osx # enable Cocoa event loop integration |
|
503 | 505 | # (requires %matplotlib 1.1) |
|
504 | 506 | %gui # disable all event loop integration |
|
505 | 507 | |
|
506 | 508 | WARNING: after any of these has been called you can simply create |
|
507 | 509 | an application object, but DO NOT start the event loop yourself, as |
|
508 | 510 | we have already handled that. |
|
509 | 511 | """ |
|
510 | 512 | opts, arg = self.parse_options(parameter_s, '') |
|
511 | 513 | if arg=='': arg = None |
|
512 | 514 | try: |
|
513 | 515 | return self.shell.enable_gui(arg) |
|
514 | 516 | except Exception as e: |
|
515 | 517 | # print simple error message, rather than traceback if we can't |
|
516 | 518 | # hook up the GUI |
|
517 | 519 | error(str(e)) |
|
518 | 520 | |
|
519 | 521 | @skip_doctest |
|
520 | 522 | @line_magic |
|
521 | 523 | def precision(self, s=''): |
|
522 | 524 | """Set floating point precision for pretty printing. |
|
523 | 525 | |
|
524 | 526 | Can set either integer precision or a format string. |
|
525 | 527 | |
|
526 | 528 | If numpy has been imported and precision is an int, |
|
527 | 529 | numpy display precision will also be set, via ``numpy.set_printoptions``. |
|
528 | 530 | |
|
529 | 531 | If no argument is given, defaults will be restored. |
|
530 | 532 | |
|
531 | 533 | Examples |
|
532 | 534 | -------- |
|
533 | 535 | :: |
|
534 | 536 | |
|
535 | 537 | In [1]: from math import pi |
|
536 | 538 | |
|
537 | 539 | In [2]: %precision 3 |
|
538 | 540 | Out[2]: u'%.3f' |
|
539 | 541 | |
|
540 | 542 | In [3]: pi |
|
541 | 543 | Out[3]: 3.142 |
|
542 | 544 | |
|
543 | 545 | In [4]: %precision %i |
|
544 | 546 | Out[4]: u'%i' |
|
545 | 547 | |
|
546 | 548 | In [5]: pi |
|
547 | 549 | Out[5]: 3 |
|
548 | 550 | |
|
549 | 551 | In [6]: %precision %e |
|
550 | 552 | Out[6]: u'%e' |
|
551 | 553 | |
|
552 | 554 | In [7]: pi**10 |
|
553 | 555 | Out[7]: 9.364805e+04 |
|
554 | 556 | |
|
555 | 557 | In [8]: %precision |
|
556 | 558 | Out[8]: u'%r' |
|
557 | 559 | |
|
558 | 560 | In [9]: pi**10 |
|
559 | 561 | Out[9]: 93648.047476082982 |
|
560 | 562 | """ |
|
561 | 563 | ptformatter = self.shell.display_formatter.formatters['text/plain'] |
|
562 | 564 | ptformatter.float_precision = s |
|
563 | 565 | return ptformatter.float_format |
|
564 | 566 | |
|
565 | 567 | @magic_arguments.magic_arguments() |
|
566 | 568 | @magic_arguments.argument( |
|
567 | 569 | 'filename', type=str, |
|
568 | 570 | help='Notebook name or filename' |
|
569 | 571 | ) |
|
570 | 572 | @line_magic |
|
571 | 573 | def notebook(self, s): |
|
572 | 574 | """Export and convert IPython notebooks. |
|
573 | 575 | |
|
574 | 576 | This function can export the current IPython history to a notebook file. |
|
575 | 577 | For example, to export the history to "foo.ipynb" do "%notebook foo.ipynb". |
|
576 | 578 | """ |
|
577 | 579 | args = magic_arguments.parse_argstring(self.notebook, s) |
|
578 | 580 | outfname = os.path.expanduser(args.filename) |
|
579 | 581 | |
|
580 | 582 | from nbformat import write, v4 |
|
581 | 583 | |
|
582 | 584 | cells = [] |
|
583 | 585 | hist = list(self.shell.history_manager.get_range()) |
|
584 | 586 | if(len(hist)<=1): |
|
585 | 587 | raise ValueError('History is empty, cannot export') |
|
586 | 588 | for session, execution_count, source in hist[:-1]: |
|
587 | 589 | cells.append(v4.new_code_cell( |
|
588 | 590 | execution_count=execution_count, |
|
589 | 591 | source=source |
|
590 | 592 | )) |
|
591 | 593 | nb = v4.new_notebook(cells=cells) |
|
592 | 594 | with io.open(outfname, "w", encoding="utf-8") as f: |
|
593 | 595 | write(nb, f, version=4) |
|
594 | 596 | |
|
595 | 597 | @magics_class |
|
596 | 598 | class AsyncMagics(BasicMagics): |
|
597 | 599 | |
|
598 | 600 | @line_magic |
|
599 | 601 | def autoawait(self, parameter_s): |
|
600 | 602 | """ |
|
601 | 603 | Allow to change the status of the autoawait option. |
|
602 | 604 | |
|
603 | 605 | This allow you to set a specific asynchronous code runner. |
|
604 | 606 | |
|
605 | 607 | If no value is passed, print the currently used asynchronous integration |
|
606 | 608 | and whether it is activated. |
|
607 | 609 | |
|
608 | 610 | It can take a number of value evaluated in the following order: |
|
609 | 611 | |
|
610 | 612 | - False/false/off deactivate autoawait integration |
|
611 | 613 | - True/true/on activate autoawait integration using configured default |
|
612 | 614 | loop |
|
613 | 615 | - asyncio/curio/trio activate autoawait integration and use integration |
|
614 | 616 | with said library. |
|
615 | 617 | |
|
616 | 618 | - `sync` turn on the pseudo-sync integration (mostly used for |
|
617 | 619 | `IPython.embed()` which does not run IPython with a real eventloop and |
|
618 | 620 | deactivate running asynchronous code. Turning on Asynchronous code with |
|
619 | 621 | the pseudo sync loop is undefined behavior and may lead IPython to crash. |
|
620 | 622 | |
|
621 | 623 | If the passed parameter does not match any of the above and is a python |
|
622 | 624 | identifier, get said object from user namespace and set it as the |
|
623 | 625 | runner, and activate autoawait. |
|
624 | 626 | |
|
625 | 627 | If the object is a fully qualified object name, attempt to import it and |
|
626 | 628 | set it as the runner, and activate autoawait. |
|
627 | 629 | |
|
628 | 630 | The exact behavior of autoawait is experimental and subject to change |
|
629 | 631 | across version of IPython and Python. |
|
630 | 632 | """ |
|
631 | 633 | |
|
632 | 634 | param = parameter_s.strip() |
|
633 | 635 | d = {True: "on", False: "off"} |
|
634 | 636 | |
|
635 | 637 | if not param: |
|
636 | 638 | print("IPython autoawait is `{}`, and set to use `{}`".format( |
|
637 | 639 | d[self.shell.autoawait], |
|
638 | 640 | self.shell.loop_runner |
|
639 | 641 | )) |
|
640 | 642 | return None |
|
641 | 643 | |
|
642 | 644 | if param.lower() in ('false', 'off'): |
|
643 | 645 | self.shell.autoawait = False |
|
644 | 646 | return None |
|
645 | 647 | if param.lower() in ('true', 'on'): |
|
646 | 648 | self.shell.autoawait = True |
|
647 | 649 | return None |
|
648 | 650 | |
|
649 | 651 | if param in self.shell.loop_runner_map: |
|
650 | 652 | self.shell.loop_runner, self.shell.autoawait = self.shell.loop_runner_map[param] |
|
651 | 653 | return None |
|
652 | 654 | |
|
653 | 655 | if param in self.shell.user_ns : |
|
654 | 656 | self.shell.loop_runner = self.shell.user_ns[param] |
|
655 | 657 | self.shell.autoawait = True |
|
656 | 658 | return None |
|
657 | 659 | |
|
658 | 660 | runner = import_item(param) |
|
659 | 661 | |
|
660 | 662 | self.shell.loop_runner = runner |
|
661 | 663 | self.shell.autoawait = True |
@@ -1,131 +1,124 b'' | |||
|
1 | 1 | """ Import Qt in a manner suitable for an IPython kernel. |
|
2 | 2 | |
|
3 | 3 | This is the import used for the `gui=qt` or `matplotlib=qt` initialization. |
|
4 | 4 | |
|
5 | 5 | Import Priority: |
|
6 | 6 | |
|
7 | 7 | if Qt has been imported anywhere else: |
|
8 | 8 | use that |
|
9 | 9 | |
|
10 | 10 | if matplotlib has been imported and doesn't support v2 (<= 1.0.1): |
|
11 | 11 | use PyQt4 @v1 |
|
12 | 12 | |
|
13 | 13 | Next, ask QT_API env variable |
|
14 | 14 | |
|
15 | 15 | if QT_API not set: |
|
16 | 16 | ask matplotlib what it's using. If Qt4Agg or Qt5Agg, then use the |
|
17 | 17 | version matplotlib is configured with |
|
18 | 18 | |
|
19 | 19 | else: (matplotlib said nothing) |
|
20 | 20 | # this is the default path - nobody told us anything |
|
21 | 21 | try in this order: |
|
22 | 22 | PyQt default version, PySide, PyQt5 |
|
23 | 23 | else: |
|
24 | 24 | use what QT_API says |
|
25 | 25 | |
|
26 | 26 | Note that %gui's implementation will always set a `QT_API`, see |
|
27 | 27 | `IPython.terminal.pt_inputhooks.get_inputhook_name_and_func` |
|
28 | 28 | |
|
29 | 29 | """ |
|
30 | 30 | # NOTE: This is no longer an external, third-party module, and should be |
|
31 | 31 | # considered part of IPython. For compatibility however, it is being kept in |
|
32 | 32 | # IPython/external. |
|
33 | 33 | |
|
34 | 34 | import os |
|
35 | 35 | import sys |
|
36 | 36 | |
|
37 | 37 | from IPython.external.qt_loaders import ( |
|
38 | 38 | load_qt, |
|
39 | 39 | loaded_api, |
|
40 | 40 | enum_factory, |
|
41 | 41 | # QT6 |
|
42 | 42 | QT_API_PYQT6, |
|
43 | 43 | QT_API_PYSIDE6, |
|
44 | 44 | # QT5 |
|
45 | 45 | QT_API_PYQT5, |
|
46 | 46 | QT_API_PYSIDE2, |
|
47 | 47 | # QT4 |
|
48 | QT_API_PYQTv1, | |
|
49 | 48 | QT_API_PYQT, |
|
50 | 49 | QT_API_PYSIDE, |
|
51 | 50 | # default |
|
52 | 51 | QT_API_PYQT_DEFAULT, |
|
53 | 52 | ) |
|
54 | 53 | |
|
55 | 54 | _qt_apis = ( |
|
56 | 55 | # QT6 |
|
57 | 56 | QT_API_PYQT6, |
|
58 | 57 | QT_API_PYSIDE6, |
|
59 | 58 | # QT5 |
|
60 | 59 | QT_API_PYQT5, |
|
61 | 60 | QT_API_PYSIDE2, |
|
62 | # QT4 | |
|
63 | QT_API_PYQTv1, | |
|
64 | QT_API_PYQT, | |
|
65 | QT_API_PYSIDE, | |
|
66 | 61 | # default |
|
67 | 62 | QT_API_PYQT_DEFAULT, |
|
68 | 63 | ) |
|
69 | 64 | |
|
70 | 65 | |
|
71 | 66 | def matplotlib_options(mpl): |
|
72 | 67 | """Constraints placed on an imported matplotlib.""" |
|
73 | 68 | if mpl is None: |
|
74 | 69 | return |
|
75 | 70 | backend = mpl.rcParams.get('backend', None) |
|
76 | 71 | if backend == 'Qt4Agg': |
|
77 | 72 | mpqt = mpl.rcParams.get('backend.qt4', None) |
|
78 | 73 | if mpqt is None: |
|
79 | 74 | return None |
|
80 | 75 | if mpqt.lower() == 'pyside': |
|
81 | 76 | return [QT_API_PYSIDE] |
|
82 | 77 | elif mpqt.lower() == 'pyqt4': |
|
83 | 78 | return [QT_API_PYQT_DEFAULT] |
|
84 | 79 | elif mpqt.lower() == 'pyqt4v2': |
|
85 | 80 | return [QT_API_PYQT] |
|
86 | 81 | raise ImportError("unhandled value for backend.qt4 from matplotlib: %r" % |
|
87 | 82 | mpqt) |
|
88 | 83 | elif backend == 'Qt5Agg': |
|
89 | 84 | mpqt = mpl.rcParams.get('backend.qt5', None) |
|
90 | 85 | if mpqt is None: |
|
91 | 86 | return None |
|
92 | 87 | if mpqt.lower() == 'pyqt5': |
|
93 | 88 | return [QT_API_PYQT5] |
|
94 | 89 | raise ImportError("unhandled value for backend.qt5 from matplotlib: %r" % |
|
95 | 90 | mpqt) |
|
96 | 91 | |
|
97 | 92 | def get_options(): |
|
98 | 93 | """Return a list of acceptable QT APIs, in decreasing order of preference.""" |
|
99 | 94 | #already imported Qt somewhere. Use that |
|
100 | 95 | loaded = loaded_api() |
|
101 | 96 | if loaded is not None: |
|
102 | 97 | return [loaded] |
|
103 | 98 | |
|
104 | 99 | mpl = sys.modules.get("matplotlib", None) |
|
105 | 100 | |
|
106 | 101 | if mpl is not None and tuple(mpl.__version__.split(".")) < ("1", "0", "2"): |
|
107 | 102 | # 1.0.1 only supports PyQt4 v1 |
|
108 | 103 | return [QT_API_PYQT_DEFAULT] |
|
109 | 104 | |
|
110 | 105 | qt_api = os.environ.get('QT_API', None) |
|
111 | 106 | if qt_api is None: |
|
112 | 107 | #no ETS variable. Ask mpl, then use default fallback path |
|
113 | 108 | return matplotlib_options(mpl) or [ |
|
114 | 109 | QT_API_PYQT_DEFAULT, |
|
115 | 110 | QT_API_PYQT6, |
|
116 | 111 | QT_API_PYSIDE6, |
|
117 | 112 | QT_API_PYQT5, |
|
118 | 113 | QT_API_PYSIDE2, |
|
119 | QT_API_PYQT, | |
|
120 | QT_API_PYSIDE, | |
|
121 | 114 | ] |
|
122 | 115 | elif qt_api not in _qt_apis: |
|
123 | 116 | raise RuntimeError("Invalid Qt API %r, valid values are: %r" % |
|
124 | 117 | (qt_api, ', '.join(_qt_apis))) |
|
125 | 118 | else: |
|
126 | 119 | return [qt_api] |
|
127 | 120 | |
|
128 | 121 | |
|
129 | 122 | api_opts = get_options() |
|
130 | 123 | QtCore, QtGui, QtSvg, QT_API = load_qt(api_opts) |
|
131 | 124 | enum_helper = enum_factory(QT_API, QtCore) |
@@ -1,408 +1,405 b'' | |||
|
1 | 1 | """ |
|
2 | 2 | This module contains factory functions that attempt |
|
3 | 3 | to return Qt submodules from the various python Qt bindings. |
|
4 | 4 | |
|
5 | 5 | It also protects against double-importing Qt with different |
|
6 | 6 | bindings, which is unstable and likely to crash |
|
7 | 7 | |
|
8 | 8 | This is used primarily by qt and qt_for_kernel, and shouldn't |
|
9 | 9 | be accessed directly from the outside |
|
10 | 10 | """ |
|
11 | 11 | import importlib.abc |
|
12 | 12 | import sys |
|
13 | 13 | import types |
|
14 | 14 | from functools import partial, lru_cache |
|
15 | 15 | import operator |
|
16 | 16 | |
|
17 | 17 | # ### Available APIs. |
|
18 | 18 | # Qt6 |
|
19 | 19 | QT_API_PYQT6 = "pyqt6" |
|
20 | 20 | QT_API_PYSIDE6 = "pyside6" |
|
21 | 21 | |
|
22 | 22 | # Qt5 |
|
23 | 23 | QT_API_PYQT5 = 'pyqt5' |
|
24 | 24 | QT_API_PYSIDE2 = 'pyside2' |
|
25 | 25 | |
|
26 | 26 | # Qt4 |
|
27 | # NOTE: Here for legacy matplotlib compatibility, but not really supported on the IPython side. | |
|
27 | 28 | QT_API_PYQT = "pyqt" # Force version 2 |
|
28 | 29 | QT_API_PYQTv1 = "pyqtv1" # Force version 2 |
|
29 | 30 | QT_API_PYSIDE = "pyside" |
|
30 | 31 | |
|
31 | 32 | QT_API_PYQT_DEFAULT = "pyqtdefault" # use system default for version 1 vs. 2 |
|
32 | 33 | |
|
33 | 34 | api_to_module = { |
|
34 | 35 | # Qt6 |
|
35 | 36 | QT_API_PYQT6: "PyQt6", |
|
36 | 37 | QT_API_PYSIDE6: "PySide6", |
|
37 | 38 | # Qt5 |
|
38 | 39 | QT_API_PYQT5: "PyQt5", |
|
39 | 40 | QT_API_PYSIDE2: "PySide2", |
|
40 | 41 | # Qt4 |
|
41 | 42 | QT_API_PYSIDE: "PySide", |
|
42 | 43 | QT_API_PYQT: "PyQt4", |
|
43 | 44 | QT_API_PYQTv1: "PyQt4", |
|
44 | 45 | # default |
|
45 | 46 | QT_API_PYQT_DEFAULT: "PyQt6", |
|
46 | 47 | } |
|
47 | 48 | |
|
48 | 49 | |
|
49 | 50 | class ImportDenier(importlib.abc.MetaPathFinder): |
|
50 | 51 | """Import Hook that will guard against bad Qt imports |
|
51 | 52 | once IPython commits to a specific binding |
|
52 | 53 | """ |
|
53 | 54 | |
|
54 | 55 | def __init__(self): |
|
55 | 56 | self.__forbidden = set() |
|
56 | 57 | |
|
57 | 58 | def forbid(self, module_name): |
|
58 | 59 | sys.modules.pop(module_name, None) |
|
59 | 60 | self.__forbidden.add(module_name) |
|
60 | 61 | |
|
61 | 62 | def find_spec(self, fullname, path, target=None): |
|
62 | 63 | if path: |
|
63 | 64 | return |
|
64 | 65 | if fullname in self.__forbidden: |
|
65 | 66 | raise ImportError( |
|
66 | 67 | """ |
|
67 | 68 | Importing %s disabled by IPython, which has |
|
68 | 69 | already imported an Incompatible QT Binding: %s |
|
69 | 70 | """ |
|
70 | 71 | % (fullname, loaded_api()) |
|
71 | 72 | ) |
|
72 | 73 | |
|
73 | 74 | |
|
74 | 75 | ID = ImportDenier() |
|
75 | 76 | sys.meta_path.insert(0, ID) |
|
76 | 77 | |
|
77 | 78 | |
|
78 | 79 | def commit_api(api): |
|
79 | 80 | """Commit to a particular API, and trigger ImportErrors on subsequent |
|
80 | 81 | dangerous imports""" |
|
81 | 82 | modules = set(api_to_module.values()) |
|
82 | 83 | |
|
83 | 84 | modules.remove(api_to_module[api]) |
|
84 | 85 | for mod in modules: |
|
85 | 86 | ID.forbid(mod) |
|
86 | 87 | |
|
87 | 88 | |
|
88 | 89 | def loaded_api(): |
|
89 | 90 | """Return which API is loaded, if any |
|
90 | 91 | |
|
91 | 92 | If this returns anything besides None, |
|
92 | 93 | importing any other Qt binding is unsafe. |
|
93 | 94 | |
|
94 | 95 | Returns |
|
95 | 96 | ------- |
|
96 | 97 | None, 'pyside6', 'pyqt6', 'pyside2', 'pyside', 'pyqt', 'pyqt5', 'pyqtv1' |
|
97 | 98 | """ |
|
98 | 99 | if sys.modules.get("PyQt6.QtCore"): |
|
99 | 100 | return QT_API_PYQT6 |
|
100 | 101 | elif sys.modules.get("PySide6.QtCore"): |
|
101 | 102 | return QT_API_PYSIDE6 |
|
102 | 103 | elif sys.modules.get("PyQt5.QtCore"): |
|
103 | 104 | return QT_API_PYQT5 |
|
104 | 105 | elif sys.modules.get("PySide2.QtCore"): |
|
105 | 106 | return QT_API_PYSIDE2 |
|
106 | 107 | elif sys.modules.get("PyQt4.QtCore"): |
|
107 | 108 | if qtapi_version() == 2: |
|
108 | 109 | return QT_API_PYQT |
|
109 | 110 | else: |
|
110 | 111 | return QT_API_PYQTv1 |
|
111 | 112 | elif sys.modules.get("PySide.QtCore"): |
|
112 | 113 | return QT_API_PYSIDE |
|
113 | 114 | |
|
114 | 115 | return None |
|
115 | 116 | |
|
116 | 117 | |
|
117 | 118 | def has_binding(api): |
|
118 | 119 | """Safely check for PyQt4/5, PySide or PySide2, without importing submodules |
|
119 | 120 | |
|
120 | 121 | Parameters |
|
121 | 122 | ---------- |
|
122 | 123 | api : str [ 'pyqtv1' | 'pyqt' | 'pyqt5' | 'pyside' | 'pyside2' | 'pyqtdefault'] |
|
123 | 124 | Which module to check for |
|
124 | 125 | |
|
125 | 126 | Returns |
|
126 | 127 | ------- |
|
127 | 128 | True if the relevant module appears to be importable |
|
128 | 129 | """ |
|
129 | 130 | module_name = api_to_module[api] |
|
130 | 131 | from importlib.util import find_spec |
|
131 | 132 | |
|
132 | 133 | required = ['QtCore', 'QtGui', 'QtSvg'] |
|
133 | 134 | if api in (QT_API_PYQT5, QT_API_PYSIDE2, QT_API_PYQT6, QT_API_PYSIDE6): |
|
134 | 135 | # QT5 requires QtWidgets too |
|
135 | 136 | required.append('QtWidgets') |
|
136 | 137 | |
|
137 | 138 | for submod in required: |
|
138 | 139 | try: |
|
139 | 140 | spec = find_spec('%s.%s' % (module_name, submod)) |
|
140 | 141 | except ImportError: |
|
141 | 142 | # Package (e.g. PyQt5) not found |
|
142 | 143 | return False |
|
143 | 144 | else: |
|
144 | 145 | if spec is None: |
|
145 | 146 | # Submodule (e.g. PyQt5.QtCore) not found |
|
146 | 147 | return False |
|
147 | 148 | |
|
148 | 149 | if api == QT_API_PYSIDE: |
|
149 | 150 | # We can also safely check PySide version |
|
150 | 151 | import PySide |
|
151 | 152 | |
|
152 | 153 | return PySide.__version_info__ >= (1, 0, 3) |
|
153 | 154 | |
|
154 | 155 | return True |
|
155 | 156 | |
|
156 | 157 | |
|
157 | 158 | def qtapi_version(): |
|
158 | 159 | """Return which QString API has been set, if any |
|
159 | 160 | |
|
160 | 161 | Returns |
|
161 | 162 | ------- |
|
162 | 163 | The QString API version (1 or 2), or None if not set |
|
163 | 164 | """ |
|
164 | 165 | try: |
|
165 | 166 | import sip |
|
166 | 167 | except ImportError: |
|
167 | 168 | # as of PyQt5 5.11, sip is no longer available as a top-level |
|
168 | 169 | # module and needs to be imported from the PyQt5 namespace |
|
169 | 170 | try: |
|
170 | 171 | from PyQt5 import sip |
|
171 | 172 | except ImportError: |
|
172 | 173 | return |
|
173 | 174 | try: |
|
174 | 175 | return sip.getapi('QString') |
|
175 | 176 | except ValueError: |
|
176 | 177 | return |
|
177 | 178 | |
|
178 | 179 | |
|
179 | 180 | def can_import(api): |
|
180 | 181 | """Safely query whether an API is importable, without importing it""" |
|
181 | 182 | if not has_binding(api): |
|
182 | 183 | return False |
|
183 | 184 | |
|
184 | 185 | current = loaded_api() |
|
185 | 186 | if api == QT_API_PYQT_DEFAULT: |
|
186 | 187 | return current in [QT_API_PYQT6, None] |
|
187 | 188 | else: |
|
188 | 189 | return current in [api, None] |
|
189 | 190 | |
|
190 | 191 | |
|
191 | 192 | def import_pyqt4(version=2): |
|
192 | 193 | """ |
|
193 | 194 | Import PyQt4 |
|
194 | 195 | |
|
195 | 196 | Parameters |
|
196 | 197 | ---------- |
|
197 | 198 | version : 1, 2, or None |
|
198 | 199 | Which QString/QVariant API to use. Set to None to use the system |
|
199 | 200 | default |
|
200 | 201 | ImportErrors raised within this function are non-recoverable |
|
201 | 202 | """ |
|
202 | 203 | # The new-style string API (version=2) automatically |
|
203 | 204 | # converts QStrings to Unicode Python strings. Also, automatically unpacks |
|
204 | 205 | # QVariants to their underlying objects. |
|
205 | 206 | import sip |
|
206 | 207 | |
|
207 | 208 | if version is not None: |
|
208 | 209 | sip.setapi('QString', version) |
|
209 | 210 | sip.setapi('QVariant', version) |
|
210 | 211 | |
|
211 | 212 | from PyQt4 import QtGui, QtCore, QtSvg |
|
212 | 213 | |
|
213 | 214 | if QtCore.PYQT_VERSION < 0x040700: |
|
214 | 215 | raise ImportError("IPython requires PyQt4 >= 4.7, found %s" % |
|
215 | 216 | QtCore.PYQT_VERSION_STR) |
|
216 | 217 | |
|
217 | 218 | # Alias PyQt-specific functions for PySide compatibility. |
|
218 | 219 | QtCore.Signal = QtCore.pyqtSignal |
|
219 | 220 | QtCore.Slot = QtCore.pyqtSlot |
|
220 | 221 | |
|
221 | 222 | # query for the API version (in case version == None) |
|
222 | 223 | version = sip.getapi('QString') |
|
223 | 224 | api = QT_API_PYQTv1 if version == 1 else QT_API_PYQT |
|
224 | 225 | return QtCore, QtGui, QtSvg, api |
|
225 | 226 | |
|
226 | 227 | |
|
227 | 228 | def import_pyqt5(): |
|
228 | 229 | """ |
|
229 | 230 | Import PyQt5 |
|
230 | 231 | |
|
231 | 232 | ImportErrors raised within this function are non-recoverable |
|
232 | 233 | """ |
|
233 | 234 | |
|
234 | 235 | from PyQt5 import QtCore, QtSvg, QtWidgets, QtGui |
|
235 | 236 | |
|
236 | 237 | # Alias PyQt-specific functions for PySide compatibility. |
|
237 | 238 | QtCore.Signal = QtCore.pyqtSignal |
|
238 | 239 | QtCore.Slot = QtCore.pyqtSlot |
|
239 | 240 | |
|
240 | 241 | # Join QtGui and QtWidgets for Qt4 compatibility. |
|
241 | 242 | QtGuiCompat = types.ModuleType('QtGuiCompat') |
|
242 | 243 | QtGuiCompat.__dict__.update(QtGui.__dict__) |
|
243 | 244 | QtGuiCompat.__dict__.update(QtWidgets.__dict__) |
|
244 | 245 | |
|
245 | 246 | api = QT_API_PYQT5 |
|
246 | 247 | return QtCore, QtGuiCompat, QtSvg, api |
|
247 | 248 | |
|
248 | 249 | |
|
249 | 250 | def import_pyqt6(): |
|
250 | 251 | """ |
|
251 | 252 | Import PyQt6 |
|
252 | 253 | |
|
253 | 254 | ImportErrors raised within this function are non-recoverable |
|
254 | 255 | """ |
|
255 | 256 | |
|
256 | 257 | from PyQt6 import QtCore, QtSvg, QtWidgets, QtGui |
|
257 | 258 | |
|
258 | 259 | # Alias PyQt-specific functions for PySide compatibility. |
|
259 | 260 | QtCore.Signal = QtCore.pyqtSignal |
|
260 | 261 | QtCore.Slot = QtCore.pyqtSlot |
|
261 | 262 | |
|
262 | 263 | # Join QtGui and QtWidgets for Qt4 compatibility. |
|
263 | 264 | QtGuiCompat = types.ModuleType("QtGuiCompat") |
|
264 | 265 | QtGuiCompat.__dict__.update(QtGui.__dict__) |
|
265 | 266 | QtGuiCompat.__dict__.update(QtWidgets.__dict__) |
|
266 | 267 | |
|
267 | 268 | api = QT_API_PYQT6 |
|
268 | 269 | return QtCore, QtGuiCompat, QtSvg, api |
|
269 | 270 | |
|
270 | 271 | |
|
271 | 272 | def import_pyside(): |
|
272 | 273 | """ |
|
273 | 274 | Import PySide |
|
274 | 275 | |
|
275 | 276 | ImportErrors raised within this function are non-recoverable |
|
276 | 277 | """ |
|
277 | 278 | from PySide import QtGui, QtCore, QtSvg |
|
278 | 279 | return QtCore, QtGui, QtSvg, QT_API_PYSIDE |
|
279 | 280 | |
|
280 | 281 | def import_pyside2(): |
|
281 | 282 | """ |
|
282 | 283 | Import PySide2 |
|
283 | 284 | |
|
284 | 285 | ImportErrors raised within this function are non-recoverable |
|
285 | 286 | """ |
|
286 | 287 | from PySide2 import QtGui, QtCore, QtSvg, QtWidgets, QtPrintSupport |
|
287 | 288 | |
|
288 | 289 | # Join QtGui and QtWidgets for Qt4 compatibility. |
|
289 | 290 | QtGuiCompat = types.ModuleType('QtGuiCompat') |
|
290 | 291 | QtGuiCompat.__dict__.update(QtGui.__dict__) |
|
291 | 292 | QtGuiCompat.__dict__.update(QtWidgets.__dict__) |
|
292 | 293 | QtGuiCompat.__dict__.update(QtPrintSupport.__dict__) |
|
293 | 294 | |
|
294 | 295 | return QtCore, QtGuiCompat, QtSvg, QT_API_PYSIDE2 |
|
295 | 296 | |
|
296 | 297 | |
|
297 | 298 | def import_pyside6(): |
|
298 | 299 | """ |
|
299 | 300 | Import PySide6 |
|
300 | 301 | |
|
301 | 302 | ImportErrors raised within this function are non-recoverable |
|
302 | 303 | """ |
|
303 | 304 | from PySide6 import QtGui, QtCore, QtSvg, QtWidgets, QtPrintSupport |
|
304 | 305 | |
|
305 | 306 | # Join QtGui and QtWidgets for Qt4 compatibility. |
|
306 | 307 | QtGuiCompat = types.ModuleType("QtGuiCompat") |
|
307 | 308 | QtGuiCompat.__dict__.update(QtGui.__dict__) |
|
308 | 309 | QtGuiCompat.__dict__.update(QtWidgets.__dict__) |
|
309 | 310 | QtGuiCompat.__dict__.update(QtPrintSupport.__dict__) |
|
310 | 311 | |
|
311 | 312 | return QtCore, QtGuiCompat, QtSvg, QT_API_PYSIDE6 |
|
312 | 313 | |
|
313 | 314 | |
|
314 | 315 | def load_qt(api_options): |
|
315 | 316 | """ |
|
316 | 317 | Attempt to import Qt, given a preference list |
|
317 | 318 | of permissible bindings |
|
318 | 319 | |
|
319 | 320 | It is safe to call this function multiple times. |
|
320 | 321 | |
|
321 | 322 | Parameters |
|
322 | 323 | ---------- |
|
323 | 324 | api_options : List of strings |
|
324 | 325 | The order of APIs to try. Valid items are 'pyside', 'pyside2', |
|
325 | 326 | 'pyqt', 'pyqt5', 'pyqtv1' and 'pyqtdefault' |
|
326 | 327 | |
|
327 | 328 | Returns |
|
328 | 329 | ------- |
|
329 | 330 | A tuple of QtCore, QtGui, QtSvg, QT_API |
|
330 | 331 | The first three are the Qt modules. The last is the |
|
331 | 332 | string indicating which module was loaded. |
|
332 | 333 | |
|
333 | 334 | Raises |
|
334 | 335 | ------ |
|
335 | 336 | ImportError, if it isn't possible to import any requested |
|
336 | 337 | bindings (either because they aren't installed, or because |
|
337 | 338 | an incompatible library has already been installed) |
|
338 | 339 | """ |
|
339 | 340 | loaders = { |
|
340 | 341 | # Qt6 |
|
341 | 342 | QT_API_PYQT6: import_pyqt6, |
|
342 | 343 | QT_API_PYSIDE6: import_pyside6, |
|
343 | 344 | # Qt5 |
|
344 | 345 | QT_API_PYQT5: import_pyqt5, |
|
345 | 346 | QT_API_PYSIDE2: import_pyside2, |
|
346 | 347 | # Qt4 |
|
347 | 348 | QT_API_PYSIDE: import_pyside, |
|
348 | 349 | QT_API_PYQT: import_pyqt4, |
|
349 | 350 | QT_API_PYQTv1: partial(import_pyqt4, version=1), |
|
350 | 351 | # default |
|
351 | 352 | QT_API_PYQT_DEFAULT: import_pyqt6, |
|
352 | 353 | } |
|
353 | 354 | |
|
354 | 355 | for api in api_options: |
|
355 | 356 | |
|
356 | 357 | if api not in loaders: |
|
357 | 358 | raise RuntimeError( |
|
358 | 359 | "Invalid Qt API %r, valid values are: %s" % |
|
359 | 360 | (api, ", ".join(["%r" % k for k in loaders.keys()]))) |
|
360 | 361 | |
|
361 | 362 | if not can_import(api): |
|
362 | 363 | continue |
|
363 | 364 | |
|
364 | 365 | #cannot safely recover from an ImportError during this |
|
365 | 366 | result = loaders[api]() |
|
366 | 367 | api = result[-1] # changed if api = QT_API_PYQT_DEFAULT |
|
367 | 368 | commit_api(api) |
|
368 | 369 | return result |
|
369 | 370 | else: |
|
370 | 371 | raise ImportError( |
|
371 | 372 | """ |
|
372 | 373 | Could not load requested Qt binding. Please ensure that |
|
373 | 374 | PyQt4 >= 4.7, PyQt5, PyQt6, PySide >= 1.0.3, PySide2, or |
|
374 | 375 | PySide6 is available, and only one is imported per session. |
|
375 | 376 | |
|
376 | 377 | Currently-imported Qt library: %r |
|
377 | PyQt4 available (requires QtCore, QtGui, QtSvg): %s | |
|
378 | 378 | PyQt5 available (requires QtCore, QtGui, QtSvg, QtWidgets): %s |
|
379 | 379 | PyQt6 available (requires QtCore, QtGui, QtSvg, QtWidgets): %s |
|
380 | PySide >= 1.0.3 installed: %s | |
|
381 | 380 | PySide2 installed: %s |
|
382 | 381 | PySide6 installed: %s |
|
383 | 382 | Tried to load: %r |
|
384 | 383 | """ |
|
385 | 384 | % ( |
|
386 | 385 | loaded_api(), |
|
387 | has_binding(QT_API_PYQT), | |
|
388 | 386 | has_binding(QT_API_PYQT5), |
|
389 | 387 | has_binding(QT_API_PYQT6), |
|
390 | has_binding(QT_API_PYSIDE), | |
|
391 | 388 | has_binding(QT_API_PYSIDE2), |
|
392 | 389 | has_binding(QT_API_PYSIDE6), |
|
393 | 390 | api_options, |
|
394 | 391 | ) |
|
395 | 392 | ) |
|
396 | 393 | |
|
397 | 394 | |
|
398 | 395 | def enum_factory(QT_API, QtCore): |
|
399 | 396 | """Construct an enum helper to account for PyQt5 <-> PyQt6 changes.""" |
|
400 | 397 | |
|
401 | 398 | @lru_cache(None) |
|
402 | 399 | def _enum(name): |
|
403 | 400 | # foo.bar.Enum.Entry (PyQt6) <=> foo.bar.Entry (non-PyQt6). |
|
404 | 401 | return operator.attrgetter( |
|
405 | 402 | name if QT_API == QT_API_PYQT6 else name.rpartition(".")[0] |
|
406 | 403 | )(sys.modules[QtCore.__package__]) |
|
407 | 404 | |
|
408 | 405 | return _enum |
@@ -1,155 +1,155 b'' | |||
|
1 | 1 | # coding: utf-8 |
|
2 | 2 | """ |
|
3 | 3 | Support for creating GUI apps and starting event loops. |
|
4 | 4 | |
|
5 | 5 | IPython's GUI integration allows interactive plotting and GUI usage in IPython |
|
6 | 6 | session. IPython has two different types of GUI integration: |
|
7 | 7 | |
|
8 | 8 | 1. The terminal based IPython supports GUI event loops through Python's |
|
9 | 9 | PyOS_InputHook. PyOS_InputHook is a hook that Python calls periodically |
|
10 | 10 | whenever raw_input is waiting for a user to type code. We implement GUI |
|
11 | 11 | support in the terminal by setting PyOS_InputHook to a function that |
|
12 | 12 | iterates the event loop for a short while. It is important to note that |
|
13 | 13 | in this situation, the real GUI event loop is NOT run in the normal |
|
14 | 14 | manner, so you can't use the normal means to detect that it is running. |
|
15 | 15 | 2. In the two process IPython kernel/frontend, the GUI event loop is run in |
|
16 | 16 | the kernel. In this case, the event loop is run in the normal manner by |
|
17 | 17 | calling the function or method of the GUI toolkit that starts the event |
|
18 | 18 | loop. |
|
19 | 19 | |
|
20 | 20 | In addition to starting the GUI event loops in one of these two ways, IPython |
|
21 | 21 | will *always* create an appropriate GUI application object when GUi |
|
22 | 22 | integration is enabled. |
|
23 | 23 | |
|
24 | 24 | If you want your GUI apps to run in IPython you need to do two things: |
|
25 | 25 | |
|
26 | 26 | 1. Test to see if there is already an existing main application object. If |
|
27 | 27 | there is, you should use it. If there is not an existing application object |
|
28 | 28 | you should create one. |
|
29 | 29 | 2. Test to see if the GUI event loop is running. If it is, you should not |
|
30 | 30 | start it. If the event loop is not running you may start it. |
|
31 | 31 | |
|
32 | 32 | This module contains functions for each toolkit that perform these things |
|
33 | 33 | in a consistent manner. Because of how PyOS_InputHook runs the event loop |
|
34 | 34 | you cannot detect if the event loop is running using the traditional calls |
|
35 | 35 | (such as ``wx.GetApp.IsMainLoopRunning()`` in wxPython). If PyOS_InputHook is |
|
36 | 36 | set These methods will return a false negative. That is, they will say the |
|
37 | 37 | event loop is not running, when is actually is. To work around this limitation |
|
38 | 38 | we proposed the following informal protocol: |
|
39 | 39 | |
|
40 | 40 | * Whenever someone starts the event loop, they *must* set the ``_in_event_loop`` |
|
41 | 41 | attribute of the main application object to ``True``. This should be done |
|
42 | 42 | regardless of how the event loop is actually run. |
|
43 | 43 | * Whenever someone stops the event loop, they *must* set the ``_in_event_loop`` |
|
44 | 44 | attribute of the main application object to ``False``. |
|
45 | 45 | * If you want to see if the event loop is running, you *must* use ``hasattr`` |
|
46 | 46 | to see if ``_in_event_loop`` attribute has been set. If it is set, you |
|
47 | 47 | *must* use its value. If it has not been set, you can query the toolkit |
|
48 | 48 | in the normal manner. |
|
49 | 49 | * If you want GUI support and no one else has created an application or |
|
50 | 50 | started the event loop you *must* do this. We don't want projects to |
|
51 | 51 | attempt to defer these things to someone else if they themselves need it. |
|
52 | 52 | |
|
53 | 53 | The functions below implement this logic for each GUI toolkit. If you need |
|
54 | 54 | to create custom application subclasses, you will likely have to modify this |
|
55 | 55 | code for your own purposes. This code can be copied into your own project |
|
56 | 56 | so you don't have to depend on IPython. |
|
57 | 57 | |
|
58 | 58 | """ |
|
59 | 59 | |
|
60 | 60 | # Copyright (c) IPython Development Team. |
|
61 | 61 | # Distributed under the terms of the Modified BSD License. |
|
62 | 62 | |
|
63 | 63 | from IPython.core.getipython import get_ipython |
|
64 | 64 | |
|
65 | 65 | #----------------------------------------------------------------------------- |
|
66 | 66 | # wx |
|
67 | 67 | #----------------------------------------------------------------------------- |
|
68 | 68 | |
|
69 | 69 | def get_app_wx(*args, **kwargs): |
|
70 | 70 | """Create a new wx app or return an exiting one.""" |
|
71 | 71 | import wx |
|
72 | 72 | app = wx.GetApp() |
|
73 | 73 | if app is None: |
|
74 | 74 | if 'redirect' not in kwargs: |
|
75 | 75 | kwargs['redirect'] = False |
|
76 | 76 | app = wx.PySimpleApp(*args, **kwargs) |
|
77 | 77 | return app |
|
78 | 78 | |
|
79 | 79 | def is_event_loop_running_wx(app=None): |
|
80 | 80 | """Is the wx event loop running.""" |
|
81 | 81 | # New way: check attribute on shell instance |
|
82 | 82 | ip = get_ipython() |
|
83 | 83 | if ip is not None: |
|
84 | 84 | if ip.active_eventloop and ip.active_eventloop == 'wx': |
|
85 | 85 | return True |
|
86 | 86 | # Fall through to checking the application, because Wx has a native way |
|
87 | 87 | # to check if the event loop is running, unlike Qt. |
|
88 | 88 | |
|
89 | 89 | # Old way: check Wx application |
|
90 | 90 | if app is None: |
|
91 | 91 | app = get_app_wx() |
|
92 | 92 | if hasattr(app, '_in_event_loop'): |
|
93 | 93 | return app._in_event_loop |
|
94 | 94 | else: |
|
95 | 95 | return app.IsMainLoopRunning() |
|
96 | 96 | |
|
97 | 97 | def start_event_loop_wx(app=None): |
|
98 | 98 | """Start the wx event loop in a consistent manner.""" |
|
99 | 99 | if app is None: |
|
100 | 100 | app = get_app_wx() |
|
101 | 101 | if not is_event_loop_running_wx(app): |
|
102 | 102 | app._in_event_loop = True |
|
103 | 103 | app.MainLoop() |
|
104 | 104 | app._in_event_loop = False |
|
105 | 105 | else: |
|
106 | 106 | app._in_event_loop = True |
|
107 | 107 | |
|
108 | 108 | #----------------------------------------------------------------------------- |
|
109 |
# |
|
|
109 | # Qt | |
|
110 | 110 | #----------------------------------------------------------------------------- |
|
111 | 111 | |
|
112 |
def get_app_qt |
|
|
113 |
"""Create a new |
|
|
112 | def get_app_qt(*args, **kwargs): | |
|
113 | """Create a new Qt app or return an existing one.""" | |
|
114 | 114 | from IPython.external.qt_for_kernel import QtGui |
|
115 | 115 | app = QtGui.QApplication.instance() |
|
116 | 116 | if app is None: |
|
117 | 117 | if not args: |
|
118 | 118 | args = ([''],) |
|
119 | 119 | app = QtGui.QApplication(*args, **kwargs) |
|
120 | 120 | return app |
|
121 | 121 | |
|
122 |
def is_event_loop_running_qt |
|
|
123 |
"""Is the qt |
|
|
122 | def is_event_loop_running_qt(app=None): | |
|
123 | """Is the qt event loop running.""" | |
|
124 | 124 | # New way: check attribute on shell instance |
|
125 | 125 | ip = get_ipython() |
|
126 | 126 | if ip is not None: |
|
127 | 127 | return ip.active_eventloop and ip.active_eventloop.startswith('qt') |
|
128 | 128 | |
|
129 | 129 | # Old way: check attribute on QApplication singleton |
|
130 | 130 | if app is None: |
|
131 |
app = get_app_qt |
|
|
131 | app = get_app_qt(['']) | |
|
132 | 132 | if hasattr(app, '_in_event_loop'): |
|
133 | 133 | return app._in_event_loop |
|
134 | 134 | else: |
|
135 |
# Does qt |
|
|
135 | # Does qt provide a other way to detect this? | |
|
136 | 136 | return False |
|
137 | 137 | |
|
138 |
def start_event_loop_qt |
|
|
139 |
"""Start the qt |
|
|
138 | def start_event_loop_qt(app=None): | |
|
139 | """Start the qt event loop in a consistent manner.""" | |
|
140 | 140 | if app is None: |
|
141 |
app = get_app_qt |
|
|
142 |
if not is_event_loop_running_qt |
|
|
141 | app = get_app_qt(['']) | |
|
142 | if not is_event_loop_running_qt(app): | |
|
143 | 143 | app._in_event_loop = True |
|
144 | 144 | app.exec_() |
|
145 | 145 | app._in_event_loop = False |
|
146 | 146 | else: |
|
147 | 147 | app._in_event_loop = True |
|
148 | 148 | |
|
149 | 149 | #----------------------------------------------------------------------------- |
|
150 | 150 | # Tk |
|
151 | 151 | #----------------------------------------------------------------------------- |
|
152 | 152 | |
|
153 | 153 | #----------------------------------------------------------------------------- |
|
154 | 154 | # gtk |
|
155 | 155 | #----------------------------------------------------------------------------- |
@@ -1,147 +1,132 b'' | |||
|
1 | 1 | import importlib |
|
2 | 2 | import os |
|
3 | 3 | |
|
4 | 4 | aliases = { |
|
5 | 5 | 'qt4': 'qt', |
|
6 | 6 | 'gtk2': 'gtk', |
|
7 | 7 | } |
|
8 | 8 | |
|
9 | 9 | backends = [ |
|
10 | 10 | "qt", |
|
11 | "qt4", | |
|
12 | 11 | "qt5", |
|
13 | 12 | "qt6", |
|
14 | 13 | "gtk", |
|
15 | 14 | "gtk2", |
|
16 | 15 | "gtk3", |
|
17 | 16 | "gtk4", |
|
18 | 17 | "tk", |
|
19 | 18 | "wx", |
|
20 | 19 | "pyglet", |
|
21 | 20 | "glut", |
|
22 | 21 | "osx", |
|
23 | 22 | "asyncio", |
|
24 | 23 | ] |
|
25 | 24 | |
|
26 | 25 | registered = {} |
|
27 | 26 | |
|
28 | 27 | def register(name, inputhook): |
|
29 | 28 | """Register the function *inputhook* as an event loop integration.""" |
|
30 | 29 | registered[name] = inputhook |
|
31 | 30 | |
|
32 | 31 | |
|
33 | 32 | class UnknownBackend(KeyError): |
|
34 | 33 | def __init__(self, name): |
|
35 | 34 | self.name = name |
|
36 | 35 | |
|
37 | 36 | def __str__(self): |
|
38 | 37 | return ("No event loop integration for {!r}. " |
|
39 | 38 | "Supported event loops are: {}").format(self.name, |
|
40 | 39 | ', '.join(backends + sorted(registered))) |
|
41 | 40 | |
|
42 | 41 | |
|
43 | 42 | def set_qt_api(gui): |
|
44 | 43 | """Sets the `QT_API` environment variable if it isn't already set.""" |
|
45 | 44 | |
|
46 | 45 | qt_api = os.environ.get("QT_API", None) |
|
47 | 46 | |
|
48 | 47 | from IPython.external.qt_loaders import ( |
|
49 | 48 | QT_API_PYQT, |
|
50 | 49 | QT_API_PYQT5, |
|
51 | 50 | QT_API_PYQT6, |
|
52 | 51 | QT_API_PYSIDE, |
|
53 | 52 | QT_API_PYSIDE2, |
|
54 | 53 | QT_API_PYSIDE6, |
|
55 | 54 | QT_API_PYQTv1, |
|
56 | 55 | loaded_api, |
|
57 | 56 | ) |
|
58 | 57 | |
|
59 | 58 | loaded = loaded_api() |
|
60 | 59 | |
|
61 | 60 | qt_env2gui = { |
|
62 | 61 | QT_API_PYSIDE: "qt4", |
|
63 | 62 | QT_API_PYQTv1: "qt4", |
|
64 | 63 | QT_API_PYQT: "qt4", |
|
65 | 64 | QT_API_PYSIDE2: "qt5", |
|
66 | 65 | QT_API_PYQT5: "qt5", |
|
67 | 66 | QT_API_PYSIDE6: "qt6", |
|
68 | 67 | QT_API_PYQT6: "qt6", |
|
69 | 68 | } |
|
70 | 69 | if loaded is not None and gui != "qt": |
|
71 | 70 | if qt_env2gui[loaded] != gui: |
|
72 | 71 | raise ImportError( |
|
73 | 72 | f"Cannot switch Qt versions for this session; must use {qt_env2gui[loaded]}." |
|
74 | 73 | ) |
|
75 | 74 | |
|
76 | 75 | if qt_api is not None and gui != "qt": |
|
77 | 76 | if qt_env2gui[qt_api] != gui: |
|
78 | 77 | print( |
|
79 | 78 | f'Request for "{gui}" will be ignored because `QT_API` ' |
|
80 | 79 | f'environment variable is set to "{qt_api}"' |
|
81 | 80 | ) |
|
82 | 81 | else: |
|
83 | # NOTE: 'qt4' is not selectable because it's set as an alias for 'qt'; see `aliases` above. | |
|
84 | if gui == "qt4": | |
|
85 | try: | |
|
86 | import PyQt # noqa | |
|
87 | ||
|
88 | os.environ["QT_API"] = "pyqt" | |
|
89 | except ImportError: | |
|
90 | try: | |
|
91 | import PySide # noqa | |
|
92 | ||
|
93 | os.environ["QT_API"] = "pyside" | |
|
94 | except ImportError: | |
|
95 | # Neither implementation installed; set it to something so IPython gives an error | |
|
96 | os.environ["QT_API"] = "pyqt" | |
|
97 | elif gui == "qt5": | |
|
82 | if gui == "qt5": | |
|
98 | 83 | try: |
|
99 | 84 | import PyQt5 # noqa |
|
100 | 85 | |
|
101 | 86 | os.environ["QT_API"] = "pyqt5" |
|
102 | 87 | except ImportError: |
|
103 | 88 | try: |
|
104 | 89 | import PySide2 # noqa |
|
105 | 90 | |
|
106 | 91 | os.environ["QT_API"] = "pyside2" |
|
107 | 92 | except ImportError: |
|
108 | 93 | os.environ["QT_API"] = "pyqt5" |
|
109 | 94 | elif gui == "qt6": |
|
110 | 95 | try: |
|
111 | 96 | import PyQt6 # noqa |
|
112 | 97 | |
|
113 | 98 | os.environ["QT_API"] = "pyqt6" |
|
114 | 99 | except ImportError: |
|
115 | 100 | try: |
|
116 | 101 | import PySide6 # noqa |
|
117 | 102 | |
|
118 | 103 | os.environ["QT_API"] = "pyside6" |
|
119 | 104 | except ImportError: |
|
120 | 105 | os.environ["QT_API"] = "pyqt6" |
|
121 | 106 | elif gui == "qt": |
|
122 | 107 | # Don't set QT_API; let IPython logic choose the version. |
|
123 | 108 | if "QT_API" in os.environ.keys(): |
|
124 | 109 | del os.environ["QT_API"] |
|
125 | 110 | else: |
|
126 | 111 | raise ValueError( |
|
127 |
f'Unrecognized Qt version: {gui}. Should be |
|
|
112 | f'Unrecognized Qt version: {gui}. Should be "qt5", "qt6", or "qt".' | |
|
128 | 113 | ) |
|
129 | 114 | |
|
130 | 115 | |
|
131 | 116 | def get_inputhook_name_and_func(gui): |
|
132 | 117 | if gui in registered: |
|
133 | 118 | return gui, registered[gui] |
|
134 | 119 | |
|
135 | 120 | if gui not in backends: |
|
136 | 121 | raise UnknownBackend(gui) |
|
137 | 122 | |
|
138 | 123 | if gui in aliases: |
|
139 | 124 | return get_inputhook_name_and_func(aliases[gui]) |
|
140 | 125 | |
|
141 | 126 | gui_mod = gui |
|
142 | 127 | if gui.startswith("qt"): |
|
143 | 128 | set_qt_api(gui) |
|
144 | 129 | gui_mod = "qt" |
|
145 | 130 | |
|
146 | 131 | mod = importlib.import_module("IPython.terminal.pt_inputhooks." + gui_mod) |
|
147 | 132 | return gui, mod.inputhook |
@@ -1,50 +1,50 b'' | |||
|
1 | 1 | import os |
|
2 | 2 | import importlib |
|
3 | 3 | |
|
4 | 4 | import pytest |
|
5 | 5 | |
|
6 | 6 | from IPython.terminal.pt_inputhooks import set_qt_api, get_inputhook_name_and_func |
|
7 | 7 | |
|
8 | 8 | |
|
9 | 9 | guis_avail = [] |
|
10 | 10 | |
|
11 | 11 | |
|
12 | 12 | def _get_qt_vers(): |
|
13 | 13 | """If any version of Qt is available, this will populate `guis_avail` with 'qt' and 'qtx'. Due |
|
14 | 14 | to the import mechanism, we can't import multiple versions of Qt in one session.""" |
|
15 |
for gui in ["qt", "qt6", "qt5" |
|
|
15 | for gui in ["qt", "qt6", "qt5"]: | |
|
16 | 16 | print(f"Trying {gui}") |
|
17 | 17 | try: |
|
18 | 18 | set_qt_api(gui) |
|
19 | 19 | importlib.import_module("IPython.terminal.pt_inputhooks.qt") |
|
20 | 20 | guis_avail.append(gui) |
|
21 | 21 | if "QT_API" in os.environ.keys(): |
|
22 | 22 | del os.environ["QT_API"] |
|
23 | 23 | except ImportError: |
|
24 | 24 | pass # that version of Qt isn't available. |
|
25 | 25 | except RuntimeError: |
|
26 | 26 | pass # the version of IPython doesn't know what to do with this Qt version. |
|
27 | 27 | |
|
28 | 28 | |
|
29 | 29 | _get_qt_vers() |
|
30 | 30 | |
|
31 | 31 | |
|
32 | 32 | @pytest.mark.skipif( |
|
33 | 33 | len(guis_avail) == 0, reason="No viable version of PyQt or PySide installed." |
|
34 | 34 | ) |
|
35 | 35 | def test_inputhook_qt(): |
|
36 | 36 | gui = guis_avail[0] |
|
37 | 37 | |
|
38 | 38 | # Choose a qt version and get the input hook function. This will import Qt... |
|
39 | 39 | get_inputhook_name_and_func(gui) |
|
40 | 40 | |
|
41 | 41 | # ...and now we're stuck with this version of Qt for good; can't switch. |
|
42 |
for not_gui in ["qt6", "qt5" |
|
|
42 | for not_gui in ["qt6", "qt5"]: | |
|
43 | 43 | if not_gui not in guis_avail: |
|
44 | 44 | break |
|
45 | 45 | |
|
46 | 46 | with pytest.raises(ImportError): |
|
47 | 47 | get_inputhook_name_and_func(not_gui) |
|
48 | 48 | |
|
49 | 49 | # A gui of 'qt' means "best available", or in this case, the last one that was used. |
|
50 | 50 | get_inputhook_name_and_func("qt") |
@@ -1,108 +1,108 b'' | |||
|
1 | 1 | ================================ |
|
2 | 2 | Integrating with GUI event loops |
|
3 | 3 | ================================ |
|
4 | 4 | |
|
5 | 5 | When the user types ``%gui qt``, IPython integrates itself with the Qt event |
|
6 | 6 | loop, so you can use both a GUI and an interactive prompt together. IPython |
|
7 | 7 | supports a number of common GUI toolkits, but from IPython 3.0, it is possible |
|
8 | 8 | to integrate other event loops without modifying IPython itself. |
|
9 | 9 | |
|
10 |
Supported event loops include ``qt |
|
|
10 | Supported event loops include ``qt5``, ``qt6``, ``gtk2``, ``gtk3``, ``gtk4``, | |
|
11 | 11 | ``wx``, ``osx`` and ``tk``. Make sure the event loop you specify matches the |
|
12 | 12 | GUI toolkit used by your own code. |
|
13 | 13 | |
|
14 | 14 | To make IPython GUI event loop integration occur automatically at every |
|
15 | 15 | startup, set the ``c.InteractiveShellApp.gui`` configuration key in your |
|
16 | 16 | IPython profile (see :ref:`setting_config`). |
|
17 | 17 | |
|
18 | 18 | If the event loop you use is supported by IPython, turning on event loop |
|
19 | 19 | integration follows the steps just described whether you use Terminal IPython |
|
20 | 20 | or an IPython kernel. |
|
21 | 21 | |
|
22 | 22 | However, the way Terminal IPython handles event loops is very different from |
|
23 | 23 | the way IPython kernel does, so if you need to integrate with a new kind of |
|
24 | 24 | event loop, different steps are needed to integrate with each. |
|
25 | 25 | |
|
26 | 26 | Integrating with a new event loop in the terminal |
|
27 | 27 | ------------------------------------------------- |
|
28 | 28 | |
|
29 | 29 | .. versionchanged:: 5.0 |
|
30 | 30 | |
|
31 | 31 | There is a new API for event loop integration using prompt_toolkit. |
|
32 | 32 | |
|
33 | 33 | In the terminal, IPython uses prompt_toolkit to prompt the user for input. |
|
34 | 34 | prompt_toolkit provides hooks to integrate with an external event loop. |
|
35 | 35 | |
|
36 | 36 | To integrate an event loop, define a function which runs the GUI event loop |
|
37 | 37 | until there is input waiting for prompt_toolkit to process. There are two ways |
|
38 | 38 | to detect this condition:: |
|
39 | 39 | |
|
40 | 40 | # Polling for input. |
|
41 | 41 | def inputhook(context): |
|
42 | 42 | while not context.input_is_ready(): |
|
43 | 43 | # Replace this with the appropriate call for the event loop: |
|
44 | 44 | iterate_loop_once() |
|
45 | 45 | |
|
46 | 46 | # Using a file descriptor to notify the event loop to stop. |
|
47 | 47 | def inputhook2(context): |
|
48 | 48 | fd = context.fileno() |
|
49 | 49 | # Replace the functions below with those for the event loop. |
|
50 | 50 | add_file_reader(fd, callback=stop_the_loop) |
|
51 | 51 | run_the_loop() |
|
52 | 52 | |
|
53 | 53 | Once you have defined this function, register it with IPython: |
|
54 | 54 | |
|
55 | 55 | .. currentmodule:: IPython.terminal.pt_inputhooks |
|
56 | 56 | |
|
57 | 57 | .. function:: register(name, inputhook) |
|
58 | 58 | |
|
59 | 59 | Register the function *inputhook* as the event loop integration for the |
|
60 | 60 | GUI *name*. If ``name='foo'``, then the user can enable this integration |
|
61 | 61 | by running ``%gui foo``. |
|
62 | 62 | |
|
63 | 63 | |
|
64 | 64 | Integrating with a new event loop in the kernel |
|
65 | 65 | ----------------------------------------------- |
|
66 | 66 | |
|
67 | 67 | The kernel runs its own event loop, so it's simpler to integrate with others. |
|
68 | 68 | IPython allows the other event loop to take control, but it must call |
|
69 | 69 | :meth:`IPython.kernel.zmq.kernelbase.Kernel.do_one_iteration` periodically. |
|
70 | 70 | |
|
71 | 71 | To integrate with this, write a function that takes a single argument, |
|
72 | 72 | the IPython kernel instance, arranges for your event loop to call |
|
73 | 73 | ``kernel.do_one_iteration()`` at least every ``kernel._poll_interval`` seconds, |
|
74 | 74 | and starts the event loop. |
|
75 | 75 | |
|
76 | 76 | Decorate this function with :func:`IPython.kernel.zmq.eventloops.register_integration`, |
|
77 | 77 | passing in the names you wish to register it for. Here is a slightly simplified |
|
78 | 78 | version of the Tkinter integration already included in IPython:: |
|
79 | 79 | |
|
80 | 80 | @register_integration('tk') |
|
81 | 81 | def loop_tk(kernel): |
|
82 | 82 | """Start a kernel with the Tk event loop.""" |
|
83 | 83 | from tkinter import Tk |
|
84 | 84 | |
|
85 | 85 | # Tk uses milliseconds |
|
86 | 86 | poll_interval = int(1000*kernel._poll_interval) |
|
87 | 87 | # For Tkinter, we create a Tk object and call its withdraw method. |
|
88 | 88 | class Timer(object): |
|
89 | 89 | def __init__(self, func): |
|
90 | 90 | self.app = Tk() |
|
91 | 91 | self.app.withdraw() |
|
92 | 92 | self.func = func |
|
93 | 93 | |
|
94 | 94 | def on_timer(self): |
|
95 | 95 | self.func() |
|
96 | 96 | self.app.after(poll_interval, self.on_timer) |
|
97 | 97 | |
|
98 | 98 | def start(self): |
|
99 | 99 | self.on_timer() # Call it once to get things going. |
|
100 | 100 | self.app.mainloop() |
|
101 | 101 | |
|
102 | 102 | kernel.timer = Timer(kernel.do_one_iteration) |
|
103 | 103 | kernel.timer.start() |
|
104 | 104 | |
|
105 | 105 | Some event loops can go one better, and integrate checking for messages on the |
|
106 | 106 | kernel's ZMQ sockets, making the kernel more responsive than plain polling. How |
|
107 | 107 | to do this is outside the scope of this document; if you are interested, look at |
|
108 | 108 | the integration with Qt in :mod:`IPython.kernel.zmq.eventloops`. |
@@ -1,1044 +1,1037 b'' | |||
|
1 | 1 | ================= |
|
2 | 2 | IPython reference |
|
3 | 3 | ================= |
|
4 | 4 | |
|
5 | 5 | .. _command_line_options: |
|
6 | 6 | |
|
7 | 7 | Command-line usage |
|
8 | 8 | ================== |
|
9 | 9 | |
|
10 | 10 | You start IPython with the command:: |
|
11 | 11 | |
|
12 | 12 | $ ipython [options] files |
|
13 | 13 | |
|
14 | 14 | If invoked with no options, it executes the file and exits, passing the |
|
15 | 15 | remaining arguments to the script, just as if you had specified the same |
|
16 | 16 | command with python. You may need to specify `--` before args to be passed |
|
17 | 17 | to the script, to prevent IPython from attempting to parse them. |
|
18 | 18 | If you add the ``-i`` flag, it drops you into the interpreter while still |
|
19 | 19 | acknowledging any options you may have set in your ``ipython_config.py``. This |
|
20 | 20 | behavior is different from standard Python, which when called as python ``-i`` |
|
21 | 21 | will only execute one file and ignore your configuration setup. |
|
22 | 22 | |
|
23 | 23 | Please note that some of the configuration options are not available at the |
|
24 | 24 | command line, simply because they are not practical here. Look into your |
|
25 | 25 | configuration files for details on those. There are separate configuration files |
|
26 | 26 | for each profile, and the files look like :file:`ipython_config.py` or |
|
27 | 27 | :file:`ipython_config_{frontendname}.py`. Profile directories look like |
|
28 | 28 | :file:`profile_{profilename}` and are typically installed in the |
|
29 | 29 | :envvar:`IPYTHONDIR` directory, which defaults to :file:`$HOME/.ipython`. For |
|
30 | 30 | Windows users, :envvar:`HOME` resolves to :file:`C:\\Users\\{YourUserName}` in |
|
31 | 31 | most instances. |
|
32 | 32 | |
|
33 | 33 | Command-line Options |
|
34 | 34 | -------------------- |
|
35 | 35 | |
|
36 | 36 | To see the options IPython accepts, use ``ipython --help`` (and you probably |
|
37 | 37 | should run the output through a pager such as ``ipython --help | less`` for |
|
38 | 38 | more convenient reading). This shows all the options that have a single-word |
|
39 | 39 | alias to control them, but IPython lets you configure all of its objects from |
|
40 | 40 | the command-line by passing the full class name and a corresponding value; type |
|
41 | 41 | ``ipython --help-all`` to see this full list. For example:: |
|
42 | 42 | |
|
43 | 43 | $ ipython --help-all |
|
44 | 44 | <...snip...> |
|
45 | 45 | --matplotlib=<CaselessStrEnum> (InteractiveShellApp.matplotlib) |
|
46 | 46 | Default: None |
|
47 |
Choices: ['auto', 'gtk', 'gtk3', 'gtk4', 'inline', 'nbagg', 'notebook', 'osx', 'qt', 'qt |
|
|
47 | Choices: ['auto', 'gtk', 'gtk3', 'gtk4', 'inline', 'nbagg', 'notebook', 'osx', 'qt', 'qt5', 'qt6', 'tk', 'wx'] | |
|
48 | 48 | Configure matplotlib for interactive use with the default matplotlib |
|
49 | 49 | backend. |
|
50 | 50 | <...snip...> |
|
51 | 51 | |
|
52 | 52 | |
|
53 | 53 | Indicate that the following:: |
|
54 | 54 | |
|
55 | 55 | $ ipython --matplotlib qt |
|
56 | 56 | |
|
57 | 57 | |
|
58 | 58 | is equivalent to:: |
|
59 | 59 | |
|
60 | 60 | $ ipython --InteractiveShellApp.matplotlib='qt' |
|
61 | 61 | |
|
62 | 62 | Note that in the second form, you *must* use the equal sign, as the expression |
|
63 | 63 | is evaluated as an actual Python assignment. While in the above example the |
|
64 | 64 | short form is more convenient, only the most common options have a short form, |
|
65 | 65 | while any configurable variable in IPython can be set at the command-line by |
|
66 | 66 | using the long form. This long form is the same syntax used in the |
|
67 | 67 | configuration files, if you want to set these options permanently. |
|
68 | 68 | |
|
69 | 69 | |
|
70 | 70 | Interactive use |
|
71 | 71 | =============== |
|
72 | 72 | |
|
73 | 73 | IPython is meant to work as a drop-in replacement for the standard interactive |
|
74 | 74 | interpreter. As such, any code which is valid python should execute normally |
|
75 | 75 | under IPython (cases where this is not true should be reported as bugs). It |
|
76 | 76 | does, however, offer many features which are not available at a standard python |
|
77 | 77 | prompt. What follows is a list of these. |
|
78 | 78 | |
|
79 | 79 | |
|
80 | 80 | Caution for Windows users |
|
81 | 81 | ------------------------- |
|
82 | 82 | |
|
83 | 83 | Windows, unfortunately, uses the ``\`` character as a path separator. This is a |
|
84 | 84 | terrible choice, because ``\`` also represents the escape character in most |
|
85 | 85 | modern programming languages, including Python. For this reason, using '/' |
|
86 | 86 | character is recommended if you have problems with ``\``. However, in Windows |
|
87 | 87 | commands '/' flags options, so you can not use it for the root directory. This |
|
88 | 88 | means that paths beginning at the root must be typed in a contrived manner |
|
89 | 89 | like: ``%copy \opt/foo/bar.txt \tmp`` |
|
90 | 90 | |
|
91 | 91 | .. _magic: |
|
92 | 92 | |
|
93 | 93 | Magic command system |
|
94 | 94 | -------------------- |
|
95 | 95 | |
|
96 | 96 | IPython will treat any line whose first character is a % as a special |
|
97 | 97 | call to a 'magic' function. These allow you to control the behavior of |
|
98 | 98 | IPython itself, plus a lot of system-type features. They are all |
|
99 | 99 | prefixed with a % character, but parameters are given without |
|
100 | 100 | parentheses or quotes. |
|
101 | 101 | |
|
102 | 102 | Lines that begin with ``%%`` signal a *cell magic*: they take as arguments not |
|
103 | 103 | only the rest of the current line, but all lines below them as well, in the |
|
104 | 104 | current execution block. Cell magics can in fact make arbitrary modifications |
|
105 | 105 | to the input they receive, which need not even be valid Python code at all. |
|
106 | 106 | They receive the whole block as a single string. |
|
107 | 107 | |
|
108 | 108 | As a line magic example, the :magic:`cd` magic works just like the OS command of |
|
109 | 109 | the same name:: |
|
110 | 110 | |
|
111 | 111 | In [8]: %cd |
|
112 | 112 | /home/fperez |
|
113 | 113 | |
|
114 | 114 | The following uses the builtin :magic:`timeit` in cell mode:: |
|
115 | 115 | |
|
116 | 116 | In [10]: %%timeit x = range(10000) |
|
117 | 117 | ...: min(x) |
|
118 | 118 | ...: max(x) |
|
119 | 119 | ...: |
|
120 | 120 | 1000 loops, best of 3: 438 us per loop |
|
121 | 121 | |
|
122 | 122 | In this case, ``x = range(10000)`` is called as the line argument, and the |
|
123 | 123 | block with ``min(x)`` and ``max(x)`` is called as the cell body. The |
|
124 | 124 | :magic:`timeit` magic receives both. |
|
125 | 125 | |
|
126 | 126 | If you have 'automagic' enabled (as it is by default), you don't need to type in |
|
127 | 127 | the single ``%`` explicitly for line magics; IPython will scan its internal |
|
128 | 128 | list of magic functions and call one if it exists. With automagic on you can |
|
129 | 129 | then just type ``cd mydir`` to go to directory 'mydir':: |
|
130 | 130 | |
|
131 | 131 | In [9]: cd mydir |
|
132 | 132 | /home/fperez/mydir |
|
133 | 133 | |
|
134 | 134 | Cell magics *always* require an explicit ``%%`` prefix, automagic |
|
135 | 135 | calling only works for line magics. |
|
136 | 136 | |
|
137 | 137 | The automagic system has the lowest possible precedence in name searches, so |
|
138 | 138 | you can freely use variables with the same names as magic commands. If a magic |
|
139 | 139 | command is 'shadowed' by a variable, you will need the explicit ``%`` prefix to |
|
140 | 140 | use it: |
|
141 | 141 | |
|
142 | 142 | .. sourcecode:: ipython |
|
143 | 143 | |
|
144 | 144 | In [1]: cd ipython # %cd is called by automagic |
|
145 | 145 | /home/fperez/ipython |
|
146 | 146 | |
|
147 | 147 | In [2]: cd=1 # now cd is just a variable |
|
148 | 148 | |
|
149 | 149 | In [3]: cd .. # and doesn't work as a function anymore |
|
150 | 150 | File "<ipython-input-3-9fedb3aff56c>", line 1 |
|
151 | 151 | cd .. |
|
152 | 152 | ^ |
|
153 | 153 | SyntaxError: invalid syntax |
|
154 | 154 | |
|
155 | 155 | |
|
156 | 156 | In [4]: %cd .. # but %cd always works |
|
157 | 157 | /home/fperez |
|
158 | 158 | |
|
159 | 159 | In [5]: del cd # if you remove the cd variable, automagic works again |
|
160 | 160 | |
|
161 | 161 | In [6]: cd ipython |
|
162 | 162 | |
|
163 | 163 | /home/fperez/ipython |
|
164 | 164 | |
|
165 | 165 | Line magics, if they return a value, can be assigned to a variable using the |
|
166 | 166 | syntax ``l = %sx ls`` (which in this particular case returns the result of `ls` |
|
167 | 167 | as a python list). See :ref:`below <manual_capture>` for more information. |
|
168 | 168 | |
|
169 | 169 | Type ``%magic`` for more information, including a list of all available magic |
|
170 | 170 | functions at any time and their docstrings. You can also type |
|
171 | 171 | ``%magic_function_name?`` (see :ref:`below <dynamic_object_info>` for |
|
172 | 172 | information on the '?' system) to get information about any particular magic |
|
173 | 173 | function you are interested in. |
|
174 | 174 | |
|
175 | 175 | The API documentation for the :mod:`IPython.core.magic` module contains the full |
|
176 | 176 | docstrings of all currently available magic commands. |
|
177 | 177 | |
|
178 | 178 | .. seealso:: |
|
179 | 179 | |
|
180 | 180 | :doc:`magics` |
|
181 | 181 | A list of the line and cell magics available in IPython by default |
|
182 | 182 | |
|
183 | 183 | :ref:`defining_magics` |
|
184 | 184 | How to define and register additional magic functions |
|
185 | 185 | |
|
186 | 186 | |
|
187 | 187 | Access to the standard Python help |
|
188 | 188 | ---------------------------------- |
|
189 | 189 | |
|
190 | 190 | Simply type ``help()`` to access Python's standard help system. You can |
|
191 | 191 | also type ``help(object)`` for information about a given object, or |
|
192 | 192 | ``help('keyword')`` for information on a keyword. You may need to configure your |
|
193 | 193 | PYTHONDOCS environment variable for this feature to work correctly. |
|
194 | 194 | |
|
195 | 195 | .. _dynamic_object_info: |
|
196 | 196 | |
|
197 | 197 | Dynamic object information |
|
198 | 198 | -------------------------- |
|
199 | 199 | |
|
200 | 200 | Typing ``?word`` or ``word?`` prints detailed information about an object. If |
|
201 | 201 | certain strings in the object are too long (e.g. function signatures) they get |
|
202 | 202 | snipped in the center for brevity. This system gives access variable types and |
|
203 | 203 | values, docstrings, function prototypes and other useful information. |
|
204 | 204 | |
|
205 | 205 | If the information will not fit in the terminal, it is displayed in a pager |
|
206 | 206 | (``less`` if available, otherwise a basic internal pager). |
|
207 | 207 | |
|
208 | 208 | Typing ``??word`` or ``word??`` gives access to the full information, including |
|
209 | 209 | the source code where possible. Long strings are not snipped. |
|
210 | 210 | |
|
211 | 211 | The following magic functions are particularly useful for gathering |
|
212 | 212 | information about your working environment: |
|
213 | 213 | |
|
214 | 214 | * :magic:`pdoc` **<object>**: Print (or run through a pager if too long) the |
|
215 | 215 | docstring for an object. If the given object is a class, it will |
|
216 | 216 | print both the class and the constructor docstrings. |
|
217 | 217 | * :magic:`pdef` **<object>**: Print the call signature for any callable |
|
218 | 218 | object. If the object is a class, print the constructor information. |
|
219 | 219 | * :magic:`psource` **<object>**: Print (or run through a pager if too long) |
|
220 | 220 | the source code for an object. |
|
221 | 221 | * :magic:`pfile` **<object>**: Show the entire source file where an object was |
|
222 | 222 | defined via a pager, opening it at the line where the object |
|
223 | 223 | definition begins. |
|
224 | 224 | * :magic:`who`/:magic:`whos`: These functions give information about identifiers |
|
225 | 225 | you have defined interactively (not things you loaded or defined |
|
226 | 226 | in your configuration files). %who just prints a list of |
|
227 | 227 | identifiers and %whos prints a table with some basic details about |
|
228 | 228 | each identifier. |
|
229 | 229 | |
|
230 | 230 | The dynamic object information functions (?/??, ``%pdoc``, |
|
231 | 231 | ``%pfile``, ``%pdef``, ``%psource``) work on object attributes, as well as |
|
232 | 232 | directly on variables. For example, after doing ``import os``, you can use |
|
233 | 233 | ``os.path.abspath??``. |
|
234 | 234 | |
|
235 | 235 | |
|
236 | 236 | Command line completion |
|
237 | 237 | +++++++++++++++++++++++ |
|
238 | 238 | |
|
239 | 239 | At any time, hitting TAB will complete any available python commands or |
|
240 | 240 | variable names, and show you a list of the possible completions if |
|
241 | 241 | there's no unambiguous one. It will also complete filenames in the |
|
242 | 242 | current directory if no python names match what you've typed so far. |
|
243 | 243 | |
|
244 | 244 | |
|
245 | 245 | Search command history |
|
246 | 246 | ++++++++++++++++++++++ |
|
247 | 247 | |
|
248 | 248 | IPython provides two ways for searching through previous input and thus |
|
249 | 249 | reduce the need for repetitive typing: |
|
250 | 250 | |
|
251 | 251 | 1. Start typing, and then use the up and down arrow keys (or :kbd:`Ctrl-p` |
|
252 | 252 | and :kbd:`Ctrl-n`) to search through only the history items that match |
|
253 | 253 | what you've typed so far. |
|
254 | 254 | 2. Hit :kbd:`Ctrl-r`: to open a search prompt. Begin typing and the system |
|
255 | 255 | searches your history for lines that contain what you've typed so |
|
256 | 256 | far, completing as much as it can. |
|
257 | 257 | |
|
258 | 258 | IPython will save your input history when it leaves and reload it next |
|
259 | 259 | time you restart it. By default, the history file is named |
|
260 | 260 | :file:`.ipython/profile_{name}/history.sqlite`. |
|
261 | 261 | |
|
262 | 262 | Autoindent |
|
263 | 263 | ++++++++++ |
|
264 | 264 | |
|
265 | 265 | Starting with 5.0, IPython uses `prompt_toolkit` in place of ``readline``, |
|
266 | 266 | it thus can recognize lines ending in ':' and indent the next line, |
|
267 | 267 | while also un-indenting automatically after 'raise' or 'return', |
|
268 | 268 | and support real multi-line editing as well as syntactic coloration |
|
269 | 269 | during edition. |
|
270 | 270 | |
|
271 | 271 | This feature does not use the ``readline`` library anymore, so it will |
|
272 | 272 | not honor your :file:`~/.inputrc` configuration (or whatever |
|
273 | 273 | file your :envvar:`INPUTRC` environment variable points to). |
|
274 | 274 | |
|
275 | 275 | In particular if you want to change the input mode to ``vi``, you will need to |
|
276 | 276 | set the ``TerminalInteractiveShell.editing_mode`` configuration option of IPython. |
|
277 | 277 | |
|
278 | 278 | Session logging and restoring |
|
279 | 279 | ----------------------------- |
|
280 | 280 | |
|
281 | 281 | You can log all input from a session either by starting IPython with the |
|
282 | 282 | command line switch ``--logfile=foo.py`` (see :ref:`here <command_line_options>`) |
|
283 | 283 | or by activating the logging at any moment with the magic function :magic:`logstart`. |
|
284 | 284 | |
|
285 | 285 | Log files can later be reloaded by running them as scripts and IPython |
|
286 | 286 | will attempt to 'replay' the log by executing all the lines in it, thus |
|
287 | 287 | restoring the state of a previous session. This feature is not quite |
|
288 | 288 | perfect, but can still be useful in many cases. |
|
289 | 289 | |
|
290 | 290 | The log files can also be used as a way to have a permanent record of |
|
291 | 291 | any code you wrote while experimenting. Log files are regular text files |
|
292 | 292 | which you can later open in your favorite text editor to extract code or |
|
293 | 293 | to 'clean them up' before using them to replay a session. |
|
294 | 294 | |
|
295 | 295 | The :magic:`logstart` function for activating logging in mid-session is used as |
|
296 | 296 | follows:: |
|
297 | 297 | |
|
298 | 298 | %logstart [log_name [log_mode]] |
|
299 | 299 | |
|
300 | 300 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
301 | 301 | current working directory, in 'rotate' mode (see below). |
|
302 | 302 | |
|
303 | 303 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
304 | 304 | history up to that point and then continues logging. |
|
305 | 305 | |
|
306 | 306 | %logstart takes a second optional parameter: logging mode. This can be |
|
307 | 307 | one of (note that the modes are given unquoted): |
|
308 | 308 | |
|
309 | 309 | * [over:] overwrite existing log_name. |
|
310 | 310 | * [backup:] rename (if exists) to log_name~ and start log_name. |
|
311 | 311 | * [append:] well, that says it. |
|
312 | 312 | * [rotate:] create rotating logs log_name.1~, log_name.2~, etc. |
|
313 | 313 | |
|
314 | 314 | Adding the '-o' flag to '%logstart' magic (as in '%logstart -o [log_name [log_mode]]') |
|
315 | 315 | will also include output from iPython in the log file. |
|
316 | 316 | |
|
317 | 317 | The :magic:`logoff` and :magic:`logon` functions allow you to temporarily stop and |
|
318 | 318 | resume logging to a file which had previously been started with |
|
319 | 319 | %logstart. They will fail (with an explanation) if you try to use them |
|
320 | 320 | before logging has been started. |
|
321 | 321 | |
|
322 | 322 | .. _system_shell_access: |
|
323 | 323 | |
|
324 | 324 | System shell access |
|
325 | 325 | ------------------- |
|
326 | 326 | |
|
327 | 327 | Any input line beginning with a ``!`` character is passed verbatim (minus |
|
328 | 328 | the ``!``, of course) to the underlying operating system. For example, |
|
329 | 329 | typing ``!ls`` will run 'ls' in the current directory. |
|
330 | 330 | |
|
331 | 331 | .. _manual_capture: |
|
332 | 332 | |
|
333 | 333 | Manual capture of command output and magic output |
|
334 | 334 | ------------------------------------------------- |
|
335 | 335 | |
|
336 | 336 | You can assign the result of a system command to a Python variable with the |
|
337 | 337 | syntax ``myfiles = !ls``. Similarly, the result of a magic (as long as it returns |
|
338 | 338 | a value) can be assigned to a variable. For example, the syntax ``myfiles = %sx ls`` |
|
339 | 339 | is equivalent to the above system command example (the :magic:`sx` magic runs a shell command |
|
340 | 340 | and captures the output). Each of these gets machine |
|
341 | 341 | readable output from stdout (e.g. without colours), and splits on newlines. To |
|
342 | 342 | explicitly get this sort of output without assigning to a variable, use two |
|
343 | 343 | exclamation marks (``!!ls``) or the :magic:`sx` magic command without an assignment. |
|
344 | 344 | (However, ``!!`` commands cannot be assigned to a variable.) |
|
345 | 345 | |
|
346 | 346 | The captured list in this example has some convenience features. ``myfiles.n`` or ``myfiles.s`` |
|
347 | 347 | returns a string delimited by newlines or spaces, respectively. ``myfiles.p`` |
|
348 | 348 | produces `path objects <http://pypi.python.org/pypi/path.py>`_ from the list items. |
|
349 | 349 | See :ref:`string_lists` for details. |
|
350 | 350 | |
|
351 | 351 | IPython also allows you to expand the value of python variables when |
|
352 | 352 | making system calls. Wrap variables or expressions in {braces}:: |
|
353 | 353 | |
|
354 | 354 | In [1]: pyvar = 'Hello world' |
|
355 | 355 | In [2]: !echo "A python variable: {pyvar}" |
|
356 | 356 | A python variable: Hello world |
|
357 | 357 | In [3]: import math |
|
358 | 358 | In [4]: x = 8 |
|
359 | 359 | In [5]: !echo {math.factorial(x)} |
|
360 | 360 | 40320 |
|
361 | 361 | |
|
362 | 362 | For simple cases, you can alternatively prepend $ to a variable name:: |
|
363 | 363 | |
|
364 | 364 | In [6]: !echo $sys.argv |
|
365 | 365 | [/home/fperez/usr/bin/ipython] |
|
366 | 366 | In [7]: !echo "A system variable: $$HOME" # Use $$ for literal $ |
|
367 | 367 | A system variable: /home/fperez |
|
368 | 368 | |
|
369 | 369 | Note that `$$` is used to represent a literal `$`. |
|
370 | 370 | |
|
371 | 371 | System command aliases |
|
372 | 372 | ---------------------- |
|
373 | 373 | |
|
374 | 374 | The :magic:`alias` magic function allows you to define magic functions which are in fact |
|
375 | 375 | system shell commands. These aliases can have parameters. |
|
376 | 376 | |
|
377 | 377 | ``%alias alias_name cmd`` defines 'alias_name' as an alias for 'cmd' |
|
378 | 378 | |
|
379 | 379 | Then, typing ``alias_name params`` will execute the system command 'cmd |
|
380 | 380 | params' (from your underlying operating system). |
|
381 | 381 | |
|
382 | 382 | You can also define aliases with parameters using ``%s`` specifiers (one per |
|
383 | 383 | parameter). The following example defines the parts function as an |
|
384 | 384 | alias to the command ``echo first %s second %s`` where each ``%s`` will be |
|
385 | 385 | replaced by a positional parameter to the call to %parts:: |
|
386 | 386 | |
|
387 | 387 | In [1]: %alias parts echo first %s second %s |
|
388 | 388 | In [2]: parts A B |
|
389 | 389 | first A second B |
|
390 | 390 | In [3]: parts A |
|
391 | 391 | ERROR: Alias <parts> requires 2 arguments, 1 given. |
|
392 | 392 | |
|
393 | 393 | If called with no parameters, :magic:`alias` prints the table of currently |
|
394 | 394 | defined aliases. |
|
395 | 395 | |
|
396 | 396 | The :magic:`rehashx` magic allows you to load your entire $PATH as |
|
397 | 397 | ipython aliases. See its docstring for further details. |
|
398 | 398 | |
|
399 | 399 | |
|
400 | 400 | .. _dreload: |
|
401 | 401 | |
|
402 | 402 | Recursive reload |
|
403 | 403 | ---------------- |
|
404 | 404 | |
|
405 | 405 | The :mod:`IPython.lib.deepreload` module allows you to recursively reload a |
|
406 | 406 | module: changes made to any of its dependencies will be reloaded without |
|
407 | 407 | having to exit. To start using it, do:: |
|
408 | 408 | |
|
409 | 409 | from IPython.lib.deepreload import reload as dreload |
|
410 | 410 | |
|
411 | 411 | |
|
412 | 412 | Verbose and colored exception traceback printouts |
|
413 | 413 | ------------------------------------------------- |
|
414 | 414 | |
|
415 | 415 | IPython provides the option to see very detailed exception tracebacks, |
|
416 | 416 | which can be especially useful when debugging large programs. You can |
|
417 | 417 | run any Python file with the %run function to benefit from these |
|
418 | 418 | detailed tracebacks. Furthermore, both normal and verbose tracebacks can |
|
419 | 419 | be colored (if your terminal supports it) which makes them much easier |
|
420 | 420 | to parse visually. |
|
421 | 421 | |
|
422 | 422 | See the magic :magic:`xmode` and :magic:`colors` functions for details. |
|
423 | 423 | |
|
424 | 424 | These features are basically a terminal version of Ka-Ping Yee's cgitb |
|
425 | 425 | module, now part of the standard Python library. |
|
426 | 426 | |
|
427 | 427 | |
|
428 | 428 | .. _input_caching: |
|
429 | 429 | |
|
430 | 430 | Input caching system |
|
431 | 431 | -------------------- |
|
432 | 432 | |
|
433 | 433 | IPython offers numbered prompts (In/Out) with input and output caching |
|
434 | 434 | (also referred to as 'input history'). All input is saved and can be |
|
435 | 435 | retrieved as variables (besides the usual arrow key recall), in |
|
436 | 436 | addition to the :magic:`rep` magic command that brings a history entry |
|
437 | 437 | up for editing on the next command line. |
|
438 | 438 | |
|
439 | 439 | The following variables always exist: |
|
440 | 440 | |
|
441 | 441 | * ``_i``, ``_ii``, ``_iii``: store previous, next previous and next-next |
|
442 | 442 | previous inputs. |
|
443 | 443 | |
|
444 | 444 | * ``In``, ``_ih`` : a list of all inputs; ``_ih[n]`` is the input from line |
|
445 | 445 | ``n``. If you overwrite In with a variable of your own, you can remake the |
|
446 | 446 | assignment to the internal list with a simple ``In=_ih``. |
|
447 | 447 | |
|
448 | 448 | Additionally, global variables named ``_i<n>`` are dynamically created (``<n>`` |
|
449 | 449 | being the prompt counter), so ``_i<n> == _ih[<n>] == In[<n>]``. |
|
450 | 450 | |
|
451 | 451 | For example, what you typed at prompt 14 is available as ``_i14``, ``_ih[14]`` |
|
452 | 452 | and ``In[14]``. |
|
453 | 453 | |
|
454 | 454 | This allows you to easily cut and paste multi line interactive prompts |
|
455 | 455 | by printing them out: they print like a clean string, without prompt |
|
456 | 456 | characters. You can also manipulate them like regular variables (they |
|
457 | 457 | are strings), modify or exec them. |
|
458 | 458 | |
|
459 | 459 | You can also re-execute multiple lines of input easily by using the magic |
|
460 | 460 | :magic:`rerun` or :magic:`macro` functions. The macro system also allows you to |
|
461 | 461 | re-execute previous lines which include magic function calls (which require |
|
462 | 462 | special processing). Type %macro? for more details on the macro system. |
|
463 | 463 | |
|
464 | 464 | A history function :magic:`history` allows you to see any part of your input |
|
465 | 465 | history by printing a range of the _i variables. |
|
466 | 466 | |
|
467 | 467 | You can also search ('grep') through your history by typing |
|
468 | 468 | ``%hist -g somestring``. This is handy for searching for URLs, IP addresses, |
|
469 | 469 | etc. You can bring history entries listed by '%hist -g' up for editing |
|
470 | 470 | with the %recall command, or run them immediately with :magic:`rerun`. |
|
471 | 471 | |
|
472 | 472 | .. _output_caching: |
|
473 | 473 | |
|
474 | 474 | Output caching system |
|
475 | 475 | --------------------- |
|
476 | 476 | |
|
477 | 477 | For output that is returned from actions, a system similar to the input |
|
478 | 478 | cache exists but using _ instead of _i. Only actions that produce a |
|
479 | 479 | result (NOT assignments, for example) are cached. If you are familiar |
|
480 | 480 | with Mathematica, IPython's _ variables behave exactly like |
|
481 | 481 | Mathematica's % variables. |
|
482 | 482 | |
|
483 | 483 | The following variables always exist: |
|
484 | 484 | |
|
485 | 485 | * [_] (a single underscore): stores previous output, like Python's |
|
486 | 486 | default interpreter. |
|
487 | 487 | * [__] (two underscores): next previous. |
|
488 | 488 | * [___] (three underscores): next-next previous. |
|
489 | 489 | |
|
490 | 490 | Additionally, global variables named _<n> are dynamically created (<n> |
|
491 | 491 | being the prompt counter), such that the result of output <n> is always |
|
492 | 492 | available as _<n> (don't use the angle brackets, just the number, e.g. |
|
493 | 493 | ``_21``). |
|
494 | 494 | |
|
495 | 495 | These variables are also stored in a global dictionary (not a |
|
496 | 496 | list, since it only has entries for lines which returned a result) |
|
497 | 497 | available under the names _oh and Out (similar to _ih and In). So the |
|
498 | 498 | output from line 12 can be obtained as ``_12``, ``Out[12]`` or ``_oh[12]``. If you |
|
499 | 499 | accidentally overwrite the Out variable you can recover it by typing |
|
500 | 500 | ``Out=_oh`` at the prompt. |
|
501 | 501 | |
|
502 | 502 | This system obviously can potentially put heavy memory demands on your |
|
503 | 503 | system, since it prevents Python's garbage collector from removing any |
|
504 | 504 | previously computed results. You can control how many results are kept |
|
505 | 505 | in memory with the configuration option ``InteractiveShell.cache_size``. |
|
506 | 506 | If you set it to 0, output caching is disabled. You can also use the :magic:`reset` |
|
507 | 507 | and :magic:`xdel` magics to clear large items from memory. |
|
508 | 508 | |
|
509 | 509 | Directory history |
|
510 | 510 | ----------------- |
|
511 | 511 | |
|
512 | 512 | Your history of visited directories is kept in the global list _dh, and |
|
513 | 513 | the magic :magic:`cd` command can be used to go to any entry in that list. The |
|
514 | 514 | :magic:`dhist` command allows you to view this history. Do ``cd -<TAB>`` to |
|
515 | 515 | conveniently view the directory history. |
|
516 | 516 | |
|
517 | 517 | |
|
518 | 518 | Automatic parentheses and quotes |
|
519 | 519 | -------------------------------- |
|
520 | 520 | |
|
521 | 521 | These features were adapted from Nathan Gray's LazyPython. They are |
|
522 | 522 | meant to allow less typing for common situations. |
|
523 | 523 | |
|
524 | 524 | Callable objects (i.e. functions, methods, etc) can be invoked like this |
|
525 | 525 | (notice the commas between the arguments):: |
|
526 | 526 | |
|
527 | 527 | In [1]: callable_ob arg1, arg2, arg3 |
|
528 | 528 | ------> callable_ob(arg1, arg2, arg3) |
|
529 | 529 | |
|
530 | 530 | .. note:: |
|
531 | 531 | This feature is disabled by default. To enable it, use the ``%autocall`` |
|
532 | 532 | magic command. The commands below with special prefixes will always work, |
|
533 | 533 | however. |
|
534 | 534 | |
|
535 | 535 | You can force automatic parentheses by using '/' as the first character |
|
536 | 536 | of a line. For example:: |
|
537 | 537 | |
|
538 | 538 | In [2]: /globals # becomes 'globals()' |
|
539 | 539 | |
|
540 | 540 | Note that the '/' MUST be the first character on the line! This won't work:: |
|
541 | 541 | |
|
542 | 542 | In [3]: print /globals # syntax error |
|
543 | 543 | |
|
544 | 544 | In most cases the automatic algorithm should work, so you should rarely |
|
545 | 545 | need to explicitly invoke /. One notable exception is if you are trying |
|
546 | 546 | to call a function with a list of tuples as arguments (the parenthesis |
|
547 | 547 | will confuse IPython):: |
|
548 | 548 | |
|
549 | 549 | In [4]: zip (1,2,3),(4,5,6) # won't work |
|
550 | 550 | |
|
551 | 551 | but this will work:: |
|
552 | 552 | |
|
553 | 553 | In [5]: /zip (1,2,3),(4,5,6) |
|
554 | 554 | ------> zip ((1,2,3),(4,5,6)) |
|
555 | 555 | Out[5]: [(1, 4), (2, 5), (3, 6)] |
|
556 | 556 | |
|
557 | 557 | IPython tells you that it has altered your command line by displaying |
|
558 | 558 | the new command line preceded by ``--->``. |
|
559 | 559 | |
|
560 | 560 | You can force automatic quoting of a function's arguments by using ``,`` |
|
561 | 561 | or ``;`` as the first character of a line. For example:: |
|
562 | 562 | |
|
563 | 563 | In [1]: ,my_function /home/me # becomes my_function("/home/me") |
|
564 | 564 | |
|
565 | 565 | If you use ';' the whole argument is quoted as a single string, while ',' splits |
|
566 | 566 | on whitespace:: |
|
567 | 567 | |
|
568 | 568 | In [2]: ,my_function a b c # becomes my_function("a","b","c") |
|
569 | 569 | |
|
570 | 570 | In [3]: ;my_function a b c # becomes my_function("a b c") |
|
571 | 571 | |
|
572 | 572 | Note that the ',' or ';' MUST be the first character on the line! This |
|
573 | 573 | won't work:: |
|
574 | 574 | |
|
575 | 575 | In [4]: x = ,my_function /home/me # syntax error |
|
576 | 576 | |
|
577 | 577 | IPython as your default Python environment |
|
578 | 578 | ========================================== |
|
579 | 579 | |
|
580 | 580 | Python honors the environment variable :envvar:`PYTHONSTARTUP` and will |
|
581 | 581 | execute at startup the file referenced by this variable. If you put the |
|
582 | 582 | following code at the end of that file, then IPython will be your working |
|
583 | 583 | environment anytime you start Python:: |
|
584 | 584 | |
|
585 | 585 | import os, IPython |
|
586 | 586 | os.environ['PYTHONSTARTUP'] = '' # Prevent running this again |
|
587 | 587 | IPython.start_ipython() |
|
588 | 588 | raise SystemExit |
|
589 | 589 | |
|
590 | 590 | The ``raise SystemExit`` is needed to exit Python when |
|
591 | 591 | it finishes, otherwise you'll be back at the normal Python ``>>>`` |
|
592 | 592 | prompt. |
|
593 | 593 | |
|
594 | 594 | This is probably useful to developers who manage multiple Python |
|
595 | 595 | versions and don't want to have correspondingly multiple IPython |
|
596 | 596 | versions. Note that in this mode, there is no way to pass IPython any |
|
597 | 597 | command-line options, as those are trapped first by Python itself. |
|
598 | 598 | |
|
599 | 599 | .. _Embedding: |
|
600 | 600 | |
|
601 | 601 | Embedding IPython |
|
602 | 602 | ================= |
|
603 | 603 | |
|
604 | 604 | You can start a regular IPython session with |
|
605 | 605 | |
|
606 | 606 | .. sourcecode:: python |
|
607 | 607 | |
|
608 | 608 | import IPython |
|
609 | 609 | IPython.start_ipython(argv=[]) |
|
610 | 610 | |
|
611 | 611 | at any point in your program. This will load IPython configuration, |
|
612 | 612 | startup files, and everything, just as if it were a normal IPython session. |
|
613 | 613 | For information on setting configuration options when running IPython from |
|
614 | 614 | python, see :ref:`configure_start_ipython`. |
|
615 | 615 | |
|
616 | 616 | It is also possible to embed an IPython shell in a namespace in your Python |
|
617 | 617 | code. This allows you to evaluate dynamically the state of your code, operate |
|
618 | 618 | with your variables, analyze them, etc. For example, if you run the following |
|
619 | 619 | code snippet:: |
|
620 | 620 | |
|
621 | 621 | import IPython |
|
622 | 622 | |
|
623 | 623 | a = 42 |
|
624 | 624 | IPython.embed() |
|
625 | 625 | |
|
626 | 626 | and within the IPython shell, you reassign `a` to `23` to do further testing of |
|
627 | 627 | some sort, you can then exit:: |
|
628 | 628 | |
|
629 | 629 | >>> IPython.embed() |
|
630 | 630 | Python 3.6.2 (default, Jul 17 2017, 16:44:45) |
|
631 | 631 | Type 'copyright', 'credits' or 'license' for more information |
|
632 | 632 | IPython 6.2.0.dev -- An enhanced Interactive Python. Type '?' for help. |
|
633 | 633 | |
|
634 | 634 | In [1]: a = 23 |
|
635 | 635 | |
|
636 | 636 | In [2]: exit() |
|
637 | 637 | |
|
638 | 638 | Once you exit and print `a`, the value 23 will be shown:: |
|
639 | 639 | |
|
640 | 640 | |
|
641 | 641 | In: print(a) |
|
642 | 642 | 23 |
|
643 | 643 | |
|
644 | 644 | It's important to note that the code run in the embedded IPython shell will |
|
645 | 645 | *not* change the state of your code and variables, **unless** the shell is |
|
646 | 646 | contained within the global namespace. In the above example, `a` is changed |
|
647 | 647 | because this is true. |
|
648 | 648 | |
|
649 | 649 | To further exemplify this, consider the following example:: |
|
650 | 650 | |
|
651 | 651 | import IPython |
|
652 | 652 | def do(): |
|
653 | 653 | a = 42 |
|
654 | 654 | print(a) |
|
655 | 655 | IPython.embed() |
|
656 | 656 | print(a) |
|
657 | 657 | |
|
658 | 658 | Now if call the function and complete the state changes as we did above, the |
|
659 | 659 | value `42` will be printed. Again, this is because it's not in the global |
|
660 | 660 | namespace:: |
|
661 | 661 | |
|
662 | 662 | do() |
|
663 | 663 | |
|
664 | 664 | Running a file with the above code can lead to the following session:: |
|
665 | 665 | |
|
666 | 666 | >>> do() |
|
667 | 667 | 42 |
|
668 | 668 | Python 3.6.2 (default, Jul 17 2017, 16:44:45) |
|
669 | 669 | Type 'copyright', 'credits' or 'license' for more information |
|
670 | 670 | IPython 6.2.0.dev -- An enhanced Interactive Python. Type '?' for help. |
|
671 | 671 | |
|
672 | 672 | In [1]: a = 23 |
|
673 | 673 | |
|
674 | 674 | In [2]: exit() |
|
675 | 675 | 42 |
|
676 | 676 | |
|
677 | 677 | .. note:: |
|
678 | 678 | |
|
679 | 679 | At present, embedding IPython cannot be done from inside IPython. |
|
680 | 680 | Run the code samples below outside IPython. |
|
681 | 681 | |
|
682 | 682 | This feature allows you to easily have a fully functional python |
|
683 | 683 | environment for doing object introspection anywhere in your code with a |
|
684 | 684 | simple function call. In some cases a simple print statement is enough, |
|
685 | 685 | but if you need to do more detailed analysis of a code fragment this |
|
686 | 686 | feature can be very valuable. |
|
687 | 687 | |
|
688 | 688 | It can also be useful in scientific computing situations where it is |
|
689 | 689 | common to need to do some automatic, computationally intensive part and |
|
690 | 690 | then stop to look at data, plots, etc. |
|
691 | 691 | Opening an IPython instance will give you full access to your data and |
|
692 | 692 | functions, and you can resume program execution once you are done with |
|
693 | 693 | the interactive part (perhaps to stop again later, as many times as |
|
694 | 694 | needed). |
|
695 | 695 | |
|
696 | 696 | The following code snippet is the bare minimum you need to include in |
|
697 | 697 | your Python programs for this to work (detailed examples follow later):: |
|
698 | 698 | |
|
699 | 699 | from IPython import embed |
|
700 | 700 | |
|
701 | 701 | embed() # this call anywhere in your program will start IPython |
|
702 | 702 | |
|
703 | 703 | You can also embed an IPython *kernel*, for use with qtconsole, etc. via |
|
704 | 704 | ``IPython.embed_kernel()``. This should work the same way, but you can |
|
705 | 705 | connect an external frontend (``ipython qtconsole`` or ``ipython console``), |
|
706 | 706 | rather than interacting with it in the terminal. |
|
707 | 707 | |
|
708 | 708 | You can run embedded instances even in code which is itself being run at |
|
709 | 709 | the IPython interactive prompt with '%run <filename>'. Since it's easy |
|
710 | 710 | to get lost as to where you are (in your top-level IPython or in your |
|
711 | 711 | embedded one), it's a good idea in such cases to set the in/out prompts |
|
712 | 712 | to something different for the embedded instances. The code examples |
|
713 | 713 | below illustrate this. |
|
714 | 714 | |
|
715 | 715 | You can also have multiple IPython instances in your program and open |
|
716 | 716 | them separately, for example with different options for data |
|
717 | 717 | presentation. If you close and open the same instance multiple times, |
|
718 | 718 | its prompt counters simply continue from each execution to the next. |
|
719 | 719 | |
|
720 | 720 | Please look at the docstrings in the :mod:`~IPython.frontend.terminal.embed` |
|
721 | 721 | module for more details on the use of this system. |
|
722 | 722 | |
|
723 | 723 | The following sample file illustrating how to use the embedding |
|
724 | 724 | functionality is provided in the examples directory as embed_class_long.py. |
|
725 | 725 | It should be fairly self-explanatory: |
|
726 | 726 | |
|
727 | 727 | .. literalinclude:: ../../../examples/Embedding/embed_class_long.py |
|
728 | 728 | :language: python |
|
729 | 729 | |
|
730 | 730 | Once you understand how the system functions, you can use the following |
|
731 | 731 | code fragments in your programs which are ready for cut and paste: |
|
732 | 732 | |
|
733 | 733 | .. literalinclude:: ../../../examples/Embedding/embed_class_short.py |
|
734 | 734 | :language: python |
|
735 | 735 | |
|
736 | 736 | Using the Python debugger (pdb) |
|
737 | 737 | =============================== |
|
738 | 738 | |
|
739 | 739 | Running entire programs via pdb |
|
740 | 740 | ------------------------------- |
|
741 | 741 | |
|
742 | 742 | pdb, the Python debugger, is a powerful interactive debugger which |
|
743 | 743 | allows you to step through code, set breakpoints, watch variables, |
|
744 | 744 | etc. IPython makes it very easy to start any script under the control |
|
745 | 745 | of pdb, regardless of whether you have wrapped it into a 'main()' |
|
746 | 746 | function or not. For this, simply type ``%run -d myscript`` at an |
|
747 | 747 | IPython prompt. See the :magic:`run` command's documentation for more details, including |
|
748 | 748 | how to control where pdb will stop execution first. |
|
749 | 749 | |
|
750 | 750 | For more information on the use of the pdb debugger, see :ref:`debugger-commands` |
|
751 | 751 | in the Python documentation. |
|
752 | 752 | |
|
753 | 753 | IPython extends the debugger with a few useful additions, like coloring of |
|
754 | 754 | tracebacks. The debugger will adopt the color scheme selected for IPython. |
|
755 | 755 | |
|
756 | 756 | The ``where`` command has also been extended to take as argument the number of |
|
757 | 757 | context line to show. This allows to a many line of context on shallow stack trace: |
|
758 | 758 | |
|
759 | 759 | .. code:: |
|
760 | 760 | |
|
761 | 761 | In [5]: def foo(x): |
|
762 | 762 | ...: 1 |
|
763 | 763 | ...: 2 |
|
764 | 764 | ...: 3 |
|
765 | 765 | ...: return 1/x+foo(x-1) |
|
766 | 766 | ...: 5 |
|
767 | 767 | ...: 6 |
|
768 | 768 | ...: 7 |
|
769 | 769 | ...: |
|
770 | 770 | |
|
771 | 771 | In[6]: foo(1) |
|
772 | 772 | # ... |
|
773 | 773 | ipdb> where 8 |
|
774 | 774 | <ipython-input-6-9e45007b2b59>(1)<module> |
|
775 | 775 | ----> 1 foo(1) |
|
776 | 776 | |
|
777 | 777 | <ipython-input-5-7baadc3d1465>(5)foo() |
|
778 | 778 | 1 def foo(x): |
|
779 | 779 | 2 1 |
|
780 | 780 | 3 2 |
|
781 | 781 | 4 3 |
|
782 | 782 | ----> 5 return 1/x+foo(x-1) |
|
783 | 783 | 6 5 |
|
784 | 784 | 7 6 |
|
785 | 785 | 8 7 |
|
786 | 786 | |
|
787 | 787 | > <ipython-input-5-7baadc3d1465>(5)foo() |
|
788 | 788 | 1 def foo(x): |
|
789 | 789 | 2 1 |
|
790 | 790 | 3 2 |
|
791 | 791 | 4 3 |
|
792 | 792 | ----> 5 return 1/x+foo(x-1) |
|
793 | 793 | 6 5 |
|
794 | 794 | 7 6 |
|
795 | 795 | 8 7 |
|
796 | 796 | |
|
797 | 797 | |
|
798 | 798 | And less context on shallower Stack Trace: |
|
799 | 799 | |
|
800 | 800 | .. code:: |
|
801 | 801 | |
|
802 | 802 | ipdb> where 1 |
|
803 | 803 | <ipython-input-13-afa180a57233>(1)<module> |
|
804 | 804 | ----> 1 foo(7) |
|
805 | 805 | |
|
806 | 806 | <ipython-input-5-7baadc3d1465>(5)foo() |
|
807 | 807 | ----> 5 return 1/x+foo(x-1) |
|
808 | 808 | |
|
809 | 809 | <ipython-input-5-7baadc3d1465>(5)foo() |
|
810 | 810 | ----> 5 return 1/x+foo(x-1) |
|
811 | 811 | |
|
812 | 812 | <ipython-input-5-7baadc3d1465>(5)foo() |
|
813 | 813 | ----> 5 return 1/x+foo(x-1) |
|
814 | 814 | |
|
815 | 815 | <ipython-input-5-7baadc3d1465>(5)foo() |
|
816 | 816 | ----> 5 return 1/x+foo(x-1) |
|
817 | 817 | |
|
818 | 818 | |
|
819 | 819 | Post-mortem debugging |
|
820 | 820 | --------------------- |
|
821 | 821 | |
|
822 | 822 | Going into a debugger when an exception occurs can be |
|
823 | 823 | extremely useful in order to find the origin of subtle bugs, because pdb |
|
824 | 824 | opens up at the point in your code which triggered the exception, and |
|
825 | 825 | while your program is at this point 'dead', all the data is still |
|
826 | 826 | available and you can walk up and down the stack frame and understand |
|
827 | 827 | the origin of the problem. |
|
828 | 828 | |
|
829 | 829 | You can use the :magic:`debug` magic after an exception has occurred to start |
|
830 | 830 | post-mortem debugging. IPython can also call debugger every time your code |
|
831 | 831 | triggers an uncaught exception. This feature can be toggled with the :magic:`pdb` magic |
|
832 | 832 | command, or you can start IPython with the ``--pdb`` option. |
|
833 | 833 | |
|
834 | 834 | For a post-mortem debugger in your programs outside IPython, |
|
835 | 835 | put the following lines toward the top of your 'main' routine:: |
|
836 | 836 | |
|
837 | 837 | import sys |
|
838 | 838 | from IPython.core import ultratb |
|
839 | 839 | sys.excepthook = ultratb.FormattedTB(mode='Verbose', |
|
840 | 840 | color_scheme='Linux', call_pdb=1) |
|
841 | 841 | |
|
842 | 842 | The mode keyword can be either 'Verbose' or 'Plain', giving either very |
|
843 | 843 | detailed or normal tracebacks respectively. The color_scheme keyword can |
|
844 | 844 | be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same |
|
845 | 845 | options which can be set in IPython with ``--colors`` and ``--xmode``. |
|
846 | 846 | |
|
847 | 847 | This will give any of your programs detailed, colored tracebacks with |
|
848 | 848 | automatic invocation of pdb. |
|
849 | 849 | |
|
850 | 850 | .. _pasting_with_prompts: |
|
851 | 851 | |
|
852 | 852 | Pasting of code starting with Python or IPython prompts |
|
853 | 853 | ======================================================= |
|
854 | 854 | |
|
855 | 855 | IPython is smart enough to filter out input prompts, be they plain Python ones |
|
856 | 856 | (``>>>`` and ``...``) or IPython ones (``In [N]:`` and ``...:``). You can |
|
857 | 857 | therefore copy and paste from existing interactive sessions without worry. |
|
858 | 858 | |
|
859 | 859 | The following is a 'screenshot' of how things work, copying an example from the |
|
860 | 860 | standard Python tutorial:: |
|
861 | 861 | |
|
862 | 862 | In [1]: >>> # Fibonacci series: |
|
863 | 863 | |
|
864 | 864 | In [2]: ... # the sum of two elements defines the next |
|
865 | 865 | |
|
866 | 866 | In [3]: ... a, b = 0, 1 |
|
867 | 867 | |
|
868 | 868 | In [4]: >>> while b < 10: |
|
869 | 869 | ...: ... print(b) |
|
870 | 870 | ...: ... a, b = b, a+b |
|
871 | 871 | ...: |
|
872 | 872 | 1 |
|
873 | 873 | 1 |
|
874 | 874 | 2 |
|
875 | 875 | 3 |
|
876 | 876 | 5 |
|
877 | 877 | 8 |
|
878 | 878 | |
|
879 | 879 | And pasting from IPython sessions works equally well:: |
|
880 | 880 | |
|
881 | 881 | In [1]: In [5]: def f(x): |
|
882 | 882 | ...: ...: "A simple function" |
|
883 | 883 | ...: ...: return x**2 |
|
884 | 884 | ...: ...: |
|
885 | 885 | |
|
886 | 886 | In [2]: f(3) |
|
887 | 887 | Out[2]: 9 |
|
888 | 888 | |
|
889 | 889 | .. _gui_support: |
|
890 | 890 | |
|
891 | 891 | GUI event loop support |
|
892 | 892 | ====================== |
|
893 | 893 | |
|
894 | 894 | IPython has excellent support for working interactively with Graphical User |
|
895 |
Interface (GUI) toolkits, such as wxPython, PyQt |
|
|
895 | Interface (GUI) toolkits, such as wxPython, PyQt/PySide, PyGTK and Tk. This is | |
|
896 | 896 | implemented by running the toolkit's event loop while IPython is waiting for |
|
897 | 897 | input. |
|
898 | 898 | |
|
899 | 899 | For users, enabling GUI event loop integration is simple. You simple use the |
|
900 | 900 | :magic:`gui` magic as follows:: |
|
901 | 901 | |
|
902 | 902 | %gui [GUINAME] |
|
903 | 903 | |
|
904 | 904 | With no arguments, ``%gui`` removes all GUI support. Valid ``GUINAME`` |
|
905 | arguments include ``wx``, ``qt``, ``qt5``, ``gtk``, ``gtk3`` ``gtk4``, and | |
|
905 | arguments include ``wx``, ``qt``, ``qt5``, ``qt6``, ``gtk``, ``gtk3`` ``gtk4``, and | |
|
906 | 906 | ``tk``. |
|
907 | 907 | |
|
908 | 908 | Thus, to use wxPython interactively and create a running :class:`wx.App` |
|
909 | 909 | object, do:: |
|
910 | 910 | |
|
911 | 911 | %gui wx |
|
912 | 912 | |
|
913 | 913 | You can also start IPython with an event loop set up using the `--gui` |
|
914 | 914 | flag:: |
|
915 | 915 | |
|
916 | 916 | $ ipython --gui=qt |
|
917 | 917 | |
|
918 | 918 | For information on IPython's matplotlib_ integration (and the ``matplotlib`` |
|
919 | 919 | mode) see :ref:`this section <matplotlib_support>`. |
|
920 | 920 | |
|
921 | 921 | For developers that want to integrate additional event loops with IPython, see |
|
922 | 922 | :doc:`/config/eventloops`. |
|
923 | 923 | |
|
924 | 924 | When running inside IPython with an integrated event loop, a GUI application |
|
925 | 925 | should *not* start its own event loop. This means that applications that are |
|
926 | 926 | meant to be used both |
|
927 | 927 | in IPython and as standalone apps need to have special code to detects how the |
|
928 | 928 | application is being run. We highly recommend using IPython's support for this. |
|
929 | 929 | Since the details vary slightly between toolkits, we point you to the various |
|
930 | 930 | examples in our source directory :file:`examples/IPython Kernel/gui/` that |
|
931 | 931 | demonstrate these capabilities. |
|
932 | 932 | |
|
933 | 933 | PyQt and PySide |
|
934 | 934 | --------------- |
|
935 | 935 | |
|
936 | 936 | .. attempt at explanation of the complete mess that is Qt support |
|
937 | 937 | |
|
938 | 938 | When you use ``--gui=qt`` or ``--matplotlib=qt``, IPython can work with either |
|
939 | PyQt4 or PySide. There are three options for configuration here, because | |
|
940 | PyQt4 has two APIs for QString and QVariant: v1, which is the default on | |
|
941 | Python 2, and the more natural v2, which is the only API supported by PySide. | |
|
942 | v2 is also the default for PyQt4 on Python 3. IPython's code for the QtConsole | |
|
943 | uses v2, but you can still use any interface in your code, since the | |
|
944 | Qt frontend is in a different process. | |
|
945 | ||
|
946 | The default will be to import PyQt4 without configuration of the APIs, thus | |
|
947 | matching what most applications would expect. It will fall back to PySide if | |
|
948 | PyQt4 is unavailable. | |
|
939 | PyQt or PySide. ``qt`` implies "use the latest version available", and it favors | |
|
940 | PyQt over PySide. To request a specific version, use ``qt5`` or ``qt6``. Note that | |
|
941 | Qt4 is not supported with the ``--gui`` switch (and has not been for some time now). | |
|
949 | 942 | |
|
950 | 943 | If specified, IPython will respect the environment variable ``QT_API`` used |
|
951 | 944 | by ETS. ETS 4.0 also works with both PyQt4 and PySide, but it requires |
|
952 | 945 | PyQt4 to use its v2 API. So if ``QT_API=pyside`` PySide will be used, |
|
953 | 946 | and if ``QT_API=pyqt`` then PyQt4 will be used *with the v2 API* for |
|
954 | 947 | QString and QVariant, so ETS codes like MayaVi will also work with IPython. |
|
955 | 948 | |
|
956 | 949 | If you launch IPython in matplotlib mode with ``ipython --matplotlib=qt``, |
|
957 | 950 | then IPython will ask matplotlib which Qt library to use (only if QT_API is |
|
958 | 951 | *not set*), via the 'backend.qt4' rcParam. If matplotlib is version 1.0.1 or |
|
959 | 952 | older, then IPython will always use PyQt4 without setting the v2 APIs, since |
|
960 | 953 | neither v2 PyQt nor PySide work. |
|
961 | 954 | |
|
962 | 955 | .. warning:: |
|
963 | 956 | |
|
964 | 957 | Note that this means for ETS 4 to work with PyQt4, ``QT_API`` *must* be set |
|
965 | 958 | to work with IPython's qt integration, because otherwise PyQt4 will be |
|
966 | 959 | loaded in an incompatible mode. |
|
967 | 960 | |
|
968 | 961 | It also means that you must *not* have ``QT_API`` set if you want to |
|
969 | 962 | use ``--gui=qt`` with code that requires PyQt4 API v1. |
|
970 | 963 | |
|
971 | 964 | |
|
972 | 965 | .. _matplotlib_support: |
|
973 | 966 | |
|
974 | 967 | Plotting with matplotlib |
|
975 | 968 | ======================== |
|
976 | 969 | |
|
977 | 970 | matplotlib_ provides high quality 2D and 3D plotting for Python. matplotlib_ |
|
978 | 971 | can produce plots on screen using a variety of GUI toolkits, including Tk, |
|
979 | 972 | PyGTK, PyQt4 and wxPython. It also provides a number of commands useful for |
|
980 | 973 | scientific computing, all with a syntax compatible with that of the popular |
|
981 | 974 | Matlab program. |
|
982 | 975 | |
|
983 | 976 | To start IPython with matplotlib support, use the ``--matplotlib`` switch. If |
|
984 | 977 | IPython is already running, you can run the :magic:`matplotlib` magic. If no |
|
985 | 978 | arguments are given, IPython will automatically detect your choice of |
|
986 | 979 | matplotlib backend. You can also request a specific backend with |
|
987 | 980 | ``%matplotlib backend``, where ``backend`` must be one of: 'tk', 'qt', 'wx', |
|
988 | 981 | 'gtk', 'osx'. In the web notebook and Qt console, 'inline' is also a valid |
|
989 | 982 | backend value, which produces static figures inlined inside the application |
|
990 | 983 | window instead of matplotlib's interactive figures that live in separate |
|
991 | 984 | windows. |
|
992 | 985 | |
|
993 | 986 | .. _interactive_demos: |
|
994 | 987 | |
|
995 | 988 | Interactive demos with IPython |
|
996 | 989 | ============================== |
|
997 | 990 | |
|
998 | 991 | IPython ships with a basic system for running scripts interactively in |
|
999 | 992 | sections, useful when presenting code to audiences. A few tags embedded |
|
1000 | 993 | in comments (so that the script remains valid Python code) divide a file |
|
1001 | 994 | into separate blocks, and the demo can be run one block at a time, with |
|
1002 | 995 | IPython printing (with syntax highlighting) the block before executing |
|
1003 | 996 | it, and returning to the interactive prompt after each block. The |
|
1004 | 997 | interactive namespace is updated after each block is run with the |
|
1005 | 998 | contents of the demo's namespace. |
|
1006 | 999 | |
|
1007 | 1000 | This allows you to show a piece of code, run it and then execute |
|
1008 | 1001 | interactively commands based on the variables just created. Once you |
|
1009 | 1002 | want to continue, you simply execute the next block of the demo. The |
|
1010 | 1003 | following listing shows the markup necessary for dividing a script into |
|
1011 | 1004 | sections for execution as a demo: |
|
1012 | 1005 | |
|
1013 | 1006 | .. literalinclude:: ../../../examples/IPython Kernel/example-demo.py |
|
1014 | 1007 | :language: python |
|
1015 | 1008 | |
|
1016 | 1009 | In order to run a file as a demo, you must first make a Demo object out |
|
1017 | 1010 | of it. If the file is named myscript.py, the following code will make a |
|
1018 | 1011 | demo:: |
|
1019 | 1012 | |
|
1020 | 1013 | from IPython.lib.demo import Demo |
|
1021 | 1014 | |
|
1022 | 1015 | mydemo = Demo('myscript.py') |
|
1023 | 1016 | |
|
1024 | 1017 | This creates the mydemo object, whose blocks you run one at a time by |
|
1025 | 1018 | simply calling the object with no arguments. Then call it to run each step |
|
1026 | 1019 | of the demo:: |
|
1027 | 1020 | |
|
1028 | 1021 | mydemo() |
|
1029 | 1022 | |
|
1030 | 1023 | Demo objects can be |
|
1031 | 1024 | restarted, you can move forward or back skipping blocks, re-execute the |
|
1032 | 1025 | last block, etc. See the :mod:`IPython.lib.demo` module and the |
|
1033 | 1026 | :class:`~IPython.lib.demo.Demo` class for details. |
|
1034 | 1027 | |
|
1035 | 1028 | Limitations: These demos are limited to |
|
1036 | 1029 | fairly simple uses. In particular, you cannot break up sections within |
|
1037 | 1030 | indented code (loops, if statements, function definitions, etc.) |
|
1038 | 1031 | Supporting something like this would basically require tracking the |
|
1039 | 1032 | internal execution state of the Python interpreter, so only top-level |
|
1040 | 1033 | divisions are allowed. If you want to be able to open an IPython |
|
1041 | 1034 | instance at an arbitrary point in a program, you can use IPython's |
|
1042 | 1035 | :ref:`embedding facilities <Embedding>`. |
|
1043 | 1036 | |
|
1044 | 1037 | .. include:: ../links.txt |
General Comments 0
You need to be logged in to leave comments.
Login now