##// END OF EJS Templates
Small fixes as per @certik's review.
Fernando Perez -
Show More
@@ -1,128 +1,128 b''
1 1 """Implementation of magic functions that control various automatic behaviors.
2 2 """
3 3 #-----------------------------------------------------------------------------
4 4 # Copyright (c) 2012 The IPython Development Team.
5 5 #
6 6 # Distributed under the terms of the Modified BSD License.
7 7 #
8 8 # The full license is in the file COPYING.txt, distributed with this software.
9 9 #-----------------------------------------------------------------------------
10 10
11 11 #-----------------------------------------------------------------------------
12 12 # Imports
13 13 #-----------------------------------------------------------------------------
14 14
15 15 # Our own packages
16 16 from IPython.core.magic import Bunch, Magics, magics_class, line_magic
17 17 from IPython.testing.skipdoctest import skip_doctest
18 18 from IPython.utils.warn import error
19 19
20 20 #-----------------------------------------------------------------------------
21 21 # Magic implementation classes
22 22 #-----------------------------------------------------------------------------
23 23
24 24 @magics_class
25 25 class AutoMagics(Magics):
26 26 """Magics that control various autoX behaviors."""
27 27
28 28 def __init__(self, shell):
29 29 super(AutoMagics, self).__init__(shell)
30 30 # namespace for holding state we may need
31 31 self._magic_state = Bunch()
32 32
33 33 @line_magic
34 34 def automagic(self, parameter_s=''):
35 35 """Make magic functions callable without having to type the initial %.
36 36
37 37 Without argumentsl toggles on/off (when off, you must call it as
38 38 %automagic, of course). With arguments it sets the value, and you can
39 39 use any of (case insensitive):
40 40
41 41 - on, 1, True: to activate
42 42
43 43 - off, 0, False: to deactivate.
44 44
45 45 Note that magic functions have lowest priority, so if there's a
46 46 variable whose name collides with that of a magic fn, automagic won't
47 47 work for that function (you get the variable instead). However, if you
48 48 delete the variable (del var), the previously shadowed magic function
49 49 becomes visible to automagic again."""
50 50
51 51 arg = parameter_s.lower()
52 52 mman = self.shell.magics_manager
53 53 if arg in ('on', '1', 'true'):
54 54 val = True
55 55 elif arg in ('off', '0', 'false'):
56 56 val = False
57 57 else:
58 58 val = not mman.auto_magic
59 59 mman.auto_magic = val
60 60 print '\n' + self.shell.magics_manager.auto_status()
61 61
62 62 @skip_doctest
63 63 @line_magic
64 64 def autocall(self, parameter_s=''):
65 65 """Make functions callable without having to type parentheses.
66 66
67 67 Usage:
68 68
69 69 %autocall [mode]
70 70
71 71 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
72 72 value is toggled on and off (remembering the previous state).
73 73
74 74 In more detail, these values mean:
75 75
76 76 0 -> fully disabled
77 77
78 78 1 -> active, but do not apply if there are no arguments on the line.
79 79
80 80 In this mode, you get::
81 81
82 82 In [1]: callable
83 83 Out[1]: <built-in function callable>
84 84
85 85 In [2]: callable 'hello'
86 86 ------> callable('hello')
87 87 Out[2]: False
88 88
89 89 2 -> Active always. Even if no arguments are present, the callable
90 90 object is called::
91 91
92 92 In [2]: float
93 93 ------> float()
94 94 Out[2]: 0.0
95 95
96 96 Note that even with autocall off, you can still use '/' at the start of
97 97 a line to treat the first argument on the command line as a function
98 98 and add parentheses to it::
99 99
100 100 In [8]: /str 43
101 101 ------> str(43)
102 102 Out[8]: '43'
103 103
104 104 # all-random (note for auto-testing)
105 105 """
106 106
107 107 if parameter_s:
108 108 arg = int(parameter_s)
109 109 else:
110 110 arg = 'toggle'
111 111
112 if not arg in (0, 1, 2,'toggle'):
112 if not arg in (0, 1, 2, 'toggle'):
113 113 error('Valid modes: (0->Off, 1->Smart, 2->Full')
114 114 return
115 115
116 116 if arg in (0, 1, 2):
117 117 self.shell.autocall = arg
118 118 else: # toggle
119 119 if self.shell.autocall:
120 120 self._magic_state.autocall_save = self.shell.autocall
121 121 self.shell.autocall = 0
122 122 else:
123 123 try:
124 124 self.shell.autocall = self._magic_state.autocall_save
125 125 except AttributeError:
126 126 self.shell.autocall = self._magic_state.autocall_save = 1
127 127
128 128 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
@@ -1,513 +1,513 b''
1 1 """Implementation of basic magic functions.
2 2 """
3 3 #-----------------------------------------------------------------------------
4 4 # Copyright (c) 2012 The IPython Development Team.
5 5 #
6 6 # Distributed under the terms of the Modified BSD License.
7 7 #
8 8 # The full license is in the file COPYING.txt, distributed with this software.
9 9 #-----------------------------------------------------------------------------
10 10
11 11 #-----------------------------------------------------------------------------
12 12 # Imports
13 13 #-----------------------------------------------------------------------------
14 14 from __future__ import print_function
15 15
16 16 # Stdlib
17 17 import io
18 18 import sys
19 19 from pprint import pformat
20 20
21 21 # Our own packages
22 22 from IPython.core.error import UsageError
23 23 from IPython.core.magic import Magics, magics_class, line_magic
24 24 from IPython.core.prefilter import ESC_MAGIC
25 25 from IPython.utils.text import format_screen
26 26 from IPython.core import magic_arguments, page
27 27 from IPython.testing.skipdoctest import skip_doctest
28 28 from IPython.utils.ipstruct import Struct
29 29 from IPython.utils.path import unquote_filename
30 30 from IPython.utils.warn import warn, error
31 31
32 32 #-----------------------------------------------------------------------------
33 33 # Magics class implementation
34 34 #-----------------------------------------------------------------------------
35 35
36 36 @magics_class
37 37 class BasicMagics(Magics):
38 38 """Magics that provide central IPython functionality.
39 39
40 40 These are various magics that don't fit into specific categories but that
41 41 are all part of the base 'IPython experience'."""
42 42
43 43 def _lsmagic(self):
44 44 mesc = ESC_MAGIC
45 45 cesc = mesc*2
46 46 mman = self.shell.magics_manager
47 47 magics = mman.lsmagic()
48 48 out = ['Available line magics:',
49 49 mesc + (' '+mesc).join(magics['line']),
50 50 '',
51 51 'Available cell magics:',
52 52 cesc + (' '+cesc).join(magics['cell']),
53 53 '',
54 54 mman.auto_status()]
55 55 return '\n'.join(out)
56 56
57 57 @line_magic
58 58 def lsmagic(self, parameter_s=''):
59 59 """List currently available magic functions."""
60 60 print(self._lsmagic())
61 61
62 62 @line_magic
63 63 def magic(self, parameter_s=''):
64 64 """Print information about the magic function system.
65 65
66 66 Supported formats: -latex, -brief, -rest
67 67 """
68 68
69 69 mode = ''
70 70 try:
71 71 mode = parameter_s.split()[0][1:]
72 72 if mode == 'rest':
73 73 rest_docs = []
74 except:
74 except IndexError:
75 75 pass
76 76
77 77 magic_docs = []
78 78 escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC*2)
79 79 magics = self.shell.magics_manager.magics
80 80
81 81 for mtype in ('line', 'cell'):
82 82 escape = escapes[mtype]
83 83 for fname, fn in magics[mtype].iteritems():
84 84
85 85 if mode == 'brief':
86 86 # only first line
87 87 if fn.__doc__:
88 88 fndoc = fn.__doc__.split('\n',1)[0]
89 89 else:
90 90 fndoc = 'No documentation'
91 91 else:
92 92 if fn.__doc__:
93 93 fndoc = fn.__doc__.rstrip()
94 94 else:
95 95 fndoc = 'No documentation'
96 96
97 97 if mode == 'rest':
98 98 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %
99 99 (escape, fname, fndoc))
100 100 else:
101 101 magic_docs.append('%s%s:\n\t%s\n' %
102 102 (escape, fname, fndoc))
103 103
104 104 magic_docs = ''.join(magic_docs)
105 105
106 106 if mode == 'rest':
107 107 return "".join(rest_docs)
108 108
109 109 if mode == 'latex':
110 110 print(self.format_latex(magic_docs))
111 111 return
112 112 else:
113 113 magic_docs = format_screen(magic_docs)
114 114 if mode == 'brief':
115 115 return magic_docs
116 116
117 117 out = ["""
118 118 IPython's 'magic' functions
119 119 ===========================
120 120
121 121 The magic function system provides a series of functions which allow you to
122 122 control the behavior of IPython itself, plus a lot of system-type
123 123 features. All these functions are prefixed with a % character, but parameters
124 124 are given without parentheses or quotes.
125 125
126 126 NOTE: If you have 'automagic' enabled (via the command line option or with the
127 127 %automagic function), you don't need to type in the % explicitly. By default,
128 128 IPython ships with automagic on, so you should only rarely need the % escape.
129 129
130 130 Example: typing '%cd mydir' (without the quotes) changes you working directory
131 131 to 'mydir', if it exists.
132 132
133 133 For a list of the available magic functions, use %lsmagic. For a description
134 134 of any of them, type %magic_name?, e.g. '%cd?'.
135 135
136 136 Currently the magic system has the following functions:""",
137 137 magic_docs,
138 138 "Summary of magic functions (from %slsmagic):",
139 139 self._lsmagic(),
140 140 ]
141 141 page.page('\n'.join(out))
142 142
143 143
144 144 @line_magic
145 145 def page(self, parameter_s=''):
146 146 """Pretty print the object and display it through a pager.
147 147
148 148 %page [options] OBJECT
149 149
150 150 If no object is given, use _ (last output).
151 151
152 152 Options:
153 153
154 154 -r: page str(object), don't pretty-print it."""
155 155
156 156 # After a function contributed by Olivier Aubert, slightly modified.
157 157
158 158 # Process options/args
159 159 opts, args = self.parse_options(parameter_s, 'r')
160 160 raw = 'r' in opts
161 161
162 162 oname = args and args or '_'
163 163 info = self._ofind(oname)
164 164 if info['found']:
165 165 txt = (raw and str or pformat)( info['obj'] )
166 166 page.page(txt)
167 167 else:
168 168 print('Object `%s` not found' % oname)
169 169
170 170 @line_magic
171 171 def profile(self, parameter_s=''):
172 172 """Print your currently active IPython profile."""
173 173 from IPython.core.application import BaseIPythonApplication
174 174 if BaseIPythonApplication.initialized():
175 175 print(BaseIPythonApplication.instance().profile)
176 176 else:
177 177 error("profile is an application-level value, but you don't appear to be in an IPython application")
178 178
179 179 @line_magic
180 180 def pprint(self, parameter_s=''):
181 181 """Toggle pretty printing on/off."""
182 182 ptformatter = self.shell.display_formatter.formatters['text/plain']
183 183 ptformatter.pprint = bool(1 - ptformatter.pprint)
184 184 print('Pretty printing has been turned',
185 185 ['OFF','ON'][ptformatter.pprint])
186 186
187 187 @line_magic
188 188 def colors(self, parameter_s=''):
189 189 """Switch color scheme for prompts, info system and exception handlers.
190 190
191 191 Currently implemented schemes: NoColor, Linux, LightBG.
192 192
193 193 Color scheme names are not case-sensitive.
194 194
195 195 Examples
196 196 --------
197 197 To get a plain black and white terminal::
198 198
199 199 %colors nocolor
200 200 """
201 201 def color_switch_err(name):
202 202 warn('Error changing %s color schemes.\n%s' %
203 203 (name, sys.exc_info()[1]))
204 204
205 205
206 206 new_scheme = parameter_s.strip()
207 207 if not new_scheme:
208 208 raise UsageError(
209 209 "%colors: you must specify a color scheme. See '%colors?'")
210 210 return
211 211 # local shortcut
212 212 shell = self.shell
213 213
214 214 import IPython.utils.rlineimpl as readline
215 215
216 216 if not shell.colors_force and \
217 217 not readline.have_readline and sys.platform == "win32":
218 218 msg = """\
219 219 Proper color support under MS Windows requires the pyreadline library.
220 220 You can find it at:
221 221 http://ipython.org/pyreadline.html
222 222 Gary's readline needs the ctypes module, from:
223 223 http://starship.python.net/crew/theller/ctypes
224 224 (Note that ctypes is already part of Python versions 2.5 and newer).
225 225
226 226 Defaulting color scheme to 'NoColor'"""
227 227 new_scheme = 'NoColor'
228 228 warn(msg)
229 229
230 230 # readline option is 0
231 231 if not shell.colors_force and not shell.has_readline:
232 232 new_scheme = 'NoColor'
233 233
234 234 # Set prompt colors
235 235 try:
236 236 shell.prompt_manager.color_scheme = new_scheme
237 237 except:
238 238 color_switch_err('prompt')
239 239 else:
240 240 shell.colors = \
241 241 shell.prompt_manager.color_scheme_table.active_scheme_name
242 242 # Set exception colors
243 243 try:
244 244 shell.InteractiveTB.set_colors(scheme = new_scheme)
245 245 shell.SyntaxTB.set_colors(scheme = new_scheme)
246 246 except:
247 247 color_switch_err('exception')
248 248
249 249 # Set info (for 'object?') colors
250 250 if shell.color_info:
251 251 try:
252 252 shell.inspector.set_active_scheme(new_scheme)
253 253 except:
254 254 color_switch_err('object inspector')
255 255 else:
256 256 shell.inspector.set_active_scheme('NoColor')
257 257
258 258 @line_magic
259 259 def xmode(self, parameter_s=''):
260 260 """Switch modes for the exception handlers.
261 261
262 262 Valid modes: Plain, Context and Verbose.
263 263
264 264 If called without arguments, acts as a toggle."""
265 265
266 266 def xmode_switch_err(name):
267 267 warn('Error changing %s exception modes.\n%s' %
268 268 (name,sys.exc_info()[1]))
269 269
270 270 shell = self.shell
271 271 new_mode = parameter_s.strip().capitalize()
272 272 try:
273 273 shell.InteractiveTB.set_mode(mode=new_mode)
274 274 print('Exception reporting mode:',shell.InteractiveTB.mode)
275 275 except:
276 276 xmode_switch_err('user')
277 277
278 278 @line_magic
279 279 def quickref(self,arg):
280 280 """ Show a quick reference sheet """
281 281 from IPython.core.usage import quick_reference
282 282 qr = quick_reference + self.magic('-brief')
283 283 page.page(qr)
284 284
285 285 @line_magic
286 286 def doctest_mode(self, parameter_s=''):
287 287 """Toggle doctest mode on and off.
288 288
289 289 This mode is intended to make IPython behave as much as possible like a
290 290 plain Python shell, from the perspective of how its prompts, exceptions
291 291 and output look. This makes it easy to copy and paste parts of a
292 292 session into doctests. It does so by:
293 293
294 294 - Changing the prompts to the classic ``>>>`` ones.
295 295 - Changing the exception reporting mode to 'Plain'.
296 296 - Disabling pretty-printing of output.
297 297
298 298 Note that IPython also supports the pasting of code snippets that have
299 299 leading '>>>' and '...' prompts in them. This means that you can paste
300 300 doctests from files or docstrings (even if they have leading
301 301 whitespace), and the code will execute correctly. You can then use
302 302 '%history -t' to see the translated history; this will give you the
303 303 input after removal of all the leading prompts and whitespace, which
304 304 can be pasted back into an editor.
305 305
306 306 With these features, you can switch into this mode easily whenever you
307 307 need to do testing and changes to doctests, without having to leave
308 308 your existing IPython session.
309 309 """
310 310
311 311 # Shorthands
312 312 shell = self.shell
313 313 pm = shell.prompt_manager
314 314 meta = shell.meta
315 315 disp_formatter = self.shell.display_formatter
316 316 ptformatter = disp_formatter.formatters['text/plain']
317 317 # dstore is a data store kept in the instance metadata bag to track any
318 318 # changes we make, so we can undo them later.
319 319 dstore = meta.setdefault('doctest_mode',Struct())
320 320 save_dstore = dstore.setdefault
321 321
322 322 # save a few values we'll need to recover later
323 323 mode = save_dstore('mode',False)
324 324 save_dstore('rc_pprint',ptformatter.pprint)
325 325 save_dstore('xmode',shell.InteractiveTB.mode)
326 326 save_dstore('rc_separate_out',shell.separate_out)
327 327 save_dstore('rc_separate_out2',shell.separate_out2)
328 328 save_dstore('rc_prompts_pad_left',pm.justify)
329 329 save_dstore('rc_separate_in',shell.separate_in)
330 330 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
331 331 save_dstore('prompt_templates',(pm.in_template, pm.in2_template, pm.out_template))
332 332
333 333 if mode == False:
334 334 # turn on
335 335 pm.in_template = '>>> '
336 336 pm.in2_template = '... '
337 337 pm.out_template = ''
338 338
339 339 # Prompt separators like plain python
340 340 shell.separate_in = ''
341 341 shell.separate_out = ''
342 342 shell.separate_out2 = ''
343 343
344 344 pm.justify = False
345 345
346 346 ptformatter.pprint = False
347 347 disp_formatter.plain_text_only = True
348 348
349 349 shell.magic('xmode Plain')
350 350 else:
351 351 # turn off
352 352 pm.in_template, pm.in2_template, pm.out_template = dstore.prompt_templates
353 353
354 354 shell.separate_in = dstore.rc_separate_in
355 355
356 356 shell.separate_out = dstore.rc_separate_out
357 357 shell.separate_out2 = dstore.rc_separate_out2
358 358
359 359 pm.justify = dstore.rc_prompts_pad_left
360 360
361 361 ptformatter.pprint = dstore.rc_pprint
362 362 disp_formatter.plain_text_only = dstore.rc_plain_text_only
363 363
364 364 shell.magic('xmode ' + dstore.xmode)
365 365
366 366 # Store new mode and inform
367 367 dstore.mode = bool(1-int(mode))
368 368 mode_label = ['OFF','ON'][dstore.mode]
369 369 print('Doctest mode is:', mode_label)
370 370
371 371 @line_magic
372 372 def gui(self, parameter_s=''):
373 373 """Enable or disable IPython GUI event loop integration.
374 374
375 375 %gui [GUINAME]
376 376
377 377 This magic replaces IPython's threaded shells that were activated
378 378 using the (pylab/wthread/etc.) command line flags. GUI toolkits
379 379 can now be enabled at runtime and keyboard
380 380 interrupts should work without any problems. The following toolkits
381 381 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
382 382
383 383 %gui wx # enable wxPython event loop integration
384 384 %gui qt4|qt # enable PyQt4 event loop integration
385 385 %gui gtk # enable PyGTK event loop integration
386 386 %gui gtk3 # enable Gtk3 event loop integration
387 387 %gui tk # enable Tk event loop integration
388 388 %gui OSX # enable Cocoa event loop integration
389 389 # (requires %matplotlib 1.1)
390 390 %gui # disable all event loop integration
391 391
392 392 WARNING: after any of these has been called you can simply create
393 393 an application object, but DO NOT start the event loop yourself, as
394 394 we have already handled that.
395 395 """
396 396 opts, arg = self.parse_options(parameter_s, '')
397 397 if arg=='': arg = None
398 398 try:
399 399 return self.enable_gui(arg)
400 400 except Exception as e:
401 401 # print simple error message, rather than traceback if we can't
402 402 # hook up the GUI
403 403 error(str(e))
404 404
405 405 @skip_doctest
406 406 @line_magic
407 407 def precision(self, s=''):
408 408 """Set floating point precision for pretty printing.
409 409
410 410 Can set either integer precision or a format string.
411 411
412 412 If numpy has been imported and precision is an int,
413 413 numpy display precision will also be set, via ``numpy.set_printoptions``.
414 414
415 415 If no argument is given, defaults will be restored.
416 416
417 417 Examples
418 418 --------
419 419 ::
420 420
421 421 In [1]: from math import pi
422 422
423 423 In [2]: %precision 3
424 424 Out[2]: u'%.3f'
425 425
426 426 In [3]: pi
427 427 Out[3]: 3.142
428 428
429 429 In [4]: %precision %i
430 430 Out[4]: u'%i'
431 431
432 432 In [5]: pi
433 433 Out[5]: 3
434 434
435 435 In [6]: %precision %e
436 436 Out[6]: u'%e'
437 437
438 438 In [7]: pi**10
439 439 Out[7]: 9.364805e+04
440 440
441 441 In [8]: %precision
442 442 Out[8]: u'%r'
443 443
444 444 In [9]: pi**10
445 445 Out[9]: 93648.047476082982
446 446 """
447 447 ptformatter = self.shell.display_formatter.formatters['text/plain']
448 448 ptformatter.float_precision = s
449 449 return ptformatter.float_format
450 450
451 451 @magic_arguments.magic_arguments()
452 452 @magic_arguments.argument(
453 453 '-e', '--export', action='store_true', default=False,
454 454 help='Export IPython history as a notebook. The filename argument '
455 455 'is used to specify the notebook name and format. For example '
456 456 'a filename of notebook.ipynb will result in a notebook name '
457 457 'of "notebook" and a format of "xml". Likewise using a ".json" '
458 458 'or ".py" file extension will write the notebook in the json '
459 459 'or py formats.'
460 460 )
461 461 @magic_arguments.argument(
462 462 '-f', '--format',
463 463 help='Convert an existing IPython notebook to a new format. This option '
464 464 'specifies the new format and can have the values: xml, json, py. '
465 465 'The target filename is chosen automatically based on the new '
466 466 'format. The filename argument gives the name of the source file.'
467 467 )
468 468 @magic_arguments.argument(
469 469 'filename', type=unicode,
470 470 help='Notebook name or filename'
471 471 )
472 472 @line_magic
473 473 def notebook(self, s):
474 474 """Export and convert IPython notebooks.
475 475
476 476 This function can export the current IPython history to a notebook file
477 477 or can convert an existing notebook file into a different format. For
478 478 example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb".
479 479 To export the history to "foo.py" do "%notebook -e foo.py". To convert
480 480 "foo.ipynb" to "foo.json" do "%notebook -f json foo.ipynb". Possible
481 481 formats include (json/ipynb, py).
482 482 """
483 483 args = magic_arguments.parse_argstring(self.notebook, s)
484 484
485 485 from IPython.nbformat import current
486 486 args.filename = unquote_filename(args.filename)
487 487 if args.export:
488 488 fname, name, format = current.parse_filename(args.filename)
489 489 cells = []
490 490 hist = list(self.shell.history_manager.get_range())
491 491 for session, prompt_number, input in hist[:-1]:
492 492 cells.append(current.new_code_cell(prompt_number=prompt_number,
493 493 input=input))
494 494 worksheet = current.new_worksheet(cells=cells)
495 495 nb = current.new_notebook(name=name,worksheets=[worksheet])
496 496 with io.open(fname, 'w', encoding='utf-8') as f:
497 497 current.write(nb, f, format);
498 498 elif args.format is not None:
499 499 old_fname, old_name, old_format = current.parse_filename(args.filename)
500 500 new_format = args.format
501 501 if new_format == u'xml':
502 502 raise ValueError('Notebooks cannot be written as xml.')
503 503 elif new_format == u'ipynb' or new_format == u'json':
504 504 new_fname = old_name + u'.ipynb'
505 505 new_format = u'json'
506 506 elif new_format == u'py':
507 507 new_fname = old_name + u'.py'
508 508 else:
509 509 raise ValueError('Invalid notebook format: %s' % new_format)
510 510 with io.open(old_fname, 'r', encoding='utf-8') as f:
511 511 nb = current.read(f, old_format)
512 512 with io.open(new_fname, 'w', encoding='utf-8') as f:
513 513 current.write(nb, f, new_format)
@@ -1,478 +1,478 b''
1 1 """Implementation of code management magic functions.
2 2 """
3 3 #-----------------------------------------------------------------------------
4 4 # Copyright (c) 2012 The IPython Development Team.
5 5 #
6 6 # Distributed under the terms of the Modified BSD License.
7 7 #
8 8 # The full license is in the file COPYING.txt, distributed with this software.
9 9 #-----------------------------------------------------------------------------
10 10
11 11 #-----------------------------------------------------------------------------
12 12 # Imports
13 13 #-----------------------------------------------------------------------------
14 14
15 15 # Stdlib
16 16 import inspect
17 17 import io
18 18 import json
19 19 import os
20 20 import sys
21 21 from urllib2 import urlopen
22 22
23 23 # Our own packages
24 24 from IPython.core.error import TryNext
25 25 from IPython.core.macro import Macro
26 26 from IPython.core.magic import Magics, magics_class, line_magic
27 27 from IPython.testing.skipdoctest import skip_doctest
28 28 from IPython.utils import openpy
29 29 from IPython.utils import py3compat
30 30 from IPython.utils.io import file_read
31 31 from IPython.utils.path import get_py_filename, unquote_filename
32 32 from IPython.utils.warn import warn
33 33
34 34 #-----------------------------------------------------------------------------
35 35 # Magic implementation classes
36 36 #-----------------------------------------------------------------------------
37 37
38 38 # Used for exception handling in magic_edit
39 39 class MacroToEdit(ValueError): pass
40 40
41 41
42 42 @magics_class
43 43 class CodeMagics(Magics):
44 44 """Magics related to code management (loading, saving, editing, ...)."""
45 45
46 46 @line_magic
47 47 def save(self, parameter_s=''):
48 48 """Save a set of lines or a macro to a given filename.
49 49
50 50 Usage:\\
51 51 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
52 52
53 53 Options:
54 54
55 55 -r: use 'raw' input. By default, the 'processed' history is used,
56 56 so that magics are loaded in their transformed version to valid
57 57 Python. If this option is given, the raw input as typed as the
58 58 command line is used instead.
59 59
60 60 This function uses the same syntax as %history for input ranges,
61 61 then saves the lines to the filename you specify.
62 62
63 63 It adds a '.py' extension to the file if you don't do so yourself, and
64 64 it asks for confirmation before overwriting existing files."""
65 65
66 66 opts,args = self.parse_options(parameter_s,'r',mode='list')
67 67 fname, codefrom = unquote_filename(args[0]), " ".join(args[1:])
68 68 if not fname.endswith('.py'):
69 69 fname += '.py'
70 70 if os.path.isfile(fname):
71 71 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
72 72 if ans.lower() not in ['y','yes']:
73 73 print 'Operation cancelled.'
74 74 return
75 75 try:
76 76 cmds = self.shell.find_user_code(codefrom, 'r' in opts)
77 77 except (TypeError, ValueError) as e:
78 78 print e.args[0]
79 79 return
80 80 with io.open(fname,'w', encoding="utf-8") as f:
81 81 f.write(u"# coding: utf-8\n")
82 82 f.write(py3compat.cast_unicode(cmds))
83 83 print 'The following commands were written to file `%s`:' % fname
84 84 print cmds
85 85
86 86 @line_magic
87 87 def pastebin(self, parameter_s=''):
88 88 """Upload code to Github's Gist paste bin, returning the URL.
89 89
90 90 Usage:\\
91 91 %pastebin [-d "Custom description"] 1-7
92 92
93 93 The argument can be an input history range, a filename, or the name of a
94 94 string or macro.
95 95
96 96 Options:
97 97
98 98 -d: Pass a custom description for the gist. The default will say
99 99 "Pasted from IPython".
100 100 """
101 101 opts, args = self.parse_options(parameter_s, 'd:')
102 102
103 103 try:
104 104 code = self.shell.find_user_code(args)
105 105 except (ValueError, TypeError) as e:
106 106 print e.args[0]
107 107 return
108 108
109 109 post_data = json.dumps({
110 110 "description": opts.get('d', "Pasted from IPython"),
111 111 "public": True,
112 112 "files": {
113 113 "file1.py": {
114 114 "content": code
115 115 }
116 116 }
117 117 }).encode('utf-8')
118 118
119 119 response = urlopen("https://api.github.com/gists", post_data)
120 120 response_data = json.loads(response.read().decode('utf-8'))
121 121 return response_data['html_url']
122 122
123 123 @line_magic
124 124 def loadpy(self, arg_s):
125 125 """Load a .py python script into the GUI console.
126 126
127 127 This magic command can either take a local filename or a url::
128 128
129 129 %loadpy myscript.py
130 130 %loadpy http://www.example.com/myscript.py
131 131 """
132 132 arg_s = unquote_filename(arg_s)
133 133 remote_url = arg_s.startswith(('http://', 'https://'))
134 134 local_url = not remote_url
135 135 if local_url and not arg_s.endswith('.py'):
136 136 # Local files must be .py; for remote URLs it's possible that the
137 137 # fetch URL doesn't have a .py in it (many servers have an opaque
138 138 # URL, such as scipy-central.org).
139 139 raise ValueError('%%loadpy only works with .py files: %s' % arg_s)
140 140
141 141 # openpy takes care of finding the source encoding (per PEP 263)
142 142 if remote_url:
143 143 contents = openpy.read_py_url(arg_s, skip_encoding_cookie=True)
144 144 else:
145 145 contents = openpy.read_py_file(arg_s, skip_encoding_cookie=True)
146 146
147 147 self.shell.set_next_input(contents)
148 148
149 149 def _find_edit_target(self, args, opts, last_call):
150 150 """Utility method used by magic_edit to find what to edit."""
151 151
152 152 def make_filename(arg):
153 153 "Make a filename from the given args"
154 154 arg = unquote_filename(arg)
155 155 try:
156 156 filename = get_py_filename(arg)
157 157 except IOError:
158 158 # If it ends with .py but doesn't already exist, assume we want
159 159 # a new file.
160 160 if arg.endswith('.py'):
161 161 filename = arg
162 162 else:
163 163 filename = None
164 164 return filename
165 165
166 166 # Set a few locals from the options for convenience:
167 167 opts_prev = 'p' in opts
168 168 opts_raw = 'r' in opts
169 169
170 170 # custom exceptions
171 171 class DataIsObject(Exception): pass
172 172
173 173 # Default line number value
174 174 lineno = opts.get('n',None)
175 175
176 176 if opts_prev:
177 177 args = '_%s' % last_call[0]
178 178 if not self.shell.user_ns.has_key(args):
179 179 args = last_call[1]
180 180
181 181 # use last_call to remember the state of the previous call, but don't
182 182 # let it be clobbered by successive '-p' calls.
183 183 try:
184 184 last_call[0] = self.shell.displayhook.prompt_count
185 185 if not opts_prev:
186 186 last_call[1] = args
187 187 except:
188 188 pass
189 189
190 190 # by default this is done with temp files, except when the given
191 191 # arg is a filename
192 192 use_temp = True
193 193
194 194 data = ''
195 195
196 196 # First, see if the arguments should be a filename.
197 197 filename = make_filename(args)
198 198 if filename:
199 199 use_temp = False
200 200 elif args:
201 201 # Mode where user specifies ranges of lines, like in %macro.
202 202 data = self.shell.extract_input_lines(args, opts_raw)
203 203 if not data:
204 204 try:
205 205 # Load the parameter given as a variable. If not a string,
206 206 # process it as an object instead (below)
207 207
208 208 #print '*** args',args,'type',type(args) # dbg
209 209 data = eval(args, self.shell.user_ns)
210 210 if not isinstance(data, basestring):
211 211 raise DataIsObject
212 212
213 213 except (NameError,SyntaxError):
214 214 # given argument is not a variable, try as a filename
215 215 filename = make_filename(args)
216 216 if filename is None:
217 217 warn("Argument given (%s) can't be found as a variable "
218 218 "or as a filename." % args)
219 219 return
220 220 use_temp = False
221 221
222 222 except DataIsObject:
223 223 # macros have a special edit function
224 224 if isinstance(data, Macro):
225 225 raise MacroToEdit(data)
226 226
227 227 # For objects, try to edit the file where they are defined
228 228 try:
229 229 filename = inspect.getabsfile(data)
230 230 if 'fakemodule' in filename.lower() and \
231 231 inspect.isclass(data):
232 232 # class created by %edit? Try to find source
233 233 # by looking for method definitions instead, the
234 234 # __module__ in those classes is FakeModule.
235 235 attrs = [getattr(data, aname) for aname in dir(data)]
236 236 for attr in attrs:
237 237 if not inspect.ismethod(attr):
238 238 continue
239 239 filename = inspect.getabsfile(attr)
240 240 if filename and \
241 241 'fakemodule' not in filename.lower():
242 242 # change the attribute to be the edit
243 243 # target instead
244 244 data = attr
245 245 break
246 246
247 247 datafile = 1
248 248 except TypeError:
249 249 filename = make_filename(args)
250 250 datafile = 1
251 251 warn('Could not find file where `%s` is defined.\n'
252 'Opening a file named `%s`' % (args,filename))
252 'Opening a file named `%s`' % (args, filename))
253 253 # Now, make sure we can actually read the source (if it was
254 254 # in a temp file it's gone by now).
255 255 if datafile:
256 256 try:
257 257 if lineno is None:
258 258 lineno = inspect.getsourcelines(data)[1]
259 259 except IOError:
260 260 filename = make_filename(args)
261 261 if filename is None:
262 warn('The file `%s` where `%s` was defined cannot '
263 'be read.' % (filename,data))
262 warn('The file `%s` where `%s` was defined '
263 'cannot be read.' % (filename, data))
264 264 return
265 265 use_temp = False
266 266
267 267 if use_temp:
268 268 filename = self.shell.mktempfile(data)
269 269 print 'IPython will make a temporary file named:',filename
270 270
271 271 return filename, lineno, use_temp
272 272
273 273 def _edit_macro(self,mname,macro):
274 274 """open an editor with the macro data in a file"""
275 275 filename = self.shell.mktempfile(macro.value)
276 276 self.shell.hooks.editor(filename)
277 277
278 278 # and make a new macro object, to replace the old one
279 279 mfile = open(filename)
280 280 mvalue = mfile.read()
281 281 mfile.close()
282 282 self.shell.user_ns[mname] = Macro(mvalue)
283 283
284 284 @line_magic
285 285 def ed(self, parameter_s=''):
286 286 """Alias to %edit."""
287 287 return self.edit(parameter_s)
288 288
289 289 @skip_doctest
290 290 @line_magic
291 291 def edit(self, parameter_s='',last_call=['','']):
292 292 """Bring up an editor and execute the resulting code.
293 293
294 294 Usage:
295 295 %edit [options] [args]
296 296
297 297 %edit runs IPython's editor hook. The default version of this hook is
298 298 set to call the editor specified by your $EDITOR environment variable.
299 299 If this isn't found, it will default to vi under Linux/Unix and to
300 300 notepad under Windows. See the end of this docstring for how to change
301 301 the editor hook.
302 302
303 303 You can also set the value of this editor via the
304 304 ``TerminalInteractiveShell.editor`` option in your configuration file.
305 305 This is useful if you wish to use a different editor from your typical
306 306 default with IPython (and for Windows users who typically don't set
307 307 environment variables).
308 308
309 309 This command allows you to conveniently edit multi-line code right in
310 310 your IPython session.
311 311
312 312 If called without arguments, %edit opens up an empty editor with a
313 313 temporary file and will execute the contents of this file when you
314 314 close it (don't forget to save it!).
315 315
316 316
317 317 Options:
318 318
319 319 -n <number>: open the editor at a specified line number. By default,
320 320 the IPython editor hook uses the unix syntax 'editor +N filename', but
321 321 you can configure this by providing your own modified hook if your
322 322 favorite editor supports line-number specifications with a different
323 323 syntax.
324 324
325 325 -p: this will call the editor with the same data as the previous time
326 326 it was used, regardless of how long ago (in your current session) it
327 327 was.
328 328
329 329 -r: use 'raw' input. This option only applies to input taken from the
330 330 user's history. By default, the 'processed' history is used, so that
331 331 magics are loaded in their transformed version to valid Python. If
332 332 this option is given, the raw input as typed as the command line is
333 333 used instead. When you exit the editor, it will be executed by
334 334 IPython's own processor.
335 335
336 336 -x: do not execute the edited code immediately upon exit. This is
337 337 mainly useful if you are editing programs which need to be called with
338 338 command line arguments, which you can then do using %run.
339 339
340 340
341 341 Arguments:
342 342
343 343 If arguments are given, the following possibilities exist:
344 344
345 345 - If the argument is a filename, IPython will load that into the
346 346 editor. It will execute its contents with execfile() when you exit,
347 347 loading any code in the file into your interactive namespace.
348 348
349 349 - The arguments are ranges of input history, e.g. "7 ~1/4-6".
350 350 The syntax is the same as in the %history magic.
351 351
352 352 - If the argument is a string variable, its contents are loaded
353 353 into the editor. You can thus edit any string which contains
354 354 python code (including the result of previous edits).
355 355
356 356 - If the argument is the name of an object (other than a string),
357 357 IPython will try to locate the file where it was defined and open the
358 358 editor at the point where it is defined. You can use `%edit function`
359 359 to load an editor exactly at the point where 'function' is defined,
360 360 edit it and have the file be executed automatically.
361 361
362 362 - If the object is a macro (see %macro for details), this opens up your
363 363 specified editor with a temporary file containing the macro's data.
364 364 Upon exit, the macro is reloaded with the contents of the file.
365 365
366 366 Note: opening at an exact line is only supported under Unix, and some
367 367 editors (like kedit and gedit up to Gnome 2.8) do not understand the
368 368 '+NUMBER' parameter necessary for this feature. Good editors like
369 369 (X)Emacs, vi, jed, pico and joe all do.
370 370
371 371 After executing your code, %edit will return as output the code you
372 372 typed in the editor (except when it was an existing file). This way
373 373 you can reload the code in further invocations of %edit as a variable,
374 374 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
375 375 the output.
376 376
377 377 Note that %edit is also available through the alias %ed.
378 378
379 379 This is an example of creating a simple function inside the editor and
380 380 then modifying it. First, start up the editor::
381 381
382 382 In [1]: ed
383 383 Editing... done. Executing edited code...
384 384 Out[1]: 'def foo():\\n print "foo() was defined in an editing
385 385 session"\\n'
386 386
387 387 We can then call the function foo()::
388 388
389 389 In [2]: foo()
390 390 foo() was defined in an editing session
391 391
392 392 Now we edit foo. IPython automatically loads the editor with the
393 393 (temporary) file where foo() was previously defined::
394 394
395 395 In [3]: ed foo
396 396 Editing... done. Executing edited code...
397 397
398 398 And if we call foo() again we get the modified version::
399 399
400 400 In [4]: foo()
401 401 foo() has now been changed!
402 402
403 403 Here is an example of how to edit a code snippet successive
404 404 times. First we call the editor::
405 405
406 406 In [5]: ed
407 407 Editing... done. Executing edited code...
408 408 hello
409 409 Out[5]: "print 'hello'\\n"
410 410
411 411 Now we call it again with the previous output (stored in _)::
412 412
413 413 In [6]: ed _
414 414 Editing... done. Executing edited code...
415 415 hello world
416 416 Out[6]: "print 'hello world'\\n"
417 417
418 418 Now we call it with the output #8 (stored in _8, also as Out[8])::
419 419
420 420 In [7]: ed _8
421 421 Editing... done. Executing edited code...
422 422 hello again
423 423 Out[7]: "print 'hello again'\\n"
424 424
425 425
426 426 Changing the default editor hook:
427 427
428 428 If you wish to write your own editor hook, you can put it in a
429 429 configuration file which you load at startup time. The default hook
430 430 is defined in the IPython.core.hooks module, and you can use that as a
431 431 starting example for further modifications. That file also has
432 432 general instructions on how to set a new hook for use once you've
433 433 defined it."""
434 434 opts,args = self.parse_options(parameter_s,'prxn:')
435 435
436 436 try:
437 437 filename, lineno, is_temp = self._find_edit_target(args, opts, last_call)
438 438 except MacroToEdit as e:
439 439 self._edit_macro(args, e.args[0])
440 440 return
441 441
442 442 # do actual editing here
443 443 print 'Editing...',
444 444 sys.stdout.flush()
445 445 try:
446 446 # Quote filenames that may have spaces in them
447 447 if ' ' in filename:
448 448 filename = "'%s'" % filename
449 449 self.shell.hooks.editor(filename,lineno)
450 450 except TryNext:
451 451 warn('Could not open editor')
452 452 return
453 453
454 454 # XXX TODO: should this be generalized for all string vars?
455 455 # For now, this is special-cased to blocks created by cpaste
456 456 if args.strip() == 'pasted_block':
457 457 self.shell.user_ns['pasted_block'] = file_read(filename)
458 458
459 459 if 'x' in opts: # -x prevents actual execution
460 460 print
461 461 else:
462 462 print 'done. Executing edited code...'
463 463 if 'r' in opts: # Untranslated IPython code
464 464 self.shell.run_cell(file_read(filename),
465 465 store_history=False)
466 466 else:
467 467 self.shell.safe_execfile(filename, self.shell.user_ns,
468 468 self.shell.user_ns)
469 469
470 470 if is_temp:
471 471 try:
472 472 return open(filename).read()
473 473 except IOError,msg:
474 474 if msg.filename == filename:
475 475 warn('File not found. Did you forget to save?')
476 476 return
477 477 else:
478 478 self.shell.showtraceback()
@@ -1,702 +1,702 b''
1 1 """Implementation of namespace-related magic functions.
2 2 """
3 3 #-----------------------------------------------------------------------------
4 4 # Copyright (c) 2012 The IPython Development Team.
5 5 #
6 6 # Distributed under the terms of the Modified BSD License.
7 7 #
8 8 # The full license is in the file COPYING.txt, distributed with this software.
9 9 #-----------------------------------------------------------------------------
10 10
11 11 #-----------------------------------------------------------------------------
12 12 # Imports
13 13 #-----------------------------------------------------------------------------
14 14
15 15 # Stdlib
16 16 import gc
17 17 import re
18 18 import sys
19 19
20 20 # Our own packages
21 21 from IPython.core import page
22 22 from IPython.core.error import StdinNotImplementedError
23 23 from IPython.core.magic import Magics, magics_class, line_magic
24 24 from IPython.testing.skipdoctest import skip_doctest
25 25 from IPython.utils.encoding import DEFAULT_ENCODING
26 26 from IPython.utils.path import get_py_filename
27 27
28 28 #-----------------------------------------------------------------------------
29 29 # Magic implementation classes
30 30 #-----------------------------------------------------------------------------
31 31
32 32 @magics_class
33 33 class NamespaceMagics(Magics):
34 34 """Magics to manage various aspects of the user's namespace.
35 35
36 36 These include listing variables, introspecting into them, etc.
37 37 """
38 38
39 39 @line_magic
40 40 def pinfo(self, parameter_s='', namespaces=None):
41 41 """Provide detailed information about an object.
42 42
43 43 '%pinfo object' is just a synonym for object? or ?object."""
44 44
45 45 #print 'pinfo par: <%s>' % parameter_s # dbg
46 46
47 47
48 48 # detail_level: 0 -> obj? , 1 -> obj??
49 49 detail_level = 0
50 50 # We need to detect if we got called as 'pinfo pinfo foo', which can
51 51 # happen if the user types 'pinfo foo?' at the cmd line.
52 52 pinfo,qmark1,oname,qmark2 = \
53 53 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
54 54 if pinfo or qmark1 or qmark2:
55 55 detail_level = 1
56 56 if "*" in oname:
57 57 self.psearch(oname)
58 58 else:
59 59 self.shell._inspect('pinfo', oname, detail_level=detail_level,
60 60 namespaces=namespaces)
61 61
62 62 @line_magic
63 63 def pinfo2(self, parameter_s='', namespaces=None):
64 64 """Provide extra detailed information about an object.
65 65
66 66 '%pinfo2 object' is just a synonym for object?? or ??object."""
67 67 self.shell._inspect('pinfo', parameter_s, detail_level=1,
68 68 namespaces=namespaces)
69 69
70 70 @skip_doctest
71 71 @line_magic
72 72 def pdef(self, parameter_s='', namespaces=None):
73 73 """Print the definition header for any callable object.
74 74
75 75 If the object is a class, print the constructor information.
76 76
77 77 Examples
78 78 --------
79 79 ::
80 80
81 81 In [3]: %pdef urllib.urlopen
82 82 urllib.urlopen(url, data=None, proxies=None)
83 83 """
84 84 self._inspect('pdef',parameter_s, namespaces)
85 85
86 86 @line_magic
87 87 def pdoc(self, parameter_s='', namespaces=None):
88 88 """Print the docstring for an object.
89 89
90 90 If the given object is a class, it will print both the class and the
91 91 constructor docstrings."""
92 92 self._inspect('pdoc',parameter_s, namespaces)
93 93
94 94 @line_magic
95 95 def psource(self, parameter_s='', namespaces=None):
96 96 """Print (or run through pager) the source code for an object."""
97 97 self._inspect('psource',parameter_s, namespaces)
98 98
99 99 @line_magic
100 100 def pfile(self, parameter_s=''):
101 101 """Print (or run through pager) the file where an object is defined.
102 102
103 103 The file opens at the line where the object definition begins. IPython
104 104 will honor the environment variable PAGER if set, and otherwise will
105 105 do its best to print the file in a convenient form.
106 106
107 107 If the given argument is not an object currently defined, IPython will
108 108 try to interpret it as a filename (automatically adding a .py extension
109 109 if needed). You can thus use %pfile as a syntax highlighting code
110 110 viewer."""
111 111
112 112 # first interpret argument as an object name
113 113 out = self._inspect('pfile',parameter_s)
114 114 # if not, try the input as a filename
115 115 if out == 'not found':
116 116 try:
117 117 filename = get_py_filename(parameter_s)
118 118 except IOError,msg:
119 119 print msg
120 120 return
121 121 page.page(self.shell.inspector.format(open(filename).read()))
122 122
123 123 @line_magic
124 124 def psearch(self, parameter_s=''):
125 125 """Search for object in namespaces by wildcard.
126 126
127 127 %psearch [options] PATTERN [OBJECT TYPE]
128 128
129 129 Note: ? can be used as a synonym for %psearch, at the beginning or at
130 130 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
131 131 rest of the command line must be unchanged (options come first), so
132 132 for example the following forms are equivalent
133 133
134 134 %psearch -i a* function
135 135 -i a* function?
136 136 ?-i a* function
137 137
138 138 Arguments:
139 139
140 140 PATTERN
141 141
142 142 where PATTERN is a string containing * as a wildcard similar to its
143 143 use in a shell. The pattern is matched in all namespaces on the
144 144 search path. By default objects starting with a single _ are not
145 145 matched, many IPython generated objects have a single
146 146 underscore. The default is case insensitive matching. Matching is
147 147 also done on the attributes of objects and not only on the objects
148 148 in a module.
149 149
150 150 [OBJECT TYPE]
151 151
152 152 Is the name of a python type from the types module. The name is
153 153 given in lowercase without the ending type, ex. StringType is
154 154 written string. By adding a type here only objects matching the
155 155 given type are matched. Using all here makes the pattern match all
156 156 types (this is the default).
157 157
158 158 Options:
159 159
160 160 -a: makes the pattern match even objects whose names start with a
161 161 single underscore. These names are normally omitted from the
162 162 search.
163 163
164 164 -i/-c: make the pattern case insensitive/sensitive. If neither of
165 165 these options are given, the default is read from your configuration
166 166 file, with the option ``InteractiveShell.wildcards_case_sensitive``.
167 167 If this option is not specified in your configuration file, IPython's
168 168 internal default is to do a case sensitive search.
169 169
170 170 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
171 171 specify can be searched in any of the following namespaces:
172 172 'builtin', 'user', 'user_global','internal', 'alias', where
173 173 'builtin' and 'user' are the search defaults. Note that you should
174 174 not use quotes when specifying namespaces.
175 175
176 176 'Builtin' contains the python module builtin, 'user' contains all
177 177 user data, 'alias' only contain the shell aliases and no python
178 178 objects, 'internal' contains objects used by IPython. The
179 179 'user_global' namespace is only used by embedded IPython instances,
180 180 and it contains module-level globals. You can add namespaces to the
181 181 search with -s or exclude them with -e (these options can be given
182 182 more than once).
183 183
184 184 Examples
185 185 --------
186 186 ::
187 187
188 188 %psearch a* -> objects beginning with an a
189 189 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
190 190 %psearch a* function -> all functions beginning with an a
191 191 %psearch re.e* -> objects beginning with an e in module re
192 192 %psearch r*.e* -> objects that start with e in modules starting in r
193 193 %psearch r*.* string -> all strings in modules beginning with r
194 194
195 195 Case sensitive search::
196 196
197 197 %psearch -c a* list all object beginning with lower case a
198 198
199 199 Show objects beginning with a single _::
200 200
201 201 %psearch -a _* list objects beginning with a single underscore
202 202 """
203 203 try:
204 204 parameter_s.encode('ascii')
205 205 except UnicodeEncodeError:
206 206 print 'Python identifiers can only contain ascii characters.'
207 207 return
208 208
209 209 # default namespaces to be searched
210 210 def_search = ['user_local', 'user_global', 'builtin']
211 211
212 212 # Process options/args
213 213 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
214 214 opt = opts.get
215 215 shell = self.shell
216 216 psearch = shell.inspector.psearch
217 217
218 218 # select case options
219 219 if opts.has_key('i'):
220 220 ignore_case = True
221 221 elif opts.has_key('c'):
222 222 ignore_case = False
223 223 else:
224 224 ignore_case = not shell.wildcards_case_sensitive
225 225
226 226 # Build list of namespaces to search from user options
227 227 def_search.extend(opt('s',[]))
228 228 ns_exclude = ns_exclude=opt('e',[])
229 229 ns_search = [nm for nm in def_search if nm not in ns_exclude]
230 230
231 231 # Call the actual search
232 232 try:
233 233 psearch(args,shell.ns_table,ns_search,
234 234 show_all=opt('a'),ignore_case=ignore_case)
235 235 except:
236 236 shell.showtraceback()
237 237
238 238 @skip_doctest
239 239 @line_magic
240 240 def who_ls(self, parameter_s=''):
241 241 """Return a sorted list of all interactive variables.
242 242
243 243 If arguments are given, only variables of types matching these
244 244 arguments are returned.
245 245
246 246 Examples
247 247 --------
248 248
249 249 Define two variables and list them with who_ls::
250 250
251 251 In [1]: alpha = 123
252 252
253 253 In [2]: beta = 'test'
254 254
255 255 In [3]: %who_ls
256 256 Out[3]: ['alpha', 'beta']
257 257
258 258 In [4]: %who_ls int
259 259 Out[4]: ['alpha']
260 260
261 261 In [5]: %who_ls str
262 262 Out[5]: ['beta']
263 263 """
264 264
265 265 user_ns = self.shell.user_ns
266 266 user_ns_hidden = self.shell.user_ns_hidden
267 267 out = [ i for i in user_ns
268 268 if not i.startswith('_') \
269 269 and not i in user_ns_hidden ]
270 270
271 271 typelist = parameter_s.split()
272 272 if typelist:
273 273 typeset = set(typelist)
274 274 out = [i for i in out if type(user_ns[i]).__name__ in typeset]
275 275
276 276 out.sort()
277 277 return out
278 278
279 279 @skip_doctest
280 280 @line_magic
281 281 def who(self, parameter_s=''):
282 282 """Print all interactive variables, with some minimal formatting.
283 283
284 284 If any arguments are given, only variables whose type matches one of
285 285 these are printed. For example::
286 286
287 287 %who function str
288 288
289 289 will only list functions and strings, excluding all other types of
290 290 variables. To find the proper type names, simply use type(var) at a
291 291 command line to see how python prints type names. For example:
292 292
293 293 ::
294 294
295 295 In [1]: type('hello')\\
296 296 Out[1]: <type 'str'>
297 297
298 298 indicates that the type name for strings is 'str'.
299 299
300 300 ``%who`` always excludes executed names loaded through your configuration
301 301 file and things which are internal to IPython.
302 302
303 303 This is deliberate, as typically you may load many modules and the
304 304 purpose of %who is to show you only what you've manually defined.
305 305
306 306 Examples
307 307 --------
308 308
309 309 Define two variables and list them with who::
310 310
311 311 In [1]: alpha = 123
312 312
313 313 In [2]: beta = 'test'
314 314
315 315 In [3]: %who
316 316 alpha beta
317 317
318 318 In [4]: %who int
319 319 alpha
320 320
321 321 In [5]: %who str
322 322 beta
323 323 """
324 324
325 325 varlist = self.who_ls(parameter_s)
326 326 if not varlist:
327 327 if parameter_s:
328 328 print 'No variables match your requested type.'
329 329 else:
330 330 print 'Interactive namespace is empty.'
331 331 return
332 332
333 333 # if we have variables, move on...
334 334 count = 0
335 335 for i in varlist:
336 336 print i+'\t',
337 337 count += 1
338 338 if count > 8:
339 339 count = 0
340 340 print
341 341 print
342 342
343 343 @skip_doctest
344 344 @line_magic
345 345 def whos(self, parameter_s=''):
346 346 """Like %who, but gives some extra information about each variable.
347 347
348 348 The same type filtering of %who can be applied here.
349 349
350 350 For all variables, the type is printed. Additionally it prints:
351 351
352 352 - For {},[],(): their length.
353 353
354 354 - For numpy arrays, a summary with shape, number of
355 355 elements, typecode and size in memory.
356 356
357 357 - Everything else: a string representation, snipping their middle if
358 358 too long.
359 359
360 360 Examples
361 361 --------
362 362
363 363 Define two variables and list them with whos::
364 364
365 365 In [1]: alpha = 123
366 366
367 367 In [2]: beta = 'test'
368 368
369 369 In [3]: %whos
370 370 Variable Type Data/Info
371 371 --------------------------------
372 372 alpha int 123
373 373 beta str test
374 374 """
375 375
376 376 varnames = self.who_ls(parameter_s)
377 377 if not varnames:
378 378 if parameter_s:
379 379 print 'No variables match your requested type.'
380 380 else:
381 381 print 'Interactive namespace is empty.'
382 382 return
383 383
384 384 # if we have variables, move on...
385 385
386 386 # for these types, show len() instead of data:
387 387 seq_types = ['dict', 'list', 'tuple']
388 388
389 389 # for numpy arrays, display summary info
390 390 ndarray_type = None
391 391 if 'numpy' in sys.modules:
392 392 try:
393 393 from numpy import ndarray
394 394 except ImportError:
395 395 pass
396 396 else:
397 397 ndarray_type = ndarray.__name__
398 398
399 399 # Find all variable names and types so we can figure out column sizes
400 400 def get_vars(i):
401 401 return self.shell.user_ns[i]
402 402
403 403 # some types are well known and can be shorter
404 404 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
405 405 def type_name(v):
406 406 tn = type(v).__name__
407 407 return abbrevs.get(tn,tn)
408 408
409 409 varlist = map(get_vars,varnames)
410 410
411 411 typelist = []
412 412 for vv in varlist:
413 413 tt = type_name(vv)
414 414
415 415 if tt=='instance':
416 416 typelist.append( abbrevs.get(str(vv.__class__),
417 417 str(vv.__class__)))
418 418 else:
419 419 typelist.append(tt)
420 420
421 421 # column labels and # of spaces as separator
422 422 varlabel = 'Variable'
423 423 typelabel = 'Type'
424 424 datalabel = 'Data/Info'
425 425 colsep = 3
426 426 # variable format strings
427 427 vformat = "{0:<{varwidth}}{1:<{typewidth}}"
428 428 aformat = "%s: %s elems, type `%s`, %s bytes"
429 429 # find the size of the columns to format the output nicely
430 430 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
431 431 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
432 432 # table header
433 433 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
434 434 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
435 435 # and the table itself
436 436 kb = 1024
437 437 Mb = 1048576 # kb**2
438 438 for vname,var,vtype in zip(varnames,varlist,typelist):
439 439 print vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth),
440 440 if vtype in seq_types:
441 441 print "n="+str(len(var))
442 442 elif vtype == ndarray_type:
443 443 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
444 444 if vtype==ndarray_type:
445 445 # numpy
446 446 vsize = var.size
447 447 vbytes = vsize*var.itemsize
448 448 vdtype = var.dtype
449 449
450 450 if vbytes < 100000:
451 print aformat % (vshape,vsize,vdtype,vbytes)
451 print aformat % (vshape, vsize, vdtype, vbytes)
452 452 else:
453 print aformat % (vshape,vsize,vdtype,vbytes),
453 print aformat % (vshape, vsize, vdtype, vbytes),
454 454 if vbytes < Mb:
455 455 print '(%s kb)' % (vbytes/kb,)
456 456 else:
457 457 print '(%s Mb)' % (vbytes/Mb,)
458 458 else:
459 459 try:
460 460 vstr = str(var)
461 461 except UnicodeEncodeError:
462 462 vstr = unicode(var).encode(DEFAULT_ENCODING,
463 463 'backslashreplace')
464 464 except:
465 465 vstr = "<object with id %d (str() failed)>" % id(var)
466 vstr = vstr.replace('\n','\\n')
466 vstr = vstr.replace('\n', '\\n')
467 467 if len(vstr) < 50:
468 468 print vstr
469 469 else:
470 470 print vstr[:25] + "<...>" + vstr[-25:]
471 471
472 472 @line_magic
473 473 def reset(self, parameter_s=''):
474 474 """Resets the namespace by removing all names defined by the user, if
475 475 called without arguments, or by removing some types of objects, such
476 476 as everything currently in IPython's In[] and Out[] containers (see
477 477 the parameters for details).
478 478
479 479 Parameters
480 480 ----------
481 481 -f : force reset without asking for confirmation.
482 482
483 483 -s : 'Soft' reset: Only clears your namespace, leaving history intact.
484 484 References to objects may be kept. By default (without this option),
485 485 we do a 'hard' reset, giving you a new session and removing all
486 486 references to objects from the current session.
487 487
488 488 in : reset input history
489 489
490 490 out : reset output history
491 491
492 492 dhist : reset directory history
493 493
494 494 array : reset only variables that are NumPy arrays
495 495
496 496 See Also
497 497 --------
498 498 magic_reset_selective : invoked as ``%reset_selective``
499 499
500 500 Examples
501 501 --------
502 502 ::
503 503
504 504 In [6]: a = 1
505 505
506 506 In [7]: a
507 507 Out[7]: 1
508 508
509 509 In [8]: 'a' in _ip.user_ns
510 510 Out[8]: True
511 511
512 512 In [9]: %reset -f
513 513
514 514 In [1]: 'a' in _ip.user_ns
515 515 Out[1]: False
516 516
517 517 In [2]: %reset -f in
518 518 Flushing input history
519 519
520 520 In [3]: %reset -f dhist in
521 521 Flushing directory history
522 522 Flushing input history
523 523
524 524 Notes
525 525 -----
526 526 Calling this magic from clients that do not implement standard input,
527 527 such as the ipython notebook interface, will reset the namespace
528 528 without confirmation.
529 529 """
530 530 opts, args = self.parse_options(parameter_s,'sf', mode='list')
531 531 if 'f' in opts:
532 532 ans = True
533 533 else:
534 534 try:
535 535 ans = self.shell.ask_yes_no(
536 536 "Once deleted, variables cannot be recovered. Proceed (y/[n])?",
537 537 default='n')
538 538 except StdinNotImplementedError:
539 539 ans = True
540 540 if not ans:
541 541 print 'Nothing done.'
542 542 return
543 543
544 544 if 's' in opts: # Soft reset
545 545 user_ns = self.shell.user_ns
546 546 for i in self.who_ls():
547 547 del(user_ns[i])
548 548 elif len(args) == 0: # Hard reset
549 549 self.shell.reset(new_session = False)
550 550
551 551 # reset in/out/dhist/array: previously extensinions/clearcmd.py
552 552 ip = self.shell
553 553 user_ns = self.shell.user_ns # local lookup, heavily used
554 554
555 555 for target in args:
556 556 target = target.lower() # make matches case insensitive
557 557 if target == 'out':
558 558 print "Flushing output cache (%d entries)" % len(user_ns['_oh'])
559 559 self.shell.displayhook.flush()
560 560
561 561 elif target == 'in':
562 562 print "Flushing input history"
563 563 pc = self.shell.displayhook.prompt_count + 1
564 564 for n in range(1, pc):
565 565 key = '_i'+repr(n)
566 566 user_ns.pop(key,None)
567 567 user_ns.update(dict(_i=u'',_ii=u'',_iii=u''))
568 568 hm = ip.history_manager
569 569 # don't delete these, as %save and %macro depending on the
570 570 # length of these lists to be preserved
571 571 hm.input_hist_parsed[:] = [''] * pc
572 572 hm.input_hist_raw[:] = [''] * pc
573 573 # hm has internal machinery for _i,_ii,_iii, clear it out
574 574 hm._i = hm._ii = hm._iii = hm._i00 = u''
575 575
576 576 elif target == 'array':
577 577 # Support cleaning up numpy arrays
578 578 try:
579 579 from numpy import ndarray
580 580 # This must be done with items and not iteritems because
581 581 # we're going to modify the dict in-place.
582 582 for x,val in user_ns.items():
583 583 if isinstance(val,ndarray):
584 584 del user_ns[x]
585 585 except ImportError:
586 586 print "reset array only works if Numpy is available."
587 587
588 588 elif target == 'dhist':
589 589 print "Flushing directory history"
590 590 del user_ns['_dh'][:]
591 591
592 592 else:
593 593 print "Don't know how to reset ",
594 594 print target + ", please run `%reset?` for details"
595 595
596 596 gc.collect()
597 597
598 598 @line_magic
599 599 def reset_selective(self, parameter_s=''):
600 600 """Resets the namespace by removing names defined by the user.
601 601
602 602 Input/Output history are left around in case you need them.
603 603
604 604 %reset_selective [-f] regex
605 605
606 606 No action is taken if regex is not included
607 607
608 608 Options
609 609 -f : force reset without asking for confirmation.
610 610
611 611 See Also
612 612 --------
613 613 magic_reset : invoked as ``%reset``
614 614
615 615 Examples
616 616 --------
617 617
618 618 We first fully reset the namespace so your output looks identical to
619 619 this example for pedagogical reasons; in practice you do not need a
620 620 full reset::
621 621
622 622 In [1]: %reset -f
623 623
624 624 Now, with a clean namespace we can make a few variables and use
625 625 ``%reset_selective`` to only delete names that match our regexp::
626 626
627 627 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
628 628
629 629 In [3]: who_ls
630 630 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
631 631
632 632 In [4]: %reset_selective -f b[2-3]m
633 633
634 634 In [5]: who_ls
635 635 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
636 636
637 637 In [6]: %reset_selective -f d
638 638
639 639 In [7]: who_ls
640 640 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
641 641
642 642 In [8]: %reset_selective -f c
643 643
644 644 In [9]: who_ls
645 645 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
646 646
647 647 In [10]: %reset_selective -f b
648 648
649 649 In [11]: who_ls
650 650 Out[11]: ['a']
651 651
652 652 Notes
653 653 -----
654 654 Calling this magic from clients that do not implement standard input,
655 655 such as the ipython notebook interface, will reset the namespace
656 656 without confirmation.
657 657 """
658 658
659 659 opts, regex = self.parse_options(parameter_s,'f')
660 660
661 661 if opts.has_key('f'):
662 662 ans = True
663 663 else:
664 664 try:
665 665 ans = self.shell.ask_yes_no(
666 666 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ",
667 667 default='n')
668 668 except StdinNotImplementedError:
669 669 ans = True
670 670 if not ans:
671 671 print 'Nothing done.'
672 672 return
673 673 user_ns = self.shell.user_ns
674 674 if not regex:
675 675 print 'No regex pattern specified. Nothing done.'
676 676 return
677 677 else:
678 678 try:
679 679 m = re.compile(regex)
680 680 except TypeError:
681 681 raise TypeError('regex must be a string or compiled pattern')
682 682 for i in self.who_ls():
683 683 if m.search(i):
684 684 del(user_ns[i])
685 685
686 686 @line_magic
687 687 def xdel(self, parameter_s=''):
688 688 """Delete a variable, trying to clear it from anywhere that
689 689 IPython's machinery has references to it. By default, this uses
690 690 the identity of the named object in the user namespace to remove
691 691 references held under other names. The object is also removed
692 692 from the output history.
693 693
694 694 Options
695 695 -n : Delete the specified name from all namespaces, without
696 696 checking their identity.
697 697 """
698 698 opts, varname = self.parse_options(parameter_s,'n')
699 699 try:
700 700 self.shell.del_var(varname, ('n' in opts))
701 701 except (NameError, ValueError) as e:
702 702 print type(e).__name__ +": "+ str(e)
@@ -1,674 +1,674 b''
1 1 """Implementation of magic functions for interaction with the OS.
2 2
3 3 Note: this module is named 'osm' instead of 'os' to avoid a collision with the
4 4 builtin.
5 5 """
6 6 #-----------------------------------------------------------------------------
7 7 # Copyright (c) 2012 The IPython Development Team.
8 8 #
9 9 # Distributed under the terms of the Modified BSD License.
10 10 #
11 11 # The full license is in the file COPYING.txt, distributed with this software.
12 12 #-----------------------------------------------------------------------------
13 13
14 14 #-----------------------------------------------------------------------------
15 15 # Imports
16 16 #-----------------------------------------------------------------------------
17 17
18 18 # Stdlib
19 19 import os
20 20 import re
21 21 import sys
22 22 from pprint import pformat
23 23
24 24 # Our own packages
25 25 from IPython.core import oinspect
26 26 from IPython.core import page
27 27 from IPython.core.error import UsageError
28 28 from IPython.core.magic import (Magics, compress_dhist, magics_class,
29 29 line_magic)
30 30 from IPython.testing.skipdoctest import skip_doctest
31 31 from IPython.utils.io import file_read, nlprint
32 32 from IPython.utils.path import get_py_filename, unquote_filename
33 33 from IPython.utils.process import abbrev_cwd
34 34 from IPython.utils.terminal import set_term_title
35 35 #-----------------------------------------------------------------------------
36 36 # Magic implementation classes
37 37 #-----------------------------------------------------------------------------
38 38 @magics_class
39 39 class OSMagics(Magics):
40 40 """Magics to interact with the underlying OS (shell-type functionality).
41 41 """
42 42
43 43 @skip_doctest
44 44 @line_magic
45 45 def alias(self, parameter_s=''):
46 46 """Define an alias for a system command.
47 47
48 48 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
49 49
50 50 Then, typing 'alias_name params' will execute the system command 'cmd
51 51 params' (from your underlying operating system).
52 52
53 53 Aliases have lower precedence than magic functions and Python normal
54 54 variables, so if 'foo' is both a Python variable and an alias, the
55 55 alias can not be executed until 'del foo' removes the Python variable.
56 56
57 57 You can use the %l specifier in an alias definition to represent the
58 58 whole line when the alias is called. For example::
59 59
60 60 In [2]: alias bracket echo "Input in brackets: <%l>"
61 61 In [3]: bracket hello world
62 62 Input in brackets: <hello world>
63 63
64 64 You can also define aliases with parameters using %s specifiers (one
65 65 per parameter)::
66 66
67 67 In [1]: alias parts echo first %s second %s
68 68 In [2]: %parts A B
69 69 first A second B
70 70 In [3]: %parts A
71 71 Incorrect number of arguments: 2 expected.
72 72 parts is an alias to: 'echo first %s second %s'
73 73
74 74 Note that %l and %s are mutually exclusive. You can only use one or
75 75 the other in your aliases.
76 76
77 77 Aliases expand Python variables just like system calls using ! or !!
78 78 do: all expressions prefixed with '$' get expanded. For details of
79 79 the semantic rules, see PEP-215:
80 80 http://www.python.org/peps/pep-0215.html. This is the library used by
81 81 IPython for variable expansion. If you want to access a true shell
82 82 variable, an extra $ is necessary to prevent its expansion by
83 83 IPython::
84 84
85 85 In [6]: alias show echo
86 86 In [7]: PATH='A Python string'
87 87 In [8]: show $PATH
88 88 A Python string
89 89 In [9]: show $$PATH
90 90 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
91 91
92 92 You can use the alias facility to acess all of $PATH. See the %rehash
93 93 and %rehashx functions, which automatically create aliases for the
94 94 contents of your $PATH.
95 95
96 96 If called with no parameters, %alias prints the current alias table."""
97 97
98 98 par = parameter_s.strip()
99 99 if not par:
100 100 aliases = sorted(self.shell.alias_manager.aliases)
101 101 # stored = self.shell.db.get('stored_aliases', {} )
102 102 # for k, v in stored:
103 103 # atab.append(k, v[0])
104 104
105 105 print "Total number of aliases:", len(aliases)
106 106 sys.stdout.flush()
107 107 return aliases
108 108
109 109 # Now try to define a new one
110 110 try:
111 111 alias,cmd = par.split(None, 1)
112 112 except:
113 113 print oinspect.getdoc(self.alias)
114 114 else:
115 115 self.shell.alias_manager.soft_define_alias(alias, cmd)
116 116 # end magic_alias
117 117
118 118 @line_magic
119 119 def unalias(self, parameter_s=''):
120 120 """Remove an alias"""
121 121
122 122 aname = parameter_s.strip()
123 123 self.shell.alias_manager.undefine_alias(aname)
124 124 stored = self.shell.db.get('stored_aliases', {} )
125 125 if aname in stored:
126 126 print "Removing %stored alias",aname
127 127 del stored[aname]
128 128 self.shell.db['stored_aliases'] = stored
129 129
130 130 @line_magic
131 131 def rehashx(self, parameter_s=''):
132 132 """Update the alias table with all executable files in $PATH.
133 133
134 134 This version explicitly checks that every entry in $PATH is a file
135 135 with execute access (os.X_OK), so it is much slower than %rehash.
136 136
137 137 Under Windows, it checks executability as a match against a
138 138 '|'-separated string of extensions, stored in the IPython config
139 139 variable win_exec_ext. This defaults to 'exe|com|bat'.
140 140
141 141 This function also resets the root module cache of module completer,
142 142 used on slow filesystems.
143 143 """
144 144 from IPython.core.alias import InvalidAliasError
145 145
146 146 # for the benefit of module completer in ipy_completers.py
147 147 del self.shell.db['rootmodules']
148 148
149 149 path = [os.path.abspath(os.path.expanduser(p)) for p in
150 150 os.environ.get('PATH','').split(os.pathsep)]
151 151 path = filter(os.path.isdir,path)
152 152
153 153 syscmdlist = []
154 154 # Now define isexec in a cross platform manner.
155 155 if os.name == 'posix':
156 156 isexec = lambda fname:os.path.isfile(fname) and \
157 157 os.access(fname,os.X_OK)
158 158 else:
159 159 try:
160 160 winext = os.environ['pathext'].replace(';','|').replace('.','')
161 161 except KeyError:
162 162 winext = 'exe|com|bat|py'
163 163 if 'py' not in winext:
164 164 winext += '|py'
165 165 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
166 166 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
167 167 savedir = os.getcwdu()
168 168
169 169 # Now walk the paths looking for executables to alias.
170 170 try:
171 171 # write the whole loop for posix/Windows so we don't have an if in
172 172 # the innermost part
173 173 if os.name == 'posix':
174 174 for pdir in path:
175 175 os.chdir(pdir)
176 176 for ff in os.listdir(pdir):
177 177 if isexec(ff):
178 178 try:
179 179 # Removes dots from the name since ipython
180 180 # will assume names with dots to be python.
181 181 self.shell.alias_manager.define_alias(
182 182 ff.replace('.',''), ff)
183 183 except InvalidAliasError:
184 184 pass
185 185 else:
186 186 syscmdlist.append(ff)
187 187 else:
188 188 no_alias = self.shell.alias_manager.no_alias
189 189 for pdir in path:
190 190 os.chdir(pdir)
191 191 for ff in os.listdir(pdir):
192 192 base, ext = os.path.splitext(ff)
193 193 if isexec(ff) and base.lower() not in no_alias:
194 194 if ext.lower() == '.exe':
195 195 ff = base
196 196 try:
197 197 # Removes dots from the name since ipython
198 198 # will assume names with dots to be python.
199 199 self.shell.alias_manager.define_alias(
200 200 base.lower().replace('.',''), ff)
201 201 except InvalidAliasError:
202 202 pass
203 203 syscmdlist.append(ff)
204 204 self.shell.db['syscmdlist'] = syscmdlist
205 205 finally:
206 206 os.chdir(savedir)
207 207
208 208 @skip_doctest
209 209 @line_magic
210 210 def pwd(self, parameter_s=''):
211 211 """Return the current working directory path.
212 212
213 213 Examples
214 214 --------
215 215 ::
216 216
217 217 In [9]: pwd
218 218 Out[9]: '/home/tsuser/sprint/ipython'
219 219 """
220 220 return os.getcwdu()
221 221
222 222 @skip_doctest
223 223 @line_magic
224 224 def cd(self, parameter_s=''):
225 225 """Change the current working directory.
226 226
227 227 This command automatically maintains an internal list of directories
228 228 you visit during your IPython session, in the variable _dh. The
229 229 command %dhist shows this history nicely formatted. You can also
230 230 do 'cd -<tab>' to see directory history conveniently.
231 231
232 232 Usage:
233 233
234 234 cd 'dir': changes to directory 'dir'.
235 235
236 236 cd -: changes to the last visited directory.
237 237
238 238 cd -<n>: changes to the n-th directory in the directory history.
239 239
240 240 cd --foo: change to directory that matches 'foo' in history
241 241
242 242 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
243 243 (note: cd <bookmark_name> is enough if there is no
244 244 directory <bookmark_name>, but a bookmark with the name exists.)
245 245 'cd -b <tab>' allows you to tab-complete bookmark names.
246 246
247 247 Options:
248 248
249 249 -q: quiet. Do not print the working directory after the cd command is
250 250 executed. By default IPython's cd command does print this directory,
251 251 since the default prompts do not display path information.
252 252
253 253 Note that !cd doesn't work for this purpose because the shell where
254 254 !command runs is immediately discarded after executing 'command'.
255 255
256 256 Examples
257 257 --------
258 258 ::
259 259
260 260 In [10]: cd parent/child
261 261 /home/tsuser/parent/child
262 262 """
263 263
264 264 oldcwd = os.getcwdu()
265 265 numcd = re.match(r'(-)(\d+)$',parameter_s)
266 266 # jump in directory history by number
267 267 if numcd:
268 268 nn = int(numcd.group(2))
269 269 try:
270 270 ps = self.shell.user_ns['_dh'][nn]
271 271 except IndexError:
272 272 print 'The requested directory does not exist in history.'
273 273 return
274 274 else:
275 275 opts = {}
276 276 elif parameter_s.startswith('--'):
277 277 ps = None
278 278 fallback = None
279 279 pat = parameter_s[2:]
280 280 dh = self.shell.user_ns['_dh']
281 281 # first search only by basename (last component)
282 282 for ent in reversed(dh):
283 283 if pat in os.path.basename(ent) and os.path.isdir(ent):
284 284 ps = ent
285 285 break
286 286
287 287 if fallback is None and pat in ent and os.path.isdir(ent):
288 288 fallback = ent
289 289
290 290 # if we have no last part match, pick the first full path match
291 291 if ps is None:
292 292 ps = fallback
293 293
294 294 if ps is None:
295 295 print "No matching entry in directory history"
296 296 return
297 297 else:
298 298 opts = {}
299 299
300 300
301 301 else:
302 302 #turn all non-space-escaping backslashes to slashes,
303 303 # for c:\windows\directory\names\
304 304 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
305 305 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
306 306 # jump to previous
307 307 if ps == '-':
308 308 try:
309 309 ps = self.shell.user_ns['_dh'][-2]
310 310 except IndexError:
311 311 raise UsageError('%cd -: No previous directory to change to.')
312 312 # jump to bookmark if needed
313 313 else:
314 314 if not os.path.isdir(ps) or 'b' in opts:
315 315 bkms = self.shell.db.get('bookmarks', {})
316 316
317 317 if ps in bkms:
318 318 target = bkms[ps]
319 print '(bookmark:%s) -> %s' % (ps,target)
319 print '(bookmark:%s) -> %s' % (ps, target)
320 320 ps = target
321 321 else:
322 322 if 'b' in opts:
323 323 raise UsageError("Bookmark '%s' not found. "
324 324 "Use '%%bookmark -l' to see your bookmarks." % ps)
325 325
326 326 # strip extra quotes on Windows, because os.chdir doesn't like them
327 327 ps = unquote_filename(ps)
328 328 # at this point ps should point to the target dir
329 329 if ps:
330 330 try:
331 331 os.chdir(os.path.expanduser(ps))
332 332 if hasattr(self.shell, 'term_title') and self.shell.term_title:
333 333 set_term_title('IPython: ' + abbrev_cwd())
334 334 except OSError:
335 335 print sys.exc_info()[1]
336 336 else:
337 337 cwd = os.getcwdu()
338 338 dhist = self.shell.user_ns['_dh']
339 339 if oldcwd != cwd:
340 340 dhist.append(cwd)
341 341 self.shell.db['dhist'] = compress_dhist(dhist)[-100:]
342 342
343 343 else:
344 344 os.chdir(self.shell.home_dir)
345 345 if hasattr(self.shell, 'term_title') and self.shell.term_title:
346 346 set_term_title('IPython: ' + '~')
347 347 cwd = os.getcwdu()
348 348 dhist = self.shell.user_ns['_dh']
349 349
350 350 if oldcwd != cwd:
351 351 dhist.append(cwd)
352 352 self.shell.db['dhist'] = compress_dhist(dhist)[-100:]
353 353 if not 'q' in opts and self.shell.user_ns['_dh']:
354 354 print self.shell.user_ns['_dh'][-1]
355 355
356 356
357 357 @line_magic
358 358 def env(self, parameter_s=''):
359 359 """List environment variables."""
360 360
361 361 return dict(os.environ)
362 362
363 363 @line_magic
364 364 def pushd(self, parameter_s=''):
365 365 """Place the current dir on stack and change directory.
366 366
367 367 Usage:\\
368 368 %pushd ['dirname']
369 369 """
370 370
371 371 dir_s = self.shell.dir_stack
372 372 tgt = os.path.expanduser(unquote_filename(parameter_s))
373 373 cwd = os.getcwdu().replace(self.shell.home_dir,'~')
374 374 if tgt:
375 375 self.cd(parameter_s)
376 376 dir_s.insert(0,cwd)
377 377 return self.shell.magic('dirs')
378 378
379 379 @line_magic
380 380 def popd(self, parameter_s=''):
381 381 """Change to directory popped off the top of the stack.
382 382 """
383 383 if not self.shell.dir_stack:
384 384 raise UsageError("%popd on empty stack")
385 385 top = self.shell.dir_stack.pop(0)
386 386 self.cd(top)
387 387 print "popd ->",top
388 388
389 389 @line_magic
390 390 def dirs(self, parameter_s=''):
391 391 """Return the current directory stack."""
392 392
393 393 return self.shell.dir_stack
394 394
395 395 @line_magic
396 396 def dhist(self, parameter_s=''):
397 397 """Print your history of visited directories.
398 398
399 399 %dhist -> print full history\\
400 400 %dhist n -> print last n entries only\\
401 401 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
402 402
403 403 This history is automatically maintained by the %cd command, and
404 404 always available as the global list variable _dh. You can use %cd -<n>
405 405 to go to directory number <n>.
406 406
407 407 Note that most of time, you should view directory history by entering
408 408 cd -<TAB>.
409 409
410 410 """
411 411
412 412 dh = self.shell.user_ns['_dh']
413 413 if parameter_s:
414 414 try:
415 415 args = map(int,parameter_s.split())
416 416 except:
417 417 self.arg_err(self.dhist)
418 418 return
419 419 if len(args) == 1:
420 420 ini,fin = max(len(dh)-(args[0]),0),len(dh)
421 421 elif len(args) == 2:
422 422 ini,fin = args
423 423 else:
424 424 self.arg_err(self.dhist)
425 425 return
426 426 else:
427 427 ini,fin = 0,len(dh)
428 428 nlprint(dh,
429 429 header = 'Directory history (kept in _dh)',
430 430 start=ini,stop=fin)
431 431
432 432 @skip_doctest
433 433 @line_magic
434 434 def sc(self, parameter_s=''):
435 435 """Shell capture - execute a shell command and capture its output.
436 436
437 437 DEPRECATED. Suboptimal, retained for backwards compatibility.
438 438
439 439 You should use the form 'var = !command' instead. Example:
440 440
441 441 "%sc -l myfiles = ls ~" should now be written as
442 442
443 443 "myfiles = !ls ~"
444 444
445 445 myfiles.s, myfiles.l and myfiles.n still apply as documented
446 446 below.
447 447
448 448 --
449 449 %sc [options] varname=command
450 450
451 451 IPython will run the given command using commands.getoutput(), and
452 452 will then update the user's interactive namespace with a variable
453 453 called varname, containing the value of the call. Your command can
454 454 contain shell wildcards, pipes, etc.
455 455
456 456 The '=' sign in the syntax is mandatory, and the variable name you
457 457 supply must follow Python's standard conventions for valid names.
458 458
459 459 (A special format without variable name exists for internal use)
460 460
461 461 Options:
462 462
463 463 -l: list output. Split the output on newlines into a list before
464 464 assigning it to the given variable. By default the output is stored
465 465 as a single string.
466 466
467 467 -v: verbose. Print the contents of the variable.
468 468
469 469 In most cases you should not need to split as a list, because the
470 470 returned value is a special type of string which can automatically
471 471 provide its contents either as a list (split on newlines) or as a
472 472 space-separated string. These are convenient, respectively, either
473 473 for sequential processing or to be passed to a shell command.
474 474
475 475 For example::
476 476
477 477 # Capture into variable a
478 478 In [1]: sc a=ls *py
479 479
480 480 # a is a string with embedded newlines
481 481 In [2]: a
482 482 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
483 483
484 484 # which can be seen as a list:
485 485 In [3]: a.l
486 486 Out[3]: ['setup.py', 'win32_manual_post_install.py']
487 487
488 488 # or as a whitespace-separated string:
489 489 In [4]: a.s
490 490 Out[4]: 'setup.py win32_manual_post_install.py'
491 491
492 492 # a.s is useful to pass as a single command line:
493 493 In [5]: !wc -l $a.s
494 494 146 setup.py
495 495 130 win32_manual_post_install.py
496 496 276 total
497 497
498 498 # while the list form is useful to loop over:
499 499 In [6]: for f in a.l:
500 500 ...: !wc -l $f
501 501 ...:
502 502 146 setup.py
503 503 130 win32_manual_post_install.py
504 504
505 505 Similarly, the lists returned by the -l option are also special, in
506 506 the sense that you can equally invoke the .s attribute on them to
507 507 automatically get a whitespace-separated string from their contents::
508 508
509 509 In [7]: sc -l b=ls *py
510 510
511 511 In [8]: b
512 512 Out[8]: ['setup.py', 'win32_manual_post_install.py']
513 513
514 514 In [9]: b.s
515 515 Out[9]: 'setup.py win32_manual_post_install.py'
516 516
517 517 In summary, both the lists and strings used for output capture have
518 518 the following special attributes::
519 519
520 520 .l (or .list) : value as list.
521 521 .n (or .nlstr): value as newline-separated string.
522 522 .s (or .spstr): value as space-separated string.
523 523 """
524 524
525 opts,args = self.parse_options(parameter_s,'lv')
525 opts,args = self.parse_options(parameter_s, 'lv')
526 526 # Try to get a variable name and command to run
527 527 try:
528 528 # the variable name must be obtained from the parse_options
529 529 # output, which uses shlex.split to strip options out.
530 var,_ = args.split('=',1)
530 var,_ = args.split('=', 1)
531 531 var = var.strip()
532 532 # But the command has to be extracted from the original input
533 533 # parameter_s, not on what parse_options returns, to avoid the
534 534 # quote stripping which shlex.split performs on it.
535 _,cmd = parameter_s.split('=',1)
535 _,cmd = parameter_s.split('=', 1)
536 536 except ValueError:
537 537 var,cmd = '',''
538 538 # If all looks ok, proceed
539 539 split = 'l' in opts
540 540 out = self.shell.getoutput(cmd, split=split)
541 541 if 'v' in opts:
542 print '%s ==\n%s' % (var,pformat(out))
542 print '%s ==\n%s' % (var, pformat(out))
543 543 if var:
544 544 self.shell.user_ns.update({var:out})
545 545 else:
546 546 return out
547 547
548 548 @line_magic
549 549 def sx(self, parameter_s=''):
550 550 """Shell execute - run a shell command and capture its output.
551 551
552 552 %sx command
553 553
554 554 IPython will run the given command using commands.getoutput(), and
555 555 return the result formatted as a list (split on '\\n'). Since the
556 556 output is _returned_, it will be stored in ipython's regular output
557 557 cache Out[N] and in the '_N' automatic variables.
558 558
559 559 Notes:
560 560
561 561 1) If an input line begins with '!!', then %sx is automatically
562 562 invoked. That is, while::
563 563
564 564 !ls
565 565
566 566 causes ipython to simply issue system('ls'), typing::
567 567
568 568 !!ls
569 569
570 570 is a shorthand equivalent to::
571 571
572 572 %sx ls
573 573
574 574 2) %sx differs from %sc in that %sx automatically splits into a list,
575 575 like '%sc -l'. The reason for this is to make it as easy as possible
576 576 to process line-oriented shell output via further python commands.
577 577 %sc is meant to provide much finer control, but requires more
578 578 typing.
579 579
580 580 3) Just like %sc -l, this is a list with special attributes:
581 581 ::
582 582
583 583 .l (or .list) : value as list.
584 584 .n (or .nlstr): value as newline-separated string.
585 585 .s (or .spstr): value as whitespace-separated string.
586 586
587 587 This is very useful when trying to use such lists as arguments to
588 588 system commands."""
589 589
590 590 if parameter_s:
591 591 return self.shell.getoutput(parameter_s)
592 592
593 593
594 594 @line_magic
595 595 def bookmark(self, parameter_s=''):
596 596 """Manage IPython's bookmark system.
597 597
598 598 %bookmark <name> - set bookmark to current dir
599 599 %bookmark <name> <dir> - set bookmark to <dir>
600 600 %bookmark -l - list all bookmarks
601 601 %bookmark -d <name> - remove bookmark
602 602 %bookmark -r - remove all bookmarks
603 603
604 604 You can later on access a bookmarked folder with::
605 605
606 606 %cd -b <name>
607 607
608 608 or simply '%cd <name>' if there is no directory called <name> AND
609 609 there is such a bookmark defined.
610 610
611 611 Your bookmarks persist through IPython sessions, but they are
612 612 associated with each profile."""
613 613
614 614 opts,args = self.parse_options(parameter_s,'drl',mode='list')
615 615 if len(args) > 2:
616 616 raise UsageError("%bookmark: too many arguments")
617 617
618 618 bkms = self.shell.db.get('bookmarks',{})
619 619
620 620 if 'd' in opts:
621 621 try:
622 622 todel = args[0]
623 623 except IndexError:
624 624 raise UsageError(
625 625 "%bookmark -d: must provide a bookmark to delete")
626 626 else:
627 627 try:
628 628 del bkms[todel]
629 629 except KeyError:
630 630 raise UsageError(
631 631 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
632 632
633 633 elif 'r' in opts:
634 634 bkms = {}
635 635 elif 'l' in opts:
636 636 bks = bkms.keys()
637 637 bks.sort()
638 638 if bks:
639 639 size = max(map(len, bks))
640 640 else:
641 641 size = 0
642 642 fmt = '%-'+str(size)+'s -> %s'
643 643 print 'Current bookmarks:'
644 644 for bk in bks:
645 645 print fmt % (bk, bkms[bk])
646 646 else:
647 647 if not args:
648 648 raise UsageError("%bookmark: You must specify the bookmark name")
649 649 elif len(args)==1:
650 650 bkms[args[0]] = os.getcwdu()
651 651 elif len(args)==2:
652 652 bkms[args[0]] = args[1]
653 653 self.shell.db['bookmarks'] = bkms
654 654
655 655 @line_magic
656 656 def pycat(self, parameter_s=''):
657 657 """Show a syntax-highlighted file through a pager.
658 658
659 659 This magic is similar to the cat utility, but it will assume the file
660 660 to be Python source and will show it with syntax highlighting. """
661 661
662 662 try:
663 663 filename = get_py_filename(parameter_s)
664 664 cont = file_read(filename)
665 665 except IOError:
666 666 try:
667 667 cont = eval(parameter_s, self.shell.user_ns)
668 668 except NameError:
669 669 cont = None
670 670 if cont is None:
671 671 print "Error: no such file or variable"
672 672 return
673 673
674 674 page.page(self.shell.pycolorize(cont))
@@ -1,218 +1,218 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 %store magic for lightweight persistence.
4 4
5 5 Stores variables, aliases and macros in IPython's database.
6 6
7 7 To automatically restore stored variables at startup, add this to your
8 8 :file:`ipython_config.py` file::
9 9
10 10 c.StoreMagic.autorestore = True
11 11 """
12 12
13 13 import inspect, os, sys, textwrap
14 14
15 15 from IPython.core.error import UsageError
16 16 from IPython.core.fakemodule import FakeModule
17 17 from IPython.core.magic import Magics, magics_class, line_magic
18 18 from IPython.core.plugin import Plugin
19 19 from IPython.testing.skipdoctest import skip_doctest
20 20 from IPython.utils.traitlets import Bool, Instance
21 21
22 22
23 23 def restore_aliases(ip):
24 24 staliases = ip.db.get('stored_aliases', {})
25 25 for k,v in staliases.items():
26 26 #print "restore alias",k,v # dbg
27 27 #self.alias_table[k] = v
28 28 ip.alias_manager.define_alias(k,v)
29 29
30 30
31 31 def refresh_variables(ip):
32 32 db = ip.db
33 33 for key in db.keys('autorestore/*'):
34 34 # strip autorestore
35 35 justkey = os.path.basename(key)
36 36 try:
37 37 obj = db[key]
38 38 except KeyError:
39 39 print "Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % justkey
40 40 print "The error was:", sys.exc_info()[0]
41 41 else:
42 42 #print "restored",justkey,"=",obj #dbg
43 43 ip.user_ns[justkey] = obj
44 44
45 45
46 46 def restore_dhist(ip):
47 47 ip.user_ns['_dh'] = ip.db.get('dhist',[])
48 48
49 49
50 50 def restore_data(ip):
51 51 refresh_variables(ip)
52 52 restore_aliases(ip)
53 53 restore_dhist(ip)
54 54
55 55
56 56 @magics_class
57 57 class StoreMagics(Magics):
58 58 """Lightweight persistence for python variables.
59 59
60 60 Provides the %store magic."""
61 61
62 62 @skip_doctest
63 63 @line_magic
64 64 def store(self, parameter_s=''):
65 65 """Lightweight persistence for python variables.
66 66
67 67 Example::
68 68
69 69 In [1]: l = ['hello',10,'world']
70 70 In [2]: %store l
71 71 In [3]: exit
72 72
73 73 (IPython session is closed and started again...)
74 74
75 75 ville@badger:~$ ipython
76 76 In [1]: l
77 77 Out[1]: ['hello', 10, 'world']
78 78
79 79 Usage:
80 80
81 81 * ``%store`` - Show list of all variables and their current
82 82 values
83 83 * ``%store spam`` - Store the *current* value of the variable spam
84 84 to disk
85 85 * ``%store -d spam`` - Remove the variable and its value from storage
86 86 * ``%store -z`` - Remove all variables from storage
87 87 * ``%store -r`` - Refresh all variables from store (delete
88 88 current vals)
89 89 * ``%store foo >a.txt`` - Store value of foo to new file a.txt
90 90 * ``%store foo >>a.txt`` - Append value of foo to file a.txt
91 91
92 92 It should be noted that if you change the value of a variable, you
93 93 need to %store it again if you want to persist the new value.
94 94
95 95 Note also that the variables will need to be pickleable; most basic
96 96 python types can be safely %store'd.
97 97
98 98 Also aliases can be %store'd across sessions.
99 99 """
100 100
101 101 opts,argsl = self.parse_options(parameter_s,'drz',mode='string')
102 102 args = argsl.split(None,1)
103 103 ip = self.shell
104 104 db = ip.db
105 105 # delete
106 106 if opts.has_key('d'):
107 107 try:
108 108 todel = args[0]
109 109 except IndexError:
110 110 raise UsageError('You must provide the variable to forget')
111 111 else:
112 112 try:
113 113 del db['autorestore/' + todel]
114 114 except:
115 115 raise UsageError("Can't delete variable '%s'" % todel)
116 116 # reset
117 117 elif opts.has_key('z'):
118 118 for k in db.keys('autorestore/*'):
119 119 del db[k]
120 120
121 121 elif opts.has_key('r'):
122 122 refresh_variables(ip)
123 123
124 124
125 125 # run without arguments -> list variables & values
126 126 elif not args:
127 127 vars = self.db.keys('autorestore/*')
128 128 vars.sort()
129 129 if vars:
130 size = max(map(len,vars))
130 size = max(map(len, vars))
131 131 else:
132 132 size = 0
133 133
134 134 print 'Stored variables and their in-db values:'
135 135 fmt = '%-'+str(size)+'s -> %s'
136 136 get = db.get
137 137 for var in vars:
138 138 justkey = os.path.basename(var)
139 139 # print 30 first characters from every var
140 print fmt % (justkey,repr(get(var,'<unavailable>'))[:50])
140 print fmt % (justkey, repr(get(var, '<unavailable>'))[:50])
141 141
142 142 # default action - store the variable
143 143 else:
144 144 # %store foo >file.txt or >>file.txt
145 145 if len(args) > 1 and args[1].startswith('>'):
146 146 fnam = os.path.expanduser(args[1].lstrip('>').lstrip())
147 147 if args[1].startswith('>>'):
148 fil = open(fnam,'a')
148 fil = open(fnam, 'a')
149 149 else:
150 fil = open(fnam,'w')
150 fil = open(fnam, 'w')
151 151 obj = ip.ev(args[0])
152 152 print "Writing '%s' (%s) to file '%s'." % (args[0],
153 153 obj.__class__.__name__, fnam)
154 154
155 155
156 if not isinstance (obj,basestring):
156 if not isinstance (obj, basestring):
157 157 from pprint import pprint
158 pprint(obj,fil)
158 pprint(obj, fil)
159 159 else:
160 160 fil.write(obj)
161 161 if not obj.endswith('\n'):
162 162 fil.write('\n')
163 163
164 164 fil.close()
165 165 return
166 166
167 167 # %store foo
168 168 try:
169 169 obj = ip.user_ns[args[0]]
170 170 except KeyError:
171 171 # it might be an alias
172 172 # This needs to be refactored to use the new AliasManager stuff.
173 173 if args[0] in self.alias_manager:
174 174 name = args[0]
175 175 nargs, cmd = self.alias_manager.alias_table[ name ]
176 176 staliases = db.get('stored_aliases',{})
177 177 staliases[ name ] = cmd
178 178 db['stored_aliases'] = staliases
179 179 print "Alias stored: %s (%s)" % (name, cmd)
180 180 return
181 181 else:
182 182 raise UsageError("Unknown variable '%s'" % args[0])
183 183
184 184 else:
185 185 if isinstance(inspect.getmodule(obj), FakeModule):
186 186 print textwrap.dedent("""\
187 187 Warning:%s is %s
188 188 Proper storage of interactively declared classes (or instances
189 189 of those classes) is not possible! Only instances
190 190 of classes in real modules on file system can be %%store'd.
191 191 """ % (args[0], obj) )
192 192 return
193 193 #pickled = pickle.dumps(obj)
194 194 self.db[ 'autorestore/' + args[0] ] = obj
195 195 print "Stored '%s' (%s)" % (args[0], obj.__class__.__name__)
196 196
197 197
198 198 class StoreMagic(Plugin):
199 199 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
200 200 autorestore = Bool(False, config=True)
201 201
202 202 def __init__(self, shell, config):
203 203 super(StoreMagic, self).__init__(shell=shell, config=config)
204 204 shell.register_magics(StoreMagics)
205 205
206 206 if self.autorestore:
207 207 restore_data(shell)
208 208
209 209
210 210 _loaded = False
211 211
212 212 def load_ipython_extension(ip):
213 213 """Load the extension in IPython."""
214 214 global _loaded
215 215 if not _loaded:
216 216 plugin = StoreMagic(shell=ip, config=ip.config)
217 217 ip.plugin_manager.register_plugin('storemagic', plugin)
218 218 _loaded = True
General Comments 0
You need to be logged in to leave comments. Login now