##// END OF EJS Templates
Fix paste/cpaste bug and refactor/cleanup that code a lot....
Fernando Perez -
Show More
@@ -1,3738 +1,3678 b''
1 1 # encoding: utf-8
2 2 """Magic functions for InteractiveShell.
3 3 """
4 4
5 5 #-----------------------------------------------------------------------------
6 6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 7 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
8 8 # Copyright (C) 2008-2011 The IPython Development Team
9 9
10 10 # Distributed under the terms of the BSD License. The full license is in
11 11 # the file COPYING, distributed as part of this software.
12 12 #-----------------------------------------------------------------------------
13 13
14 14 #-----------------------------------------------------------------------------
15 15 # Imports
16 16 #-----------------------------------------------------------------------------
17 17
18 18 import __builtin__ as builtin_mod
19 19 import __future__
20 20 import bdb
21 21 import inspect
22 22 import imp
23 23 import os
24 24 import sys
25 25 import shutil
26 26 import re
27 27 import time
28 import textwrap
29 28 from StringIO import StringIO
30 29 from getopt import getopt,GetoptError
31 30 from pprint import pformat
32 31 from xmlrpclib import ServerProxy
33 32
34 33 # cProfile was added in Python2.5
35 34 try:
36 35 import cProfile as profile
37 36 import pstats
38 37 except ImportError:
39 38 # profile isn't bundled by default in Debian for license reasons
40 39 try:
41 40 import profile,pstats
42 41 except ImportError:
43 42 profile = pstats = None
44 43
45 44 import IPython
46 45 from IPython.core import debugger, oinspect
47 46 from IPython.core.error import TryNext
48 47 from IPython.core.error import UsageError
49 48 from IPython.core.fakemodule import FakeModule
50 49 from IPython.core.profiledir import ProfileDir
51 50 from IPython.core.macro import Macro
52 51 from IPython.core import magic_arguments, page
53 52 from IPython.core.prefilter import ESC_MAGIC
54 53 from IPython.lib.pylabtools import mpl_runner
55 54 from IPython.testing.skipdoctest import skip_doctest
56 55 from IPython.utils import py3compat
57 56 from IPython.utils.io import file_read, nlprint
58 57 from IPython.utils.module_paths import find_mod
59 58 from IPython.utils.path import get_py_filename, unquote_filename
60 59 from IPython.utils.process import arg_split, abbrev_cwd
61 60 from IPython.utils.terminal import set_term_title
62 61 from IPython.utils.text import LSString, SList, format_screen
63 62 from IPython.utils.timing import clock, clock2
64 63 from IPython.utils.warn import warn, error
65 64 from IPython.utils.ipstruct import Struct
66 65 from IPython.config.application import Application
67 66
68 67 #-----------------------------------------------------------------------------
69 68 # Utility functions
70 69 #-----------------------------------------------------------------------------
71 70
72 71 def on_off(tag):
73 72 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
74 73 return ['OFF','ON'][tag]
75 74
76 75 class Bunch: pass
77 76
78 77 def compress_dhist(dh):
79 78 head, tail = dh[:-10], dh[-10:]
80 79
81 80 newhead = []
82 81 done = set()
83 82 for h in head:
84 83 if h in done:
85 84 continue
86 85 newhead.append(h)
87 86 done.add(h)
88 87
89 88 return newhead + tail
90 89
91 90 def needs_local_scope(func):
92 91 """Decorator to mark magic functions which need to local scope to run."""
93 92 func.needs_local_scope = True
94 93 return func
95 94
96 95
97 96 # Used for exception handling in magic_edit
98 97 class MacroToEdit(ValueError): pass
99 98
100 99 #***************************************************************************
101 100 # Main class implementing Magic functionality
102 101
103 102 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
104 103 # on construction of the main InteractiveShell object. Something odd is going
105 104 # on with super() calls, Configurable and the MRO... For now leave it as-is, but
106 105 # eventually this needs to be clarified.
107 106 # BG: This is because InteractiveShell inherits from this, but is itself a
108 107 # Configurable. This messes up the MRO in some way. The fix is that we need to
109 108 # make Magic a configurable that InteractiveShell does not subclass.
110 109
111 110 class Magic:
112 111 """Magic functions for InteractiveShell.
113 112
114 113 Shell functions which can be reached as %function_name. All magic
115 114 functions should accept a string, which they can parse for their own
116 115 needs. This can make some functions easier to type, eg `%cd ../`
117 116 vs. `%cd("../")`
118 117
119 118 ALL definitions MUST begin with the prefix magic_. The user won't need it
120 119 at the command line, but it is is needed in the definition. """
121 120
122 121 # class globals
123 122 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
124 123 'Automagic is ON, % prefix NOT needed for magic functions.']
125 124
126 125
127 126 configurables = None
128 127 #......................................................................
129 128 # some utility functions
130 129
131 130 def __init__(self,shell):
132 131
133 132 self.options_table = {}
134 133 if profile is None:
135 134 self.magic_prun = self.profile_missing_notice
136 135 self.shell = shell
137 136 if self.configurables is None:
138 137 self.configurables = []
139 138
140 139 # namespace for holding state we may need
141 140 self._magic_state = Bunch()
142 141
143 142 def profile_missing_notice(self, *args, **kwargs):
144 143 error("""\
145 144 The profile module could not be found. It has been removed from the standard
146 145 python packages because of its non-free license. To use profiling, install the
147 146 python-profiler package from non-free.""")
148 147
149 148 def default_option(self,fn,optstr):
150 149 """Make an entry in the options_table for fn, with value optstr"""
151 150
152 151 if fn not in self.lsmagic():
153 152 error("%s is not a magic function" % fn)
154 153 self.options_table[fn] = optstr
155 154
156 155 def lsmagic(self):
157 156 """Return a list of currently available magic functions.
158 157
159 158 Gives a list of the bare names after mangling (['ls','cd', ...], not
160 159 ['magic_ls','magic_cd',...]"""
161 160
162 161 # FIXME. This needs a cleanup, in the way the magics list is built.
163 162
164 163 # magics in class definition
165 164 class_magic = lambda fn: fn.startswith('magic_') and \
166 165 callable(Magic.__dict__[fn])
167 166 # in instance namespace (run-time user additions)
168 167 inst_magic = lambda fn: fn.startswith('magic_') and \
169 168 callable(self.__dict__[fn])
170 169 # and bound magics by user (so they can access self):
171 170 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
172 171 callable(self.__class__.__dict__[fn])
173 172 magics = filter(class_magic,Magic.__dict__.keys()) + \
174 173 filter(inst_magic,self.__dict__.keys()) + \
175 174 filter(inst_bound_magic,self.__class__.__dict__.keys())
176 175 out = []
177 176 for fn in set(magics):
178 177 out.append(fn.replace('magic_','',1))
179 178 out.sort()
180 179 return out
181 180
182 181 def extract_input_lines(self, range_str, raw=False):
183 182 """Return as a string a set of input history slices.
184 183
185 184 Inputs:
186 185
187 186 - range_str: the set of slices is given as a string, like
188 187 "~5/6-~4/2 4:8 9", since this function is for use by magic functions
189 188 which get their arguments as strings. The number before the / is the
190 189 session number: ~n goes n back from the current session.
191 190
192 191 Optional inputs:
193 192
194 193 - raw(False): by default, the processed input is used. If this is
195 194 true, the raw input history is used instead.
196 195
197 196 Note that slices can be called with two notations:
198 197
199 198 N:M -> standard python form, means including items N...(M-1).
200 199
201 200 N-M -> include items N..M (closed endpoint)."""
202 201 lines = self.shell.history_manager.\
203 202 get_range_by_str(range_str, raw=raw)
204 203 return "\n".join(x for _, _, x in lines)
205 204
206 205 def arg_err(self,func):
207 206 """Print docstring if incorrect arguments were passed"""
208 207 print 'Error in arguments:'
209 208 print oinspect.getdoc(func)
210 209
211 210 def format_latex(self,strng):
212 211 """Format a string for latex inclusion."""
213 212
214 213 # Characters that need to be escaped for latex:
215 214 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
216 215 # Magic command names as headers:
217 216 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
218 217 re.MULTILINE)
219 218 # Magic commands
220 219 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
221 220 re.MULTILINE)
222 221 # Paragraph continue
223 222 par_re = re.compile(r'\\$',re.MULTILINE)
224 223
225 224 # The "\n" symbol
226 225 newline_re = re.compile(r'\\n')
227 226
228 227 # Now build the string for output:
229 228 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
230 229 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
231 230 strng)
232 231 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
233 232 strng = par_re.sub(r'\\\\',strng)
234 233 strng = escape_re.sub(r'\\\1',strng)
235 234 strng = newline_re.sub(r'\\textbackslash{}n',strng)
236 235 return strng
237 236
238 237 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
239 238 """Parse options passed to an argument string.
240 239
241 240 The interface is similar to that of getopt(), but it returns back a
242 241 Struct with the options as keys and the stripped argument string still
243 242 as a string.
244 243
245 244 arg_str is quoted as a true sys.argv vector by using shlex.split.
246 245 This allows us to easily expand variables, glob files, quote
247 246 arguments, etc.
248 247
249 248 Options:
250 249 -mode: default 'string'. If given as 'list', the argument string is
251 250 returned as a list (split on whitespace) instead of a string.
252 251
253 252 -list_all: put all option values in lists. Normally only options
254 253 appearing more than once are put in a list.
255 254
256 255 -posix (True): whether to split the input line in POSIX mode or not,
257 256 as per the conventions outlined in the shlex module from the
258 257 standard library."""
259 258
260 259 # inject default options at the beginning of the input line
261 260 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
262 261 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
263 262
264 263 mode = kw.get('mode','string')
265 264 if mode not in ['string','list']:
266 265 raise ValueError,'incorrect mode given: %s' % mode
267 266 # Get options
268 267 list_all = kw.get('list_all',0)
269 268 posix = kw.get('posix', os.name == 'posix')
270 269
271 270 # Check if we have more than one argument to warrant extra processing:
272 271 odict = {} # Dictionary with options
273 272 args = arg_str.split()
274 273 if len(args) >= 1:
275 274 # If the list of inputs only has 0 or 1 thing in it, there's no
276 275 # need to look for options
277 276 argv = arg_split(arg_str,posix)
278 277 # Do regular option processing
279 278 try:
280 279 opts,args = getopt(argv,opt_str,*long_opts)
281 280 except GetoptError,e:
282 281 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
283 282 " ".join(long_opts)))
284 283 for o,a in opts:
285 284 if o.startswith('--'):
286 285 o = o[2:]
287 286 else:
288 287 o = o[1:]
289 288 try:
290 289 odict[o].append(a)
291 290 except AttributeError:
292 291 odict[o] = [odict[o],a]
293 292 except KeyError:
294 293 if list_all:
295 294 odict[o] = [a]
296 295 else:
297 296 odict[o] = a
298 297
299 298 # Prepare opts,args for return
300 299 opts = Struct(odict)
301 300 if mode == 'string':
302 301 args = ' '.join(args)
303 302
304 303 return opts,args
305 304
306 305 #......................................................................
307 306 # And now the actual magic functions
308 307
309 308 # Functions for IPython shell work (vars,funcs, config, etc)
310 309 def magic_lsmagic(self, parameter_s = ''):
311 310 """List currently available magic functions."""
312 311 mesc = ESC_MAGIC
313 312 print 'Available magic functions:\n'+mesc+\
314 313 (' '+mesc).join(self.lsmagic())
315 314 print '\n' + Magic.auto_status[self.shell.automagic]
316 315 return None
317 316
318 317 def magic_magic(self, parameter_s = ''):
319 318 """Print information about the magic function system.
320 319
321 320 Supported formats: -latex, -brief, -rest
322 321 """
323 322
324 323 mode = ''
325 324 try:
326 325 if parameter_s.split()[0] == '-latex':
327 326 mode = 'latex'
328 327 if parameter_s.split()[0] == '-brief':
329 328 mode = 'brief'
330 329 if parameter_s.split()[0] == '-rest':
331 330 mode = 'rest'
332 331 rest_docs = []
333 332 except:
334 333 pass
335 334
336 335 magic_docs = []
337 336 for fname in self.lsmagic():
338 337 mname = 'magic_' + fname
339 338 for space in (Magic,self,self.__class__):
340 339 try:
341 340 fn = space.__dict__[mname]
342 341 except KeyError:
343 342 pass
344 343 else:
345 344 break
346 345 if mode == 'brief':
347 346 # only first line
348 347 if fn.__doc__:
349 348 fndoc = fn.__doc__.split('\n',1)[0]
350 349 else:
351 350 fndoc = 'No documentation'
352 351 else:
353 352 if fn.__doc__:
354 353 fndoc = fn.__doc__.rstrip()
355 354 else:
356 355 fndoc = 'No documentation'
357 356
358 357
359 358 if mode == 'rest':
360 359 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
361 360 fname,fndoc))
362 361
363 362 else:
364 363 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
365 364 fname,fndoc))
366 365
367 366 magic_docs = ''.join(magic_docs)
368 367
369 368 if mode == 'rest':
370 369 return "".join(rest_docs)
371 370
372 371 if mode == 'latex':
373 372 print self.format_latex(magic_docs)
374 373 return
375 374 else:
376 375 magic_docs = format_screen(magic_docs)
377 376 if mode == 'brief':
378 377 return magic_docs
379 378
380 379 outmsg = """
381 380 IPython's 'magic' functions
382 381 ===========================
383 382
384 383 The magic function system provides a series of functions which allow you to
385 384 control the behavior of IPython itself, plus a lot of system-type
386 385 features. All these functions are prefixed with a % character, but parameters
387 386 are given without parentheses or quotes.
388 387
389 388 NOTE: If you have 'automagic' enabled (via the command line option or with the
390 389 %automagic function), you don't need to type in the % explicitly. By default,
391 390 IPython ships with automagic on, so you should only rarely need the % escape.
392 391
393 392 Example: typing '%cd mydir' (without the quotes) changes you working directory
394 393 to 'mydir', if it exists.
395 394
396 395 For a list of the available magic functions, use %lsmagic. For a description
397 396 of any of them, type %magic_name?, e.g. '%cd?'.
398 397
399 398 Currently the magic system has the following functions:\n"""
400 399
401 400 mesc = ESC_MAGIC
402 401 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
403 402 "\n\n%s%s\n\n%s" % (outmsg,
404 403 magic_docs,mesc,mesc,
405 404 (' '+mesc).join(self.lsmagic()),
406 405 Magic.auto_status[self.shell.automagic] ) )
407 406 page.page(outmsg)
408 407
409 408 def magic_automagic(self, parameter_s = ''):
410 409 """Make magic functions callable without having to type the initial %.
411 410
412 411 Without argumentsl toggles on/off (when off, you must call it as
413 412 %automagic, of course). With arguments it sets the value, and you can
414 413 use any of (case insensitive):
415 414
416 415 - on,1,True: to activate
417 416
418 417 - off,0,False: to deactivate.
419 418
420 419 Note that magic functions have lowest priority, so if there's a
421 420 variable whose name collides with that of a magic fn, automagic won't
422 421 work for that function (you get the variable instead). However, if you
423 422 delete the variable (del var), the previously shadowed magic function
424 423 becomes visible to automagic again."""
425 424
426 425 arg = parameter_s.lower()
427 426 if parameter_s in ('on','1','true'):
428 427 self.shell.automagic = True
429 428 elif parameter_s in ('off','0','false'):
430 429 self.shell.automagic = False
431 430 else:
432 431 self.shell.automagic = not self.shell.automagic
433 432 print '\n' + Magic.auto_status[self.shell.automagic]
434 433
435 434 @skip_doctest
436 435 def magic_autocall(self, parameter_s = ''):
437 436 """Make functions callable without having to type parentheses.
438 437
439 438 Usage:
440 439
441 440 %autocall [mode]
442 441
443 442 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
444 443 value is toggled on and off (remembering the previous state).
445 444
446 445 In more detail, these values mean:
447 446
448 447 0 -> fully disabled
449 448
450 449 1 -> active, but do not apply if there are no arguments on the line.
451 450
452 451 In this mode, you get:
453 452
454 453 In [1]: callable
455 454 Out[1]: <built-in function callable>
456 455
457 456 In [2]: callable 'hello'
458 457 ------> callable('hello')
459 458 Out[2]: False
460 459
461 460 2 -> Active always. Even if no arguments are present, the callable
462 461 object is called:
463 462
464 463 In [2]: float
465 464 ------> float()
466 465 Out[2]: 0.0
467 466
468 467 Note that even with autocall off, you can still use '/' at the start of
469 468 a line to treat the first argument on the command line as a function
470 469 and add parentheses to it:
471 470
472 471 In [8]: /str 43
473 472 ------> str(43)
474 473 Out[8]: '43'
475 474
476 475 # all-random (note for auto-testing)
477 476 """
478 477
479 478 if parameter_s:
480 479 arg = int(parameter_s)
481 480 else:
482 481 arg = 'toggle'
483 482
484 483 if not arg in (0,1,2,'toggle'):
485 484 error('Valid modes: (0->Off, 1->Smart, 2->Full')
486 485 return
487 486
488 487 if arg in (0,1,2):
489 488 self.shell.autocall = arg
490 489 else: # toggle
491 490 if self.shell.autocall:
492 491 self._magic_state.autocall_save = self.shell.autocall
493 492 self.shell.autocall = 0
494 493 else:
495 494 try:
496 495 self.shell.autocall = self._magic_state.autocall_save
497 496 except AttributeError:
498 497 self.shell.autocall = self._magic_state.autocall_save = 1
499 498
500 499 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
501 500
502 501
503 502 def magic_page(self, parameter_s=''):
504 503 """Pretty print the object and display it through a pager.
505 504
506 505 %page [options] OBJECT
507 506
508 507 If no object is given, use _ (last output).
509 508
510 509 Options:
511 510
512 511 -r: page str(object), don't pretty-print it."""
513 512
514 513 # After a function contributed by Olivier Aubert, slightly modified.
515 514
516 515 # Process options/args
517 516 opts,args = self.parse_options(parameter_s,'r')
518 517 raw = 'r' in opts
519 518
520 519 oname = args and args or '_'
521 520 info = self._ofind(oname)
522 521 if info['found']:
523 522 txt = (raw and str or pformat)( info['obj'] )
524 523 page.page(txt)
525 524 else:
526 525 print 'Object `%s` not found' % oname
527 526
528 527 def magic_profile(self, parameter_s=''):
529 528 """Print your currently active IPython profile."""
530 529 from IPython.core.application import BaseIPythonApplication
531 530 if BaseIPythonApplication.initialized():
532 531 print BaseIPythonApplication.instance().profile
533 532 else:
534 533 error("profile is an application-level value, but you don't appear to be in an IPython application")
535 534
536 535 def magic_pinfo(self, parameter_s='', namespaces=None):
537 536 """Provide detailed information about an object.
538 537
539 538 '%pinfo object' is just a synonym for object? or ?object."""
540 539
541 540 #print 'pinfo par: <%s>' % parameter_s # dbg
542 541
543 542
544 543 # detail_level: 0 -> obj? , 1 -> obj??
545 544 detail_level = 0
546 545 # We need to detect if we got called as 'pinfo pinfo foo', which can
547 546 # happen if the user types 'pinfo foo?' at the cmd line.
548 547 pinfo,qmark1,oname,qmark2 = \
549 548 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
550 549 if pinfo or qmark1 or qmark2:
551 550 detail_level = 1
552 551 if "*" in oname:
553 552 self.magic_psearch(oname)
554 553 else:
555 554 self.shell._inspect('pinfo', oname, detail_level=detail_level,
556 555 namespaces=namespaces)
557 556
558 557 def magic_pinfo2(self, parameter_s='', namespaces=None):
559 558 """Provide extra detailed information about an object.
560 559
561 560 '%pinfo2 object' is just a synonym for object?? or ??object."""
562 561 self.shell._inspect('pinfo', parameter_s, detail_level=1,
563 562 namespaces=namespaces)
564 563
565 564 @skip_doctest
566 565 def magic_pdef(self, parameter_s='', namespaces=None):
567 566 """Print the definition header for any callable object.
568 567
569 568 If the object is a class, print the constructor information.
570 569
571 570 Examples
572 571 --------
573 572 ::
574 573
575 574 In [3]: %pdef urllib.urlopen
576 575 urllib.urlopen(url, data=None, proxies=None)
577 576 """
578 577 self._inspect('pdef',parameter_s, namespaces)
579 578
580 579 def magic_pdoc(self, parameter_s='', namespaces=None):
581 580 """Print the docstring for an object.
582 581
583 582 If the given object is a class, it will print both the class and the
584 583 constructor docstrings."""
585 584 self._inspect('pdoc',parameter_s, namespaces)
586 585
587 586 def magic_psource(self, parameter_s='', namespaces=None):
588 587 """Print (or run through pager) the source code for an object."""
589 588 self._inspect('psource',parameter_s, namespaces)
590 589
591 590 def magic_pfile(self, parameter_s=''):
592 591 """Print (or run through pager) the file where an object is defined.
593 592
594 593 The file opens at the line where the object definition begins. IPython
595 594 will honor the environment variable PAGER if set, and otherwise will
596 595 do its best to print the file in a convenient form.
597 596
598 597 If the given argument is not an object currently defined, IPython will
599 598 try to interpret it as a filename (automatically adding a .py extension
600 599 if needed). You can thus use %pfile as a syntax highlighting code
601 600 viewer."""
602 601
603 602 # first interpret argument as an object name
604 603 out = self._inspect('pfile',parameter_s)
605 604 # if not, try the input as a filename
606 605 if out == 'not found':
607 606 try:
608 607 filename = get_py_filename(parameter_s)
609 608 except IOError,msg:
610 609 print msg
611 610 return
612 611 page.page(self.shell.inspector.format(file(filename).read()))
613 612
614 613 def magic_psearch(self, parameter_s=''):
615 614 """Search for object in namespaces by wildcard.
616 615
617 616 %psearch [options] PATTERN [OBJECT TYPE]
618 617
619 618 Note: ? can be used as a synonym for %psearch, at the beginning or at
620 619 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
621 620 rest of the command line must be unchanged (options come first), so
622 621 for example the following forms are equivalent
623 622
624 623 %psearch -i a* function
625 624 -i a* function?
626 625 ?-i a* function
627 626
628 627 Arguments:
629 628
630 629 PATTERN
631 630
632 631 where PATTERN is a string containing * as a wildcard similar to its
633 632 use in a shell. The pattern is matched in all namespaces on the
634 633 search path. By default objects starting with a single _ are not
635 634 matched, many IPython generated objects have a single
636 635 underscore. The default is case insensitive matching. Matching is
637 636 also done on the attributes of objects and not only on the objects
638 637 in a module.
639 638
640 639 [OBJECT TYPE]
641 640
642 641 Is the name of a python type from the types module. The name is
643 642 given in lowercase without the ending type, ex. StringType is
644 643 written string. By adding a type here only objects matching the
645 644 given type are matched. Using all here makes the pattern match all
646 645 types (this is the default).
647 646
648 647 Options:
649 648
650 649 -a: makes the pattern match even objects whose names start with a
651 650 single underscore. These names are normally ommitted from the
652 651 search.
653 652
654 653 -i/-c: make the pattern case insensitive/sensitive. If neither of
655 654 these options are given, the default is read from your configuration
656 655 file, with the option ``InteractiveShell.wildcards_case_sensitive``.
657 656 If this option is not specified in your configuration file, IPython's
658 657 internal default is to do a case sensitive search.
659 658
660 659 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
661 660 specifiy can be searched in any of the following namespaces:
662 661 'builtin', 'user', 'user_global','internal', 'alias', where
663 662 'builtin' and 'user' are the search defaults. Note that you should
664 663 not use quotes when specifying namespaces.
665 664
666 665 'Builtin' contains the python module builtin, 'user' contains all
667 666 user data, 'alias' only contain the shell aliases and no python
668 667 objects, 'internal' contains objects used by IPython. The
669 668 'user_global' namespace is only used by embedded IPython instances,
670 669 and it contains module-level globals. You can add namespaces to the
671 670 search with -s or exclude them with -e (these options can be given
672 671 more than once).
673 672
674 673 Examples:
675 674
676 675 %psearch a* -> objects beginning with an a
677 676 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
678 677 %psearch a* function -> all functions beginning with an a
679 678 %psearch re.e* -> objects beginning with an e in module re
680 679 %psearch r*.e* -> objects that start with e in modules starting in r
681 680 %psearch r*.* string -> all strings in modules beginning with r
682 681
683 682 Case sensitve search:
684 683
685 684 %psearch -c a* list all object beginning with lower case a
686 685
687 686 Show objects beginning with a single _:
688 687
689 688 %psearch -a _* list objects beginning with a single underscore"""
690 689 try:
691 690 parameter_s.encode('ascii')
692 691 except UnicodeEncodeError:
693 692 print 'Python identifiers can only contain ascii characters.'
694 693 return
695 694
696 695 # default namespaces to be searched
697 696 def_search = ['user','builtin']
698 697
699 698 # Process options/args
700 699 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
701 700 opt = opts.get
702 701 shell = self.shell
703 702 psearch = shell.inspector.psearch
704 703
705 704 # select case options
706 705 if opts.has_key('i'):
707 706 ignore_case = True
708 707 elif opts.has_key('c'):
709 708 ignore_case = False
710 709 else:
711 710 ignore_case = not shell.wildcards_case_sensitive
712 711
713 712 # Build list of namespaces to search from user options
714 713 def_search.extend(opt('s',[]))
715 714 ns_exclude = ns_exclude=opt('e',[])
716 715 ns_search = [nm for nm in def_search if nm not in ns_exclude]
717 716
718 717 # Call the actual search
719 718 try:
720 719 psearch(args,shell.ns_table,ns_search,
721 720 show_all=opt('a'),ignore_case=ignore_case)
722 721 except:
723 722 shell.showtraceback()
724 723
725 724 @skip_doctest
726 725 def magic_who_ls(self, parameter_s=''):
727 726 """Return a sorted list of all interactive variables.
728 727
729 728 If arguments are given, only variables of types matching these
730 729 arguments are returned.
731 730
732 731 Examples
733 732 --------
734 733
735 734 Define two variables and list them with who_ls::
736 735
737 736 In [1]: alpha = 123
738 737
739 738 In [2]: beta = 'test'
740 739
741 740 In [3]: %who_ls
742 741 Out[3]: ['alpha', 'beta']
743 742
744 743 In [4]: %who_ls int
745 744 Out[4]: ['alpha']
746 745
747 746 In [5]: %who_ls str
748 747 Out[5]: ['beta']
749 748 """
750 749
751 750 user_ns = self.shell.user_ns
752 751 internal_ns = self.shell.internal_ns
753 752 user_ns_hidden = self.shell.user_ns_hidden
754 753 out = [ i for i in user_ns
755 754 if not i.startswith('_') \
756 755 and not (i in internal_ns or i in user_ns_hidden) ]
757 756
758 757 typelist = parameter_s.split()
759 758 if typelist:
760 759 typeset = set(typelist)
761 760 out = [i for i in out if type(user_ns[i]).__name__ in typeset]
762 761
763 762 out.sort()
764 763 return out
765 764
766 765 @skip_doctest
767 766 def magic_who(self, parameter_s=''):
768 767 """Print all interactive variables, with some minimal formatting.
769 768
770 769 If any arguments are given, only variables whose type matches one of
771 770 these are printed. For example:
772 771
773 772 %who function str
774 773
775 774 will only list functions and strings, excluding all other types of
776 775 variables. To find the proper type names, simply use type(var) at a
777 776 command line to see how python prints type names. For example:
778 777
779 778 In [1]: type('hello')\\
780 779 Out[1]: <type 'str'>
781 780
782 781 indicates that the type name for strings is 'str'.
783 782
784 783 %who always excludes executed names loaded through your configuration
785 784 file and things which are internal to IPython.
786 785
787 786 This is deliberate, as typically you may load many modules and the
788 787 purpose of %who is to show you only what you've manually defined.
789 788
790 789 Examples
791 790 --------
792 791
793 792 Define two variables and list them with who::
794 793
795 794 In [1]: alpha = 123
796 795
797 796 In [2]: beta = 'test'
798 797
799 798 In [3]: %who
800 799 alpha beta
801 800
802 801 In [4]: %who int
803 802 alpha
804 803
805 804 In [5]: %who str
806 805 beta
807 806 """
808 807
809 808 varlist = self.magic_who_ls(parameter_s)
810 809 if not varlist:
811 810 if parameter_s:
812 811 print 'No variables match your requested type.'
813 812 else:
814 813 print 'Interactive namespace is empty.'
815 814 return
816 815
817 816 # if we have variables, move on...
818 817 count = 0
819 818 for i in varlist:
820 819 print i+'\t',
821 820 count += 1
822 821 if count > 8:
823 822 count = 0
824 823 print
825 824 print
826 825
827 826 @skip_doctest
828 827 def magic_whos(self, parameter_s=''):
829 828 """Like %who, but gives some extra information about each variable.
830 829
831 830 The same type filtering of %who can be applied here.
832 831
833 832 For all variables, the type is printed. Additionally it prints:
834 833
835 834 - For {},[],(): their length.
836 835
837 836 - For numpy arrays, a summary with shape, number of
838 837 elements, typecode and size in memory.
839 838
840 839 - Everything else: a string representation, snipping their middle if
841 840 too long.
842 841
843 842 Examples
844 843 --------
845 844
846 845 Define two variables and list them with whos::
847 846
848 847 In [1]: alpha = 123
849 848
850 849 In [2]: beta = 'test'
851 850
852 851 In [3]: %whos
853 852 Variable Type Data/Info
854 853 --------------------------------
855 854 alpha int 123
856 855 beta str test
857 856 """
858 857
859 858 varnames = self.magic_who_ls(parameter_s)
860 859 if not varnames:
861 860 if parameter_s:
862 861 print 'No variables match your requested type.'
863 862 else:
864 863 print 'Interactive namespace is empty.'
865 864 return
866 865
867 866 # if we have variables, move on...
868 867
869 868 # for these types, show len() instead of data:
870 869 seq_types = ['dict', 'list', 'tuple']
871 870
872 871 # for numpy arrays, display summary info
873 872 ndarray_type = None
874 873 if 'numpy' in sys.modules:
875 874 try:
876 875 from numpy import ndarray
877 876 except ImportError:
878 877 pass
879 878 else:
880 879 ndarray_type = ndarray.__name__
881 880
882 881 # Find all variable names and types so we can figure out column sizes
883 882 def get_vars(i):
884 883 return self.shell.user_ns[i]
885 884
886 885 # some types are well known and can be shorter
887 886 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
888 887 def type_name(v):
889 888 tn = type(v).__name__
890 889 return abbrevs.get(tn,tn)
891 890
892 891 varlist = map(get_vars,varnames)
893 892
894 893 typelist = []
895 894 for vv in varlist:
896 895 tt = type_name(vv)
897 896
898 897 if tt=='instance':
899 898 typelist.append( abbrevs.get(str(vv.__class__),
900 899 str(vv.__class__)))
901 900 else:
902 901 typelist.append(tt)
903 902
904 903 # column labels and # of spaces as separator
905 904 varlabel = 'Variable'
906 905 typelabel = 'Type'
907 906 datalabel = 'Data/Info'
908 907 colsep = 3
909 908 # variable format strings
910 909 vformat = "{0:<{varwidth}}{1:<{typewidth}}"
911 910 aformat = "%s: %s elems, type `%s`, %s bytes"
912 911 # find the size of the columns to format the output nicely
913 912 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
914 913 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
915 914 # table header
916 915 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
917 916 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
918 917 # and the table itself
919 918 kb = 1024
920 919 Mb = 1048576 # kb**2
921 920 for vname,var,vtype in zip(varnames,varlist,typelist):
922 921 print vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth),
923 922 if vtype in seq_types:
924 923 print "n="+str(len(var))
925 924 elif vtype == ndarray_type:
926 925 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
927 926 if vtype==ndarray_type:
928 927 # numpy
929 928 vsize = var.size
930 929 vbytes = vsize*var.itemsize
931 930 vdtype = var.dtype
932 931 else:
933 932 # Numeric
934 933 vsize = Numeric.size(var)
935 934 vbytes = vsize*var.itemsize()
936 935 vdtype = var.typecode()
937 936
938 937 if vbytes < 100000:
939 938 print aformat % (vshape,vsize,vdtype,vbytes)
940 939 else:
941 940 print aformat % (vshape,vsize,vdtype,vbytes),
942 941 if vbytes < Mb:
943 942 print '(%s kb)' % (vbytes/kb,)
944 943 else:
945 944 print '(%s Mb)' % (vbytes/Mb,)
946 945 else:
947 946 try:
948 947 vstr = str(var)
949 948 except UnicodeEncodeError:
950 949 vstr = unicode(var).encode(sys.getdefaultencoding(),
951 950 'backslashreplace')
952 951 vstr = vstr.replace('\n','\\n')
953 952 if len(vstr) < 50:
954 953 print vstr
955 954 else:
956 955 print vstr[:25] + "<...>" + vstr[-25:]
957 956
958 957 def magic_reset(self, parameter_s=''):
959 958 """Resets the namespace by removing all names defined by the user.
960 959
961 960 Parameters
962 961 ----------
963 962 -f : force reset without asking for confirmation.
964 963
965 964 -s : 'Soft' reset: Only clears your namespace, leaving history intact.
966 965 References to objects may be kept. By default (without this option),
967 966 we do a 'hard' reset, giving you a new session and removing all
968 967 references to objects from the current session.
969 968
970 969 Examples
971 970 --------
972 971 In [6]: a = 1
973 972
974 973 In [7]: a
975 974 Out[7]: 1
976 975
977 976 In [8]: 'a' in _ip.user_ns
978 977 Out[8]: True
979 978
980 979 In [9]: %reset -f
981 980
982 981 In [1]: 'a' in _ip.user_ns
983 982 Out[1]: False
984 983 """
985 984 opts, args = self.parse_options(parameter_s,'sf')
986 985 if 'f' in opts:
987 986 ans = True
988 987 else:
989 988 ans = self.shell.ask_yes_no(
990 989 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", default='n')
991 990 if not ans:
992 991 print 'Nothing done.'
993 992 return
994 993
995 994 if 's' in opts: # Soft reset
996 995 user_ns = self.shell.user_ns
997 996 for i in self.magic_who_ls():
998 997 del(user_ns[i])
999 998
1000 999 else: # Hard reset
1001 1000 self.shell.reset(new_session = False)
1002 1001
1003 1002
1004 1003
1005 1004 def magic_reset_selective(self, parameter_s=''):
1006 1005 """Resets the namespace by removing names defined by the user.
1007 1006
1008 1007 Input/Output history are left around in case you need them.
1009 1008
1010 1009 %reset_selective [-f] regex
1011 1010
1012 1011 No action is taken if regex is not included
1013 1012
1014 1013 Options
1015 1014 -f : force reset without asking for confirmation.
1016 1015
1017 1016 Examples
1018 1017 --------
1019 1018
1020 1019 We first fully reset the namespace so your output looks identical to
1021 1020 this example for pedagogical reasons; in practice you do not need a
1022 1021 full reset.
1023 1022
1024 1023 In [1]: %reset -f
1025 1024
1026 1025 Now, with a clean namespace we can make a few variables and use
1027 1026 %reset_selective to only delete names that match our regexp:
1028 1027
1029 1028 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1030 1029
1031 1030 In [3]: who_ls
1032 1031 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1033 1032
1034 1033 In [4]: %reset_selective -f b[2-3]m
1035 1034
1036 1035 In [5]: who_ls
1037 1036 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1038 1037
1039 1038 In [6]: %reset_selective -f d
1040 1039
1041 1040 In [7]: who_ls
1042 1041 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1043 1042
1044 1043 In [8]: %reset_selective -f c
1045 1044
1046 1045 In [9]: who_ls
1047 1046 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1048 1047
1049 1048 In [10]: %reset_selective -f b
1050 1049
1051 1050 In [11]: who_ls
1052 1051 Out[11]: ['a']
1053 1052 """
1054 1053
1055 1054 opts, regex = self.parse_options(parameter_s,'f')
1056 1055
1057 1056 if opts.has_key('f'):
1058 1057 ans = True
1059 1058 else:
1060 1059 ans = self.shell.ask_yes_no(
1061 1060 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ",
1062 1061 default='n')
1063 1062 if not ans:
1064 1063 print 'Nothing done.'
1065 1064 return
1066 1065 user_ns = self.shell.user_ns
1067 1066 if not regex:
1068 1067 print 'No regex pattern specified. Nothing done.'
1069 1068 return
1070 1069 else:
1071 1070 try:
1072 1071 m = re.compile(regex)
1073 1072 except TypeError:
1074 1073 raise TypeError('regex must be a string or compiled pattern')
1075 1074 for i in self.magic_who_ls():
1076 1075 if m.search(i):
1077 1076 del(user_ns[i])
1078 1077
1079 1078 def magic_xdel(self, parameter_s=''):
1080 1079 """Delete a variable, trying to clear it from anywhere that
1081 1080 IPython's machinery has references to it. By default, this uses
1082 1081 the identity of the named object in the user namespace to remove
1083 1082 references held under other names. The object is also removed
1084 1083 from the output history.
1085 1084
1086 1085 Options
1087 1086 -n : Delete the specified name from all namespaces, without
1088 1087 checking their identity.
1089 1088 """
1090 1089 opts, varname = self.parse_options(parameter_s,'n')
1091 1090 try:
1092 1091 self.shell.del_var(varname, ('n' in opts))
1093 1092 except (NameError, ValueError) as e:
1094 1093 print type(e).__name__ +": "+ str(e)
1095 1094
1096 1095 def magic_logstart(self,parameter_s=''):
1097 1096 """Start logging anywhere in a session.
1098 1097
1099 1098 %logstart [-o|-r|-t] [log_name [log_mode]]
1100 1099
1101 1100 If no name is given, it defaults to a file named 'ipython_log.py' in your
1102 1101 current directory, in 'rotate' mode (see below).
1103 1102
1104 1103 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1105 1104 history up to that point and then continues logging.
1106 1105
1107 1106 %logstart takes a second optional parameter: logging mode. This can be one
1108 1107 of (note that the modes are given unquoted):\\
1109 1108 append: well, that says it.\\
1110 1109 backup: rename (if exists) to name~ and start name.\\
1111 1110 global: single logfile in your home dir, appended to.\\
1112 1111 over : overwrite existing log.\\
1113 1112 rotate: create rotating logs name.1~, name.2~, etc.
1114 1113
1115 1114 Options:
1116 1115
1117 1116 -o: log also IPython's output. In this mode, all commands which
1118 1117 generate an Out[NN] prompt are recorded to the logfile, right after
1119 1118 their corresponding input line. The output lines are always
1120 1119 prepended with a '#[Out]# ' marker, so that the log remains valid
1121 1120 Python code.
1122 1121
1123 1122 Since this marker is always the same, filtering only the output from
1124 1123 a log is very easy, using for example a simple awk call:
1125 1124
1126 1125 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1127 1126
1128 1127 -r: log 'raw' input. Normally, IPython's logs contain the processed
1129 1128 input, so that user lines are logged in their final form, converted
1130 1129 into valid Python. For example, %Exit is logged as
1131 1130 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1132 1131 exactly as typed, with no transformations applied.
1133 1132
1134 1133 -t: put timestamps before each input line logged (these are put in
1135 1134 comments)."""
1136 1135
1137 1136 opts,par = self.parse_options(parameter_s,'ort')
1138 1137 log_output = 'o' in opts
1139 1138 log_raw_input = 'r' in opts
1140 1139 timestamp = 't' in opts
1141 1140
1142 1141 logger = self.shell.logger
1143 1142
1144 1143 # if no args are given, the defaults set in the logger constructor by
1145 1144 # ipytohn remain valid
1146 1145 if par:
1147 1146 try:
1148 1147 logfname,logmode = par.split()
1149 1148 except:
1150 1149 logfname = par
1151 1150 logmode = 'backup'
1152 1151 else:
1153 1152 logfname = logger.logfname
1154 1153 logmode = logger.logmode
1155 1154 # put logfname into rc struct as if it had been called on the command
1156 1155 # line, so it ends up saved in the log header Save it in case we need
1157 1156 # to restore it...
1158 1157 old_logfile = self.shell.logfile
1159 1158 if logfname:
1160 1159 logfname = os.path.expanduser(logfname)
1161 1160 self.shell.logfile = logfname
1162 1161
1163 1162 loghead = '# IPython log file\n\n'
1164 1163 try:
1165 1164 started = logger.logstart(logfname,loghead,logmode,
1166 1165 log_output,timestamp,log_raw_input)
1167 1166 except:
1168 1167 self.shell.logfile = old_logfile
1169 1168 warn("Couldn't start log: %s" % sys.exc_info()[1])
1170 1169 else:
1171 1170 # log input history up to this point, optionally interleaving
1172 1171 # output if requested
1173 1172
1174 1173 if timestamp:
1175 1174 # disable timestamping for the previous history, since we've
1176 1175 # lost those already (no time machine here).
1177 1176 logger.timestamp = False
1178 1177
1179 1178 if log_raw_input:
1180 1179 input_hist = self.shell.history_manager.input_hist_raw
1181 1180 else:
1182 1181 input_hist = self.shell.history_manager.input_hist_parsed
1183 1182
1184 1183 if log_output:
1185 1184 log_write = logger.log_write
1186 1185 output_hist = self.shell.history_manager.output_hist
1187 1186 for n in range(1,len(input_hist)-1):
1188 1187 log_write(input_hist[n].rstrip() + '\n')
1189 1188 if n in output_hist:
1190 1189 log_write(repr(output_hist[n]),'output')
1191 1190 else:
1192 1191 logger.log_write('\n'.join(input_hist[1:]))
1193 1192 logger.log_write('\n')
1194 1193 if timestamp:
1195 1194 # re-enable timestamping
1196 1195 logger.timestamp = True
1197 1196
1198 1197 print ('Activating auto-logging. '
1199 1198 'Current session state plus future input saved.')
1200 1199 logger.logstate()
1201 1200
1202 1201 def magic_logstop(self,parameter_s=''):
1203 1202 """Fully stop logging and close log file.
1204 1203
1205 1204 In order to start logging again, a new %logstart call needs to be made,
1206 1205 possibly (though not necessarily) with a new filename, mode and other
1207 1206 options."""
1208 1207 self.logger.logstop()
1209 1208
1210 1209 def magic_logoff(self,parameter_s=''):
1211 1210 """Temporarily stop logging.
1212 1211
1213 1212 You must have previously started logging."""
1214 1213 self.shell.logger.switch_log(0)
1215 1214
1216 1215 def magic_logon(self,parameter_s=''):
1217 1216 """Restart logging.
1218 1217
1219 1218 This function is for restarting logging which you've temporarily
1220 1219 stopped with %logoff. For starting logging for the first time, you
1221 1220 must use the %logstart function, which allows you to specify an
1222 1221 optional log filename."""
1223 1222
1224 1223 self.shell.logger.switch_log(1)
1225 1224
1226 1225 def magic_logstate(self,parameter_s=''):
1227 1226 """Print the status of the logging system."""
1228 1227
1229 1228 self.shell.logger.logstate()
1230 1229
1231 1230 def magic_pdb(self, parameter_s=''):
1232 1231 """Control the automatic calling of the pdb interactive debugger.
1233 1232
1234 1233 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1235 1234 argument it works as a toggle.
1236 1235
1237 1236 When an exception is triggered, IPython can optionally call the
1238 1237 interactive pdb debugger after the traceback printout. %pdb toggles
1239 1238 this feature on and off.
1240 1239
1241 1240 The initial state of this feature is set in your configuration
1242 1241 file (the option is ``InteractiveShell.pdb``).
1243 1242
1244 1243 If you want to just activate the debugger AFTER an exception has fired,
1245 1244 without having to type '%pdb on' and rerunning your code, you can use
1246 1245 the %debug magic."""
1247 1246
1248 1247 par = parameter_s.strip().lower()
1249 1248
1250 1249 if par:
1251 1250 try:
1252 1251 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1253 1252 except KeyError:
1254 1253 print ('Incorrect argument. Use on/1, off/0, '
1255 1254 'or nothing for a toggle.')
1256 1255 return
1257 1256 else:
1258 1257 # toggle
1259 1258 new_pdb = not self.shell.call_pdb
1260 1259
1261 1260 # set on the shell
1262 1261 self.shell.call_pdb = new_pdb
1263 1262 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1264 1263
1265 1264 def magic_debug(self, parameter_s=''):
1266 1265 """Activate the interactive debugger in post-mortem mode.
1267 1266
1268 1267 If an exception has just occurred, this lets you inspect its stack
1269 1268 frames interactively. Note that this will always work only on the last
1270 1269 traceback that occurred, so you must call this quickly after an
1271 1270 exception that you wish to inspect has fired, because if another one
1272 1271 occurs, it clobbers the previous one.
1273 1272
1274 1273 If you want IPython to automatically do this on every exception, see
1275 1274 the %pdb magic for more details.
1276 1275 """
1277 1276 self.shell.debugger(force=True)
1278 1277
1279 1278 @skip_doctest
1280 1279 def magic_prun(self, parameter_s ='',user_mode=1,
1281 1280 opts=None,arg_lst=None,prog_ns=None):
1282 1281
1283 1282 """Run a statement through the python code profiler.
1284 1283
1285 1284 Usage:
1286 1285 %prun [options] statement
1287 1286
1288 1287 The given statement (which doesn't require quote marks) is run via the
1289 1288 python profiler in a manner similar to the profile.run() function.
1290 1289 Namespaces are internally managed to work correctly; profile.run
1291 1290 cannot be used in IPython because it makes certain assumptions about
1292 1291 namespaces which do not hold under IPython.
1293 1292
1294 1293 Options:
1295 1294
1296 1295 -l <limit>: you can place restrictions on what or how much of the
1297 1296 profile gets printed. The limit value can be:
1298 1297
1299 1298 * A string: only information for function names containing this string
1300 1299 is printed.
1301 1300
1302 1301 * An integer: only these many lines are printed.
1303 1302
1304 1303 * A float (between 0 and 1): this fraction of the report is printed
1305 1304 (for example, use a limit of 0.4 to see the topmost 40% only).
1306 1305
1307 1306 You can combine several limits with repeated use of the option. For
1308 1307 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1309 1308 information about class constructors.
1310 1309
1311 1310 -r: return the pstats.Stats object generated by the profiling. This
1312 1311 object has all the information about the profile in it, and you can
1313 1312 later use it for further analysis or in other functions.
1314 1313
1315 1314 -s <key>: sort profile by given key. You can provide more than one key
1316 1315 by using the option several times: '-s key1 -s key2 -s key3...'. The
1317 1316 default sorting key is 'time'.
1318 1317
1319 1318 The following is copied verbatim from the profile documentation
1320 1319 referenced below:
1321 1320
1322 1321 When more than one key is provided, additional keys are used as
1323 1322 secondary criteria when the there is equality in all keys selected
1324 1323 before them.
1325 1324
1326 1325 Abbreviations can be used for any key names, as long as the
1327 1326 abbreviation is unambiguous. The following are the keys currently
1328 1327 defined:
1329 1328
1330 1329 Valid Arg Meaning
1331 1330 "calls" call count
1332 1331 "cumulative" cumulative time
1333 1332 "file" file name
1334 1333 "module" file name
1335 1334 "pcalls" primitive call count
1336 1335 "line" line number
1337 1336 "name" function name
1338 1337 "nfl" name/file/line
1339 1338 "stdname" standard name
1340 1339 "time" internal time
1341 1340
1342 1341 Note that all sorts on statistics are in descending order (placing
1343 1342 most time consuming items first), where as name, file, and line number
1344 1343 searches are in ascending order (i.e., alphabetical). The subtle
1345 1344 distinction between "nfl" and "stdname" is that the standard name is a
1346 1345 sort of the name as printed, which means that the embedded line
1347 1346 numbers get compared in an odd way. For example, lines 3, 20, and 40
1348 1347 would (if the file names were the same) appear in the string order
1349 1348 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1350 1349 line numbers. In fact, sort_stats("nfl") is the same as
1351 1350 sort_stats("name", "file", "line").
1352 1351
1353 1352 -T <filename>: save profile results as shown on screen to a text
1354 1353 file. The profile is still shown on screen.
1355 1354
1356 1355 -D <filename>: save (via dump_stats) profile statistics to given
1357 1356 filename. This data is in a format understod by the pstats module, and
1358 1357 is generated by a call to the dump_stats() method of profile
1359 1358 objects. The profile is still shown on screen.
1360 1359
1361 1360 If you want to run complete programs under the profiler's control, use
1362 1361 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1363 1362 contains profiler specific options as described here.
1364 1363
1365 1364 You can read the complete documentation for the profile module with::
1366 1365
1367 1366 In [1]: import profile; profile.help()
1368 1367 """
1369 1368
1370 1369 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1371 1370 # protect user quote marks
1372 1371 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1373 1372
1374 1373 if user_mode: # regular user call
1375 1374 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1376 1375 list_all=1)
1377 1376 namespace = self.shell.user_ns
1378 1377 else: # called to run a program by %run -p
1379 1378 try:
1380 1379 filename = get_py_filename(arg_lst[0])
1381 1380 except IOError as e:
1382 1381 try:
1383 1382 msg = str(e)
1384 1383 except UnicodeError:
1385 1384 msg = e.message
1386 1385 error(msg)
1387 1386 return
1388 1387
1389 1388 arg_str = 'execfile(filename,prog_ns)'
1390 1389 namespace = {
1391 1390 'execfile': self.shell.safe_execfile,
1392 1391 'prog_ns': prog_ns,
1393 1392 'filename': filename
1394 1393 }
1395 1394
1396 1395 opts.merge(opts_def)
1397 1396
1398 1397 prof = profile.Profile()
1399 1398 try:
1400 1399 prof = prof.runctx(arg_str,namespace,namespace)
1401 1400 sys_exit = ''
1402 1401 except SystemExit:
1403 1402 sys_exit = """*** SystemExit exception caught in code being profiled."""
1404 1403
1405 1404 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1406 1405
1407 1406 lims = opts.l
1408 1407 if lims:
1409 1408 lims = [] # rebuild lims with ints/floats/strings
1410 1409 for lim in opts.l:
1411 1410 try:
1412 1411 lims.append(int(lim))
1413 1412 except ValueError:
1414 1413 try:
1415 1414 lims.append(float(lim))
1416 1415 except ValueError:
1417 1416 lims.append(lim)
1418 1417
1419 1418 # Trap output.
1420 1419 stdout_trap = StringIO()
1421 1420
1422 1421 if hasattr(stats,'stream'):
1423 1422 # In newer versions of python, the stats object has a 'stream'
1424 1423 # attribute to write into.
1425 1424 stats.stream = stdout_trap
1426 1425 stats.print_stats(*lims)
1427 1426 else:
1428 1427 # For older versions, we manually redirect stdout during printing
1429 1428 sys_stdout = sys.stdout
1430 1429 try:
1431 1430 sys.stdout = stdout_trap
1432 1431 stats.print_stats(*lims)
1433 1432 finally:
1434 1433 sys.stdout = sys_stdout
1435 1434
1436 1435 output = stdout_trap.getvalue()
1437 1436 output = output.rstrip()
1438 1437
1439 1438 page.page(output)
1440 1439 print sys_exit,
1441 1440
1442 1441 dump_file = opts.D[0]
1443 1442 text_file = opts.T[0]
1444 1443 if dump_file:
1445 1444 dump_file = unquote_filename(dump_file)
1446 1445 prof.dump_stats(dump_file)
1447 1446 print '\n*** Profile stats marshalled to file',\
1448 1447 `dump_file`+'.',sys_exit
1449 1448 if text_file:
1450 1449 text_file = unquote_filename(text_file)
1451 1450 pfile = file(text_file,'w')
1452 1451 pfile.write(output)
1453 1452 pfile.close()
1454 1453 print '\n*** Profile printout saved to text file',\
1455 1454 `text_file`+'.',sys_exit
1456 1455
1457 1456 if opts.has_key('r'):
1458 1457 return stats
1459 1458 else:
1460 1459 return None
1461 1460
1462 1461 @skip_doctest
1463 1462 def magic_run(self, parameter_s ='', runner=None,
1464 1463 file_finder=get_py_filename):
1465 1464 """Run the named file inside IPython as a program.
1466 1465
1467 1466 Usage:\\
1468 1467 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1469 1468
1470 1469 Parameters after the filename are passed as command-line arguments to
1471 1470 the program (put in sys.argv). Then, control returns to IPython's
1472 1471 prompt.
1473 1472
1474 1473 This is similar to running at a system prompt:\\
1475 1474 $ python file args\\
1476 1475 but with the advantage of giving you IPython's tracebacks, and of
1477 1476 loading all variables into your interactive namespace for further use
1478 1477 (unless -p is used, see below).
1479 1478
1480 1479 The file is executed in a namespace initially consisting only of
1481 1480 __name__=='__main__' and sys.argv constructed as indicated. It thus
1482 1481 sees its environment as if it were being run as a stand-alone program
1483 1482 (except for sharing global objects such as previously imported
1484 1483 modules). But after execution, the IPython interactive namespace gets
1485 1484 updated with all variables defined in the program (except for __name__
1486 1485 and sys.argv). This allows for very convenient loading of code for
1487 1486 interactive work, while giving each program a 'clean sheet' to run in.
1488 1487
1489 1488 Options:
1490 1489
1491 1490 -n: __name__ is NOT set to '__main__', but to the running file's name
1492 1491 without extension (as python does under import). This allows running
1493 1492 scripts and reloading the definitions in them without calling code
1494 1493 protected by an ' if __name__ == "__main__" ' clause.
1495 1494
1496 1495 -i: run the file in IPython's namespace instead of an empty one. This
1497 1496 is useful if you are experimenting with code written in a text editor
1498 1497 which depends on variables defined interactively.
1499 1498
1500 1499 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1501 1500 being run. This is particularly useful if IPython is being used to
1502 1501 run unittests, which always exit with a sys.exit() call. In such
1503 1502 cases you are interested in the output of the test results, not in
1504 1503 seeing a traceback of the unittest module.
1505 1504
1506 1505 -t: print timing information at the end of the run. IPython will give
1507 1506 you an estimated CPU time consumption for your script, which under
1508 1507 Unix uses the resource module to avoid the wraparound problems of
1509 1508 time.clock(). Under Unix, an estimate of time spent on system tasks
1510 1509 is also given (for Windows platforms this is reported as 0.0).
1511 1510
1512 1511 If -t is given, an additional -N<N> option can be given, where <N>
1513 1512 must be an integer indicating how many times you want the script to
1514 1513 run. The final timing report will include total and per run results.
1515 1514
1516 1515 For example (testing the script uniq_stable.py):
1517 1516
1518 1517 In [1]: run -t uniq_stable
1519 1518
1520 1519 IPython CPU timings (estimated):\\
1521 1520 User : 0.19597 s.\\
1522 1521 System: 0.0 s.\\
1523 1522
1524 1523 In [2]: run -t -N5 uniq_stable
1525 1524
1526 1525 IPython CPU timings (estimated):\\
1527 1526 Total runs performed: 5\\
1528 1527 Times : Total Per run\\
1529 1528 User : 0.910862 s, 0.1821724 s.\\
1530 1529 System: 0.0 s, 0.0 s.
1531 1530
1532 1531 -d: run your program under the control of pdb, the Python debugger.
1533 1532 This allows you to execute your program step by step, watch variables,
1534 1533 etc. Internally, what IPython does is similar to calling:
1535 1534
1536 1535 pdb.run('execfile("YOURFILENAME")')
1537 1536
1538 1537 with a breakpoint set on line 1 of your file. You can change the line
1539 1538 number for this automatic breakpoint to be <N> by using the -bN option
1540 1539 (where N must be an integer). For example:
1541 1540
1542 1541 %run -d -b40 myscript
1543 1542
1544 1543 will set the first breakpoint at line 40 in myscript.py. Note that
1545 1544 the first breakpoint must be set on a line which actually does
1546 1545 something (not a comment or docstring) for it to stop execution.
1547 1546
1548 1547 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1549 1548 first enter 'c' (without qoutes) to start execution up to the first
1550 1549 breakpoint.
1551 1550
1552 1551 Entering 'help' gives information about the use of the debugger. You
1553 1552 can easily see pdb's full documentation with "import pdb;pdb.help()"
1554 1553 at a prompt.
1555 1554
1556 1555 -p: run program under the control of the Python profiler module (which
1557 1556 prints a detailed report of execution times, function calls, etc).
1558 1557
1559 1558 You can pass other options after -p which affect the behavior of the
1560 1559 profiler itself. See the docs for %prun for details.
1561 1560
1562 1561 In this mode, the program's variables do NOT propagate back to the
1563 1562 IPython interactive namespace (because they remain in the namespace
1564 1563 where the profiler executes them).
1565 1564
1566 1565 Internally this triggers a call to %prun, see its documentation for
1567 1566 details on the options available specifically for profiling.
1568 1567
1569 1568 There is one special usage for which the text above doesn't apply:
1570 1569 if the filename ends with .ipy, the file is run as ipython script,
1571 1570 just as if the commands were written on IPython prompt.
1572 1571
1573 1572 -m: specify module name to load instead of script path. Similar to
1574 1573 the -m option for the python interpreter. Use this option last if you
1575 1574 want to combine with other %run options. Unlike the python interpreter
1576 1575 only source modules are allowed no .pyc or .pyo files.
1577 1576 For example:
1578 1577
1579 1578 %run -m example
1580 1579
1581 1580 will run the example module.
1582 1581
1583 1582 """
1584 1583
1585 1584 # get arguments and set sys.argv for program to be run.
1586 1585 opts, arg_lst = self.parse_options(parameter_s, 'nidtN:b:pD:l:rs:T:em:',
1587 1586 mode='list', list_all=1)
1588 1587 if "m" in opts:
1589 1588 modulename = opts["m"][0]
1590 1589 modpath = find_mod(modulename)
1591 1590 if modpath is None:
1592 1591 warn('%r is not a valid modulename on sys.path'%modulename)
1593 1592 return
1594 1593 arg_lst = [modpath] + arg_lst
1595 1594 try:
1596 1595 filename = file_finder(arg_lst[0])
1597 1596 except IndexError:
1598 1597 warn('you must provide at least a filename.')
1599 1598 print '\n%run:\n', oinspect.getdoc(self.magic_run)
1600 1599 return
1601 1600 except IOError as e:
1602 1601 try:
1603 1602 msg = str(e)
1604 1603 except UnicodeError:
1605 1604 msg = e.message
1606 1605 error(msg)
1607 1606 return
1608 1607
1609 1608 if filename.lower().endswith('.ipy'):
1610 1609 self.shell.safe_execfile_ipy(filename)
1611 1610 return
1612 1611
1613 1612 # Control the response to exit() calls made by the script being run
1614 1613 exit_ignore = 'e' in opts
1615 1614
1616 1615 # Make sure that the running script gets a proper sys.argv as if it
1617 1616 # were run from a system shell.
1618 1617 save_argv = sys.argv # save it for later restoring
1619 1618
1620 1619 # simulate shell expansion on arguments, at least tilde expansion
1621 1620 args = [ os.path.expanduser(a) for a in arg_lst[1:] ]
1622 1621
1623 1622 sys.argv = [filename] + args # put in the proper filename
1624 1623 # protect sys.argv from potential unicode strings on Python 2:
1625 1624 if not py3compat.PY3:
1626 1625 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
1627 1626
1628 1627 if 'i' in opts:
1629 1628 # Run in user's interactive namespace
1630 1629 prog_ns = self.shell.user_ns
1631 1630 __name__save = self.shell.user_ns['__name__']
1632 1631 prog_ns['__name__'] = '__main__'
1633 1632 main_mod = self.shell.new_main_mod(prog_ns)
1634 1633 else:
1635 1634 # Run in a fresh, empty namespace
1636 1635 if 'n' in opts:
1637 1636 name = os.path.splitext(os.path.basename(filename))[0]
1638 1637 else:
1639 1638 name = '__main__'
1640 1639
1641 1640 main_mod = self.shell.new_main_mod()
1642 1641 prog_ns = main_mod.__dict__
1643 1642 prog_ns['__name__'] = name
1644 1643
1645 1644 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1646 1645 # set the __file__ global in the script's namespace
1647 1646 prog_ns['__file__'] = filename
1648 1647
1649 1648 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1650 1649 # that, if we overwrite __main__, we replace it at the end
1651 1650 main_mod_name = prog_ns['__name__']
1652 1651
1653 1652 if main_mod_name == '__main__':
1654 1653 restore_main = sys.modules['__main__']
1655 1654 else:
1656 1655 restore_main = False
1657 1656
1658 1657 # This needs to be undone at the end to prevent holding references to
1659 1658 # every single object ever created.
1660 1659 sys.modules[main_mod_name] = main_mod
1661 1660
1662 1661 try:
1663 1662 stats = None
1664 1663 with self.readline_no_record:
1665 1664 if 'p' in opts:
1666 1665 stats = self.magic_prun('', 0, opts, arg_lst, prog_ns)
1667 1666 else:
1668 1667 if 'd' in opts:
1669 1668 deb = debugger.Pdb(self.shell.colors)
1670 1669 # reset Breakpoint state, which is moronically kept
1671 1670 # in a class
1672 1671 bdb.Breakpoint.next = 1
1673 1672 bdb.Breakpoint.bplist = {}
1674 1673 bdb.Breakpoint.bpbynumber = [None]
1675 1674 # Set an initial breakpoint to stop execution
1676 1675 maxtries = 10
1677 1676 bp = int(opts.get('b', [1])[0])
1678 1677 checkline = deb.checkline(filename, bp)
1679 1678 if not checkline:
1680 1679 for bp in range(bp + 1, bp + maxtries + 1):
1681 1680 if deb.checkline(filename, bp):
1682 1681 break
1683 1682 else:
1684 1683 msg = ("\nI failed to find a valid line to set "
1685 1684 "a breakpoint\n"
1686 1685 "after trying up to line: %s.\n"
1687 1686 "Please set a valid breakpoint manually "
1688 1687 "with the -b option." % bp)
1689 1688 error(msg)
1690 1689 return
1691 1690 # if we find a good linenumber, set the breakpoint
1692 1691 deb.do_break('%s:%s' % (filename, bp))
1693 1692 # Start file run
1694 1693 print "NOTE: Enter 'c' at the",
1695 1694 print "%s prompt to start your script." % deb.prompt
1696 1695 try:
1697 1696 deb.run('execfile("%s")' % filename, prog_ns)
1698 1697
1699 1698 except:
1700 1699 etype, value, tb = sys.exc_info()
1701 1700 # Skip three frames in the traceback: the %run one,
1702 1701 # one inside bdb.py, and the command-line typed by the
1703 1702 # user (run by exec in pdb itself).
1704 1703 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
1705 1704 else:
1706 1705 if runner is None:
1707 1706 runner = self.shell.safe_execfile
1708 1707 if 't' in opts:
1709 1708 # timed execution
1710 1709 try:
1711 1710 nruns = int(opts['N'][0])
1712 1711 if nruns < 1:
1713 1712 error('Number of runs must be >=1')
1714 1713 return
1715 1714 except (KeyError):
1716 1715 nruns = 1
1717 1716 twall0 = time.time()
1718 1717 if nruns == 1:
1719 1718 t0 = clock2()
1720 1719 runner(filename, prog_ns, prog_ns,
1721 1720 exit_ignore=exit_ignore)
1722 1721 t1 = clock2()
1723 1722 t_usr = t1[0] - t0[0]
1724 1723 t_sys = t1[1] - t0[1]
1725 1724 print "\nIPython CPU timings (estimated):"
1726 1725 print " User : %10.2f s." % t_usr
1727 1726 print " System : %10.2f s." % t_sys
1728 1727 else:
1729 1728 runs = range(nruns)
1730 1729 t0 = clock2()
1731 1730 for nr in runs:
1732 1731 runner(filename, prog_ns, prog_ns,
1733 1732 exit_ignore=exit_ignore)
1734 1733 t1 = clock2()
1735 1734 t_usr = t1[0] - t0[0]
1736 1735 t_sys = t1[1] - t0[1]
1737 1736 print "\nIPython CPU timings (estimated):"
1738 1737 print "Total runs performed:", nruns
1739 1738 print " Times : %10.2f %10.2f" % ('Total', 'Per run')
1740 1739 print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns)
1741 1740 print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns)
1742 1741 twall1 = time.time()
1743 1742 print "Wall time: %10.2f s." % (twall1 - twall0)
1744 1743
1745 1744 else:
1746 1745 # regular execution
1747 1746 runner(filename, prog_ns, prog_ns, exit_ignore=exit_ignore)
1748 1747
1749 1748 if 'i' in opts:
1750 1749 self.shell.user_ns['__name__'] = __name__save
1751 1750 else:
1752 1751 # The shell MUST hold a reference to prog_ns so after %run
1753 1752 # exits, the python deletion mechanism doesn't zero it out
1754 1753 # (leaving dangling references).
1755 1754 self.shell.cache_main_mod(prog_ns, filename)
1756 1755 # update IPython interactive namespace
1757 1756
1758 1757 # Some forms of read errors on the file may mean the
1759 1758 # __name__ key was never set; using pop we don't have to
1760 1759 # worry about a possible KeyError.
1761 1760 prog_ns.pop('__name__', None)
1762 1761
1763 1762 self.shell.user_ns.update(prog_ns)
1764 1763 finally:
1765 1764 # It's a bit of a mystery why, but __builtins__ can change from
1766 1765 # being a module to becoming a dict missing some key data after
1767 1766 # %run. As best I can see, this is NOT something IPython is doing
1768 1767 # at all, and similar problems have been reported before:
1769 1768 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1770 1769 # Since this seems to be done by the interpreter itself, the best
1771 1770 # we can do is to at least restore __builtins__ for the user on
1772 1771 # exit.
1773 1772 self.shell.user_ns['__builtins__'] = builtin_mod
1774 1773
1775 1774 # Ensure key global structures are restored
1776 1775 sys.argv = save_argv
1777 1776 if restore_main:
1778 1777 sys.modules['__main__'] = restore_main
1779 1778 else:
1780 1779 # Remove from sys.modules the reference to main_mod we'd
1781 1780 # added. Otherwise it will trap references to objects
1782 1781 # contained therein.
1783 1782 del sys.modules[main_mod_name]
1784 1783
1785 1784 return stats
1786 1785
1787 1786 @skip_doctest
1788 1787 def magic_timeit(self, parameter_s =''):
1789 1788 """Time execution of a Python statement or expression
1790 1789
1791 1790 Usage:\\
1792 1791 %timeit [-n<N> -r<R> [-t|-c]] statement
1793 1792
1794 1793 Time execution of a Python statement or expression using the timeit
1795 1794 module.
1796 1795
1797 1796 Options:
1798 1797 -n<N>: execute the given statement <N> times in a loop. If this value
1799 1798 is not given, a fitting value is chosen.
1800 1799
1801 1800 -r<R>: repeat the loop iteration <R> times and take the best result.
1802 1801 Default: 3
1803 1802
1804 1803 -t: use time.time to measure the time, which is the default on Unix.
1805 1804 This function measures wall time.
1806 1805
1807 1806 -c: use time.clock to measure the time, which is the default on
1808 1807 Windows and measures wall time. On Unix, resource.getrusage is used
1809 1808 instead and returns the CPU user time.
1810 1809
1811 1810 -p<P>: use a precision of <P> digits to display the timing result.
1812 1811 Default: 3
1813 1812
1814 1813
1815 1814 Examples:
1816 1815
1817 1816 In [1]: %timeit pass
1818 1817 10000000 loops, best of 3: 53.3 ns per loop
1819 1818
1820 1819 In [2]: u = None
1821 1820
1822 1821 In [3]: %timeit u is None
1823 1822 10000000 loops, best of 3: 184 ns per loop
1824 1823
1825 1824 In [4]: %timeit -r 4 u == None
1826 1825 1000000 loops, best of 4: 242 ns per loop
1827 1826
1828 1827 In [5]: import time
1829 1828
1830 1829 In [6]: %timeit -n1 time.sleep(2)
1831 1830 1 loops, best of 3: 2 s per loop
1832 1831
1833 1832
1834 1833 The times reported by %timeit will be slightly higher than those
1835 1834 reported by the timeit.py script when variables are accessed. This is
1836 1835 due to the fact that %timeit executes the statement in the namespace
1837 1836 of the shell, compared with timeit.py, which uses a single setup
1838 1837 statement to import function or create variables. Generally, the bias
1839 1838 does not matter as long as results from timeit.py are not mixed with
1840 1839 those from %timeit."""
1841 1840
1842 1841 import timeit
1843 1842 import math
1844 1843
1845 1844 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1846 1845 # certain terminals. Until we figure out a robust way of
1847 1846 # auto-detecting if the terminal can deal with it, use plain 'us' for
1848 1847 # microseconds. I am really NOT happy about disabling the proper
1849 1848 # 'micro' prefix, but crashing is worse... If anyone knows what the
1850 1849 # right solution for this is, I'm all ears...
1851 1850 #
1852 1851 # Note: using
1853 1852 #
1854 1853 # s = u'\xb5'
1855 1854 # s.encode(sys.getdefaultencoding())
1856 1855 #
1857 1856 # is not sufficient, as I've seen terminals where that fails but
1858 1857 # print s
1859 1858 #
1860 1859 # succeeds
1861 1860 #
1862 1861 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1863 1862
1864 1863 #units = [u"s", u"ms",u'\xb5',"ns"]
1865 1864 units = [u"s", u"ms",u'us',"ns"]
1866 1865
1867 1866 scaling = [1, 1e3, 1e6, 1e9]
1868 1867
1869 1868 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1870 1869 posix=False)
1871 1870 if stmt == "":
1872 1871 return
1873 1872 timefunc = timeit.default_timer
1874 1873 number = int(getattr(opts, "n", 0))
1875 1874 repeat = int(getattr(opts, "r", timeit.default_repeat))
1876 1875 precision = int(getattr(opts, "p", 3))
1877 1876 if hasattr(opts, "t"):
1878 1877 timefunc = time.time
1879 1878 if hasattr(opts, "c"):
1880 1879 timefunc = clock
1881 1880
1882 1881 timer = timeit.Timer(timer=timefunc)
1883 1882 # this code has tight coupling to the inner workings of timeit.Timer,
1884 1883 # but is there a better way to achieve that the code stmt has access
1885 1884 # to the shell namespace?
1886 1885
1887 1886 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1888 1887 'setup': "pass"}
1889 1888 # Track compilation time so it can be reported if too long
1890 1889 # Minimum time above which compilation time will be reported
1891 1890 tc_min = 0.1
1892 1891
1893 1892 t0 = clock()
1894 1893 code = compile(src, "<magic-timeit>", "exec")
1895 1894 tc = clock()-t0
1896 1895
1897 1896 ns = {}
1898 1897 exec code in self.shell.user_ns, ns
1899 1898 timer.inner = ns["inner"]
1900 1899
1901 1900 if number == 0:
1902 1901 # determine number so that 0.2 <= total time < 2.0
1903 1902 number = 1
1904 1903 for i in range(1, 10):
1905 1904 if timer.timeit(number) >= 0.2:
1906 1905 break
1907 1906 number *= 10
1908 1907
1909 1908 best = min(timer.repeat(repeat, number)) / number
1910 1909
1911 1910 if best > 0.0 and best < 1000.0:
1912 1911 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1913 1912 elif best >= 1000.0:
1914 1913 order = 0
1915 1914 else:
1916 1915 order = 3
1917 1916 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1918 1917 precision,
1919 1918 best * scaling[order],
1920 1919 units[order])
1921 1920 if tc > tc_min:
1922 1921 print "Compiler time: %.2f s" % tc
1923 1922
1924 1923 @skip_doctest
1925 1924 @needs_local_scope
1926 1925 def magic_time(self,parameter_s = ''):
1927 1926 """Time execution of a Python statement or expression.
1928 1927
1929 1928 The CPU and wall clock times are printed, and the value of the
1930 1929 expression (if any) is returned. Note that under Win32, system time
1931 1930 is always reported as 0, since it can not be measured.
1932 1931
1933 1932 This function provides very basic timing functionality. In Python
1934 1933 2.3, the timeit module offers more control and sophistication, so this
1935 1934 could be rewritten to use it (patches welcome).
1936 1935
1937 1936 Some examples:
1938 1937
1939 1938 In [1]: time 2**128
1940 1939 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1941 1940 Wall time: 0.00
1942 1941 Out[1]: 340282366920938463463374607431768211456L
1943 1942
1944 1943 In [2]: n = 1000000
1945 1944
1946 1945 In [3]: time sum(range(n))
1947 1946 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1948 1947 Wall time: 1.37
1949 1948 Out[3]: 499999500000L
1950 1949
1951 1950 In [4]: time print 'hello world'
1952 1951 hello world
1953 1952 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1954 1953 Wall time: 0.00
1955 1954
1956 1955 Note that the time needed by Python to compile the given expression
1957 1956 will be reported if it is more than 0.1s. In this example, the
1958 1957 actual exponentiation is done by Python at compilation time, so while
1959 1958 the expression can take a noticeable amount of time to compute, that
1960 1959 time is purely due to the compilation:
1961 1960
1962 1961 In [5]: time 3**9999;
1963 1962 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1964 1963 Wall time: 0.00 s
1965 1964
1966 1965 In [6]: time 3**999999;
1967 1966 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1968 1967 Wall time: 0.00 s
1969 1968 Compiler : 0.78 s
1970 1969 """
1971 1970
1972 1971 # fail immediately if the given expression can't be compiled
1973 1972
1974 1973 expr = self.shell.prefilter(parameter_s,False)
1975 1974
1976 1975 # Minimum time above which compilation time will be reported
1977 1976 tc_min = 0.1
1978 1977
1979 1978 try:
1980 1979 mode = 'eval'
1981 1980 t0 = clock()
1982 1981 code = compile(expr,'<timed eval>',mode)
1983 1982 tc = clock()-t0
1984 1983 except SyntaxError:
1985 1984 mode = 'exec'
1986 1985 t0 = clock()
1987 1986 code = compile(expr,'<timed exec>',mode)
1988 1987 tc = clock()-t0
1989 1988 # skew measurement as little as possible
1990 1989 glob = self.shell.user_ns
1991 1990 locs = self._magic_locals
1992 1991 clk = clock2
1993 1992 wtime = time.time
1994 1993 # time execution
1995 1994 wall_st = wtime()
1996 1995 if mode=='eval':
1997 1996 st = clk()
1998 1997 out = eval(code, glob, locs)
1999 1998 end = clk()
2000 1999 else:
2001 2000 st = clk()
2002 2001 exec code in glob, locs
2003 2002 end = clk()
2004 2003 out = None
2005 2004 wall_end = wtime()
2006 2005 # Compute actual times and report
2007 2006 wall_time = wall_end-wall_st
2008 2007 cpu_user = end[0]-st[0]
2009 2008 cpu_sys = end[1]-st[1]
2010 2009 cpu_tot = cpu_user+cpu_sys
2011 2010 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
2012 2011 (cpu_user,cpu_sys,cpu_tot)
2013 2012 print "Wall time: %.2f s" % wall_time
2014 2013 if tc > tc_min:
2015 2014 print "Compiler : %.2f s" % tc
2016 2015 return out
2017 2016
2018 2017 @skip_doctest
2019 2018 def magic_macro(self,parameter_s = ''):
2020 2019 """Define a macro for future re-execution. It accepts ranges of history,
2021 2020 filenames or string objects.
2022 2021
2023 2022 Usage:\\
2024 2023 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
2025 2024
2026 2025 Options:
2027 2026
2028 2027 -r: use 'raw' input. By default, the 'processed' history is used,
2029 2028 so that magics are loaded in their transformed version to valid
2030 2029 Python. If this option is given, the raw input as typed as the
2031 2030 command line is used instead.
2032 2031
2033 2032 This will define a global variable called `name` which is a string
2034 2033 made of joining the slices and lines you specify (n1,n2,... numbers
2035 2034 above) from your input history into a single string. This variable
2036 2035 acts like an automatic function which re-executes those lines as if
2037 2036 you had typed them. You just type 'name' at the prompt and the code
2038 2037 executes.
2039 2038
2040 2039 The syntax for indicating input ranges is described in %history.
2041 2040
2042 2041 Note: as a 'hidden' feature, you can also use traditional python slice
2043 2042 notation, where N:M means numbers N through M-1.
2044 2043
2045 2044 For example, if your history contains (%hist prints it):
2046 2045
2047 2046 44: x=1
2048 2047 45: y=3
2049 2048 46: z=x+y
2050 2049 47: print x
2051 2050 48: a=5
2052 2051 49: print 'x',x,'y',y
2053 2052
2054 2053 you can create a macro with lines 44 through 47 (included) and line 49
2055 2054 called my_macro with:
2056 2055
2057 2056 In [55]: %macro my_macro 44-47 49
2058 2057
2059 2058 Now, typing `my_macro` (without quotes) will re-execute all this code
2060 2059 in one pass.
2061 2060
2062 2061 You don't need to give the line-numbers in order, and any given line
2063 2062 number can appear multiple times. You can assemble macros with any
2064 2063 lines from your input history in any order.
2065 2064
2066 2065 The macro is a simple object which holds its value in an attribute,
2067 2066 but IPython's display system checks for macros and executes them as
2068 2067 code instead of printing them when you type their name.
2069 2068
2070 2069 You can view a macro's contents by explicitly printing it with:
2071 2070
2072 2071 'print macro_name'.
2073 2072
2074 2073 """
2075 2074 opts,args = self.parse_options(parameter_s,'r',mode='list')
2076 2075 if not args: # List existing macros
2077 2076 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
2078 2077 isinstance(v, Macro))
2079 2078 if len(args) == 1:
2080 2079 raise UsageError(
2081 2080 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2082 2081 name, codefrom = args[0], " ".join(args[1:])
2083 2082
2084 2083 #print 'rng',ranges # dbg
2085 2084 try:
2086 2085 lines = self.shell.find_user_code(codefrom, 'r' in opts)
2087 2086 except (ValueError, TypeError) as e:
2088 2087 print e.args[0]
2089 2088 return
2090 2089 macro = Macro(lines)
2091 2090 self.shell.define_macro(name, macro)
2092 2091 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2093 2092 print '=== Macro contents: ==='
2094 2093 print macro,
2095 2094
2096 2095 def magic_save(self,parameter_s = ''):
2097 2096 """Save a set of lines or a macro to a given filename.
2098 2097
2099 2098 Usage:\\
2100 2099 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2101 2100
2102 2101 Options:
2103 2102
2104 2103 -r: use 'raw' input. By default, the 'processed' history is used,
2105 2104 so that magics are loaded in their transformed version to valid
2106 2105 Python. If this option is given, the raw input as typed as the
2107 2106 command line is used instead.
2108 2107
2109 2108 This function uses the same syntax as %history for input ranges,
2110 2109 then saves the lines to the filename you specify.
2111 2110
2112 2111 It adds a '.py' extension to the file if you don't do so yourself, and
2113 2112 it asks for confirmation before overwriting existing files."""
2114 2113
2115 2114 opts,args = self.parse_options(parameter_s,'r',mode='list')
2116 2115 fname, codefrom = unquote_filename(args[0]), " ".join(args[1:])
2117 2116 if not fname.endswith('.py'):
2118 2117 fname += '.py'
2119 2118 if os.path.isfile(fname):
2120 2119 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2121 2120 if ans.lower() not in ['y','yes']:
2122 2121 print 'Operation cancelled.'
2123 2122 return
2124 2123 try:
2125 2124 cmds = self.shell.find_user_code(codefrom, 'r' in opts)
2126 2125 except (TypeError, ValueError) as e:
2127 2126 print e.args[0]
2128 2127 return
2129 2128 with py3compat.open(fname,'w', encoding="utf-8") as f:
2130 2129 f.write(u"# coding: utf-8\n")
2131 2130 f.write(py3compat.cast_unicode(cmds))
2132 2131 print 'The following commands were written to file `%s`:' % fname
2133 2132 print cmds
2134 2133
2135 2134 def magic_pastebin(self, parameter_s = ''):
2136 2135 """Upload code to the 'Lodge it' paste bin, returning the URL."""
2137 2136 try:
2138 2137 code = self.shell.find_user_code(parameter_s)
2139 2138 except (ValueError, TypeError) as e:
2140 2139 print e.args[0]
2141 2140 return
2142 2141 pbserver = ServerProxy('http://paste.pocoo.org/xmlrpc/')
2143 2142 id = pbserver.pastes.newPaste("python", code)
2144 2143 return "http://paste.pocoo.org/show/" + id
2145 2144
2146 2145 def magic_loadpy(self, arg_s):
2147 2146 """Load a .py python script into the GUI console.
2148 2147
2149 2148 This magic command can either take a local filename or a url::
2150 2149
2151 2150 %loadpy myscript.py
2152 2151 %loadpy http://www.example.com/myscript.py
2153 2152 """
2154 2153 arg_s = unquote_filename(arg_s)
2155 2154 if not arg_s.endswith('.py'):
2156 2155 raise ValueError('%%load only works with .py files: %s' % arg_s)
2157 2156 if arg_s.startswith('http'):
2158 2157 import urllib2
2159 2158 response = urllib2.urlopen(arg_s)
2160 2159 content = response.read()
2161 2160 else:
2162 2161 with open(arg_s) as f:
2163 2162 content = f.read()
2164 2163 self.set_next_input(content)
2165 2164
2166 2165 def _find_edit_target(self, args, opts, last_call):
2167 2166 """Utility method used by magic_edit to find what to edit."""
2168 2167
2169 2168 def make_filename(arg):
2170 2169 "Make a filename from the given args"
2171 2170 arg = unquote_filename(arg)
2172 2171 try:
2173 2172 filename = get_py_filename(arg)
2174 2173 except IOError:
2175 2174 # If it ends with .py but doesn't already exist, assume we want
2176 2175 # a new file.
2177 2176 if arg.endswith('.py'):
2178 2177 filename = arg
2179 2178 else:
2180 2179 filename = None
2181 2180 return filename
2182 2181
2183 2182 # Set a few locals from the options for convenience:
2184 2183 opts_prev = 'p' in opts
2185 2184 opts_raw = 'r' in opts
2186 2185
2187 2186 # custom exceptions
2188 2187 class DataIsObject(Exception): pass
2189 2188
2190 2189 # Default line number value
2191 2190 lineno = opts.get('n',None)
2192 2191
2193 2192 if opts_prev:
2194 2193 args = '_%s' % last_call[0]
2195 2194 if not self.shell.user_ns.has_key(args):
2196 2195 args = last_call[1]
2197 2196
2198 2197 # use last_call to remember the state of the previous call, but don't
2199 2198 # let it be clobbered by successive '-p' calls.
2200 2199 try:
2201 2200 last_call[0] = self.shell.displayhook.prompt_count
2202 2201 if not opts_prev:
2203 2202 last_call[1] = parameter_s
2204 2203 except:
2205 2204 pass
2206 2205
2207 2206 # by default this is done with temp files, except when the given
2208 2207 # arg is a filename
2209 2208 use_temp = True
2210 2209
2211 2210 data = ''
2212 2211
2213 2212 # First, see if the arguments should be a filename.
2214 2213 filename = make_filename(args)
2215 2214 if filename:
2216 2215 use_temp = False
2217 2216 elif args:
2218 2217 # Mode where user specifies ranges of lines, like in %macro.
2219 2218 data = self.extract_input_lines(args, opts_raw)
2220 2219 if not data:
2221 2220 try:
2222 2221 # Load the parameter given as a variable. If not a string,
2223 2222 # process it as an object instead (below)
2224 2223
2225 2224 #print '*** args',args,'type',type(args) # dbg
2226 2225 data = eval(args, self.shell.user_ns)
2227 2226 if not isinstance(data, basestring):
2228 2227 raise DataIsObject
2229 2228
2230 2229 except (NameError,SyntaxError):
2231 2230 # given argument is not a variable, try as a filename
2232 2231 filename = make_filename(args)
2233 2232 if filename is None:
2234 2233 warn("Argument given (%s) can't be found as a variable "
2235 2234 "or as a filename." % args)
2236 2235 return
2237 2236 use_temp = False
2238 2237
2239 2238 except DataIsObject:
2240 2239 # macros have a special edit function
2241 2240 if isinstance(data, Macro):
2242 2241 raise MacroToEdit(data)
2243 2242
2244 2243 # For objects, try to edit the file where they are defined
2245 2244 try:
2246 2245 filename = inspect.getabsfile(data)
2247 2246 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2248 2247 # class created by %edit? Try to find source
2249 2248 # by looking for method definitions instead, the
2250 2249 # __module__ in those classes is FakeModule.
2251 2250 attrs = [getattr(data, aname) for aname in dir(data)]
2252 2251 for attr in attrs:
2253 2252 if not inspect.ismethod(attr):
2254 2253 continue
2255 2254 filename = inspect.getabsfile(attr)
2256 2255 if filename and 'fakemodule' not in filename.lower():
2257 2256 # change the attribute to be the edit target instead
2258 2257 data = attr
2259 2258 break
2260 2259
2261 2260 datafile = 1
2262 2261 except TypeError:
2263 2262 filename = make_filename(args)
2264 2263 datafile = 1
2265 2264 warn('Could not find file where `%s` is defined.\n'
2266 2265 'Opening a file named `%s`' % (args,filename))
2267 2266 # Now, make sure we can actually read the source (if it was in
2268 2267 # a temp file it's gone by now).
2269 2268 if datafile:
2270 2269 try:
2271 2270 if lineno is None:
2272 2271 lineno = inspect.getsourcelines(data)[1]
2273 2272 except IOError:
2274 2273 filename = make_filename(args)
2275 2274 if filename is None:
2276 2275 warn('The file `%s` where `%s` was defined cannot '
2277 2276 'be read.' % (filename,data))
2278 2277 return
2279 2278 use_temp = False
2280 2279
2281 2280 if use_temp:
2282 2281 filename = self.shell.mktempfile(data)
2283 2282 print 'IPython will make a temporary file named:',filename
2284 2283
2285 2284 return filename, lineno, use_temp
2286 2285
2287 2286 def _edit_macro(self,mname,macro):
2288 2287 """open an editor with the macro data in a file"""
2289 2288 filename = self.shell.mktempfile(macro.value)
2290 2289 self.shell.hooks.editor(filename)
2291 2290
2292 2291 # and make a new macro object, to replace the old one
2293 2292 mfile = open(filename)
2294 2293 mvalue = mfile.read()
2295 2294 mfile.close()
2296 2295 self.shell.user_ns[mname] = Macro(mvalue)
2297 2296
2298 2297 def magic_ed(self,parameter_s=''):
2299 2298 """Alias to %edit."""
2300 2299 return self.magic_edit(parameter_s)
2301 2300
2302 2301 @skip_doctest
2303 2302 def magic_edit(self,parameter_s='',last_call=['','']):
2304 2303 """Bring up an editor and execute the resulting code.
2305 2304
2306 2305 Usage:
2307 2306 %edit [options] [args]
2308 2307
2309 2308 %edit runs IPython's editor hook. The default version of this hook is
2310 2309 set to call the editor specified by your $EDITOR environment variable.
2311 2310 If this isn't found, it will default to vi under Linux/Unix and to
2312 2311 notepad under Windows. See the end of this docstring for how to change
2313 2312 the editor hook.
2314 2313
2315 2314 You can also set the value of this editor via the
2316 2315 ``TerminalInteractiveShell.editor`` option in your configuration file.
2317 2316 This is useful if you wish to use a different editor from your typical
2318 2317 default with IPython (and for Windows users who typically don't set
2319 2318 environment variables).
2320 2319
2321 2320 This command allows you to conveniently edit multi-line code right in
2322 2321 your IPython session.
2323 2322
2324 2323 If called without arguments, %edit opens up an empty editor with a
2325 2324 temporary file and will execute the contents of this file when you
2326 2325 close it (don't forget to save it!).
2327 2326
2328 2327
2329 2328 Options:
2330 2329
2331 2330 -n <number>: open the editor at a specified line number. By default,
2332 2331 the IPython editor hook uses the unix syntax 'editor +N filename', but
2333 2332 you can configure this by providing your own modified hook if your
2334 2333 favorite editor supports line-number specifications with a different
2335 2334 syntax.
2336 2335
2337 2336 -p: this will call the editor with the same data as the previous time
2338 2337 it was used, regardless of how long ago (in your current session) it
2339 2338 was.
2340 2339
2341 2340 -r: use 'raw' input. This option only applies to input taken from the
2342 2341 user's history. By default, the 'processed' history is used, so that
2343 2342 magics are loaded in their transformed version to valid Python. If
2344 2343 this option is given, the raw input as typed as the command line is
2345 2344 used instead. When you exit the editor, it will be executed by
2346 2345 IPython's own processor.
2347 2346
2348 2347 -x: do not execute the edited code immediately upon exit. This is
2349 2348 mainly useful if you are editing programs which need to be called with
2350 2349 command line arguments, which you can then do using %run.
2351 2350
2352 2351
2353 2352 Arguments:
2354 2353
2355 2354 If arguments are given, the following possibilites exist:
2356 2355
2357 2356 - If the argument is a filename, IPython will load that into the
2358 2357 editor. It will execute its contents with execfile() when you exit,
2359 2358 loading any code in the file into your interactive namespace.
2360 2359
2361 2360 - The arguments are ranges of input history, e.g. "7 ~1/4-6".
2362 2361 The syntax is the same as in the %history magic.
2363 2362
2364 2363 - If the argument is a string variable, its contents are loaded
2365 2364 into the editor. You can thus edit any string which contains
2366 2365 python code (including the result of previous edits).
2367 2366
2368 2367 - If the argument is the name of an object (other than a string),
2369 2368 IPython will try to locate the file where it was defined and open the
2370 2369 editor at the point where it is defined. You can use `%edit function`
2371 2370 to load an editor exactly at the point where 'function' is defined,
2372 2371 edit it and have the file be executed automatically.
2373 2372
2374 2373 - If the object is a macro (see %macro for details), this opens up your
2375 2374 specified editor with a temporary file containing the macro's data.
2376 2375 Upon exit, the macro is reloaded with the contents of the file.
2377 2376
2378 2377 Note: opening at an exact line is only supported under Unix, and some
2379 2378 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2380 2379 '+NUMBER' parameter necessary for this feature. Good editors like
2381 2380 (X)Emacs, vi, jed, pico and joe all do.
2382 2381
2383 2382 After executing your code, %edit will return as output the code you
2384 2383 typed in the editor (except when it was an existing file). This way
2385 2384 you can reload the code in further invocations of %edit as a variable,
2386 2385 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2387 2386 the output.
2388 2387
2389 2388 Note that %edit is also available through the alias %ed.
2390 2389
2391 2390 This is an example of creating a simple function inside the editor and
2392 2391 then modifying it. First, start up the editor:
2393 2392
2394 2393 In [1]: ed
2395 2394 Editing... done. Executing edited code...
2396 2395 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2397 2396
2398 2397 We can then call the function foo():
2399 2398
2400 2399 In [2]: foo()
2401 2400 foo() was defined in an editing session
2402 2401
2403 2402 Now we edit foo. IPython automatically loads the editor with the
2404 2403 (temporary) file where foo() was previously defined:
2405 2404
2406 2405 In [3]: ed foo
2407 2406 Editing... done. Executing edited code...
2408 2407
2409 2408 And if we call foo() again we get the modified version:
2410 2409
2411 2410 In [4]: foo()
2412 2411 foo() has now been changed!
2413 2412
2414 2413 Here is an example of how to edit a code snippet successive
2415 2414 times. First we call the editor:
2416 2415
2417 2416 In [5]: ed
2418 2417 Editing... done. Executing edited code...
2419 2418 hello
2420 2419 Out[5]: "print 'hello'n"
2421 2420
2422 2421 Now we call it again with the previous output (stored in _):
2423 2422
2424 2423 In [6]: ed _
2425 2424 Editing... done. Executing edited code...
2426 2425 hello world
2427 2426 Out[6]: "print 'hello world'n"
2428 2427
2429 2428 Now we call it with the output #8 (stored in _8, also as Out[8]):
2430 2429
2431 2430 In [7]: ed _8
2432 2431 Editing... done. Executing edited code...
2433 2432 hello again
2434 2433 Out[7]: "print 'hello again'n"
2435 2434
2436 2435
2437 2436 Changing the default editor hook:
2438 2437
2439 2438 If you wish to write your own editor hook, you can put it in a
2440 2439 configuration file which you load at startup time. The default hook
2441 2440 is defined in the IPython.core.hooks module, and you can use that as a
2442 2441 starting example for further modifications. That file also has
2443 2442 general instructions on how to set a new hook for use once you've
2444 2443 defined it."""
2445 2444 opts,args = self.parse_options(parameter_s,'prxn:')
2446 2445
2447 2446 try:
2448 2447 filename, lineno, is_temp = self._find_edit_target(args, opts, last_call)
2449 2448 except MacroToEdit as e:
2450 2449 self._edit_macro(args, e.args[0])
2451 2450 return
2452 2451
2453 2452 # do actual editing here
2454 2453 print 'Editing...',
2455 2454 sys.stdout.flush()
2456 2455 try:
2457 2456 # Quote filenames that may have spaces in them
2458 2457 if ' ' in filename:
2459 2458 filename = "'%s'" % filename
2460 2459 self.shell.hooks.editor(filename,lineno)
2461 2460 except TryNext:
2462 2461 warn('Could not open editor')
2463 2462 return
2464 2463
2465 2464 # XXX TODO: should this be generalized for all string vars?
2466 2465 # For now, this is special-cased to blocks created by cpaste
2467 2466 if args.strip() == 'pasted_block':
2468 2467 self.shell.user_ns['pasted_block'] = file_read(filename)
2469 2468
2470 2469 if 'x' in opts: # -x prevents actual execution
2471 2470 print
2472 2471 else:
2473 2472 print 'done. Executing edited code...'
2474 2473 if 'r' in opts: # Untranslated IPython code
2475 2474 self.shell.run_cell(file_read(filename),
2476 2475 store_history=False)
2477 2476 else:
2478 2477 self.shell.safe_execfile(filename,self.shell.user_ns,
2479 2478 self.shell.user_ns)
2480 2479
2481 2480 if is_temp:
2482 2481 try:
2483 2482 return open(filename).read()
2484 2483 except IOError,msg:
2485 2484 if msg.filename == filename:
2486 2485 warn('File not found. Did you forget to save?')
2487 2486 return
2488 2487 else:
2489 2488 self.shell.showtraceback()
2490 2489
2491 2490 def magic_xmode(self,parameter_s = ''):
2492 2491 """Switch modes for the exception handlers.
2493 2492
2494 2493 Valid modes: Plain, Context and Verbose.
2495 2494
2496 2495 If called without arguments, acts as a toggle."""
2497 2496
2498 2497 def xmode_switch_err(name):
2499 2498 warn('Error changing %s exception modes.\n%s' %
2500 2499 (name,sys.exc_info()[1]))
2501 2500
2502 2501 shell = self.shell
2503 2502 new_mode = parameter_s.strip().capitalize()
2504 2503 try:
2505 2504 shell.InteractiveTB.set_mode(mode=new_mode)
2506 2505 print 'Exception reporting mode:',shell.InteractiveTB.mode
2507 2506 except:
2508 2507 xmode_switch_err('user')
2509 2508
2510 2509 def magic_colors(self,parameter_s = ''):
2511 2510 """Switch color scheme for prompts, info system and exception handlers.
2512 2511
2513 2512 Currently implemented schemes: NoColor, Linux, LightBG.
2514 2513
2515 2514 Color scheme names are not case-sensitive.
2516 2515
2517 2516 Examples
2518 2517 --------
2519 2518 To get a plain black and white terminal::
2520 2519
2521 2520 %colors nocolor
2522 2521 """
2523 2522
2524 2523 def color_switch_err(name):
2525 2524 warn('Error changing %s color schemes.\n%s' %
2526 2525 (name,sys.exc_info()[1]))
2527 2526
2528 2527
2529 2528 new_scheme = parameter_s.strip()
2530 2529 if not new_scheme:
2531 2530 raise UsageError(
2532 2531 "%colors: you must specify a color scheme. See '%colors?'")
2533 2532 return
2534 2533 # local shortcut
2535 2534 shell = self.shell
2536 2535
2537 2536 import IPython.utils.rlineimpl as readline
2538 2537
2539 2538 if not shell.colors_force and \
2540 2539 not readline.have_readline and sys.platform == "win32":
2541 2540 msg = """\
2542 2541 Proper color support under MS Windows requires the pyreadline library.
2543 2542 You can find it at:
2544 2543 http://ipython.org/pyreadline.html
2545 2544 Gary's readline needs the ctypes module, from:
2546 2545 http://starship.python.net/crew/theller/ctypes
2547 2546 (Note that ctypes is already part of Python versions 2.5 and newer).
2548 2547
2549 2548 Defaulting color scheme to 'NoColor'"""
2550 2549 new_scheme = 'NoColor'
2551 2550 warn(msg)
2552 2551
2553 2552 # readline option is 0
2554 2553 if not shell.colors_force and not shell.has_readline:
2555 2554 new_scheme = 'NoColor'
2556 2555
2557 2556 # Set prompt colors
2558 2557 try:
2559 2558 shell.displayhook.set_colors(new_scheme)
2560 2559 except:
2561 2560 color_switch_err('prompt')
2562 2561 else:
2563 2562 shell.colors = \
2564 2563 shell.displayhook.color_table.active_scheme_name
2565 2564 # Set exception colors
2566 2565 try:
2567 2566 shell.InteractiveTB.set_colors(scheme = new_scheme)
2568 2567 shell.SyntaxTB.set_colors(scheme = new_scheme)
2569 2568 except:
2570 2569 color_switch_err('exception')
2571 2570
2572 2571 # Set info (for 'object?') colors
2573 2572 if shell.color_info:
2574 2573 try:
2575 2574 shell.inspector.set_active_scheme(new_scheme)
2576 2575 except:
2577 2576 color_switch_err('object inspector')
2578 2577 else:
2579 2578 shell.inspector.set_active_scheme('NoColor')
2580 2579
2581 2580 def magic_pprint(self, parameter_s=''):
2582 2581 """Toggle pretty printing on/off."""
2583 2582 ptformatter = self.shell.display_formatter.formatters['text/plain']
2584 2583 ptformatter.pprint = bool(1 - ptformatter.pprint)
2585 2584 print 'Pretty printing has been turned', \
2586 2585 ['OFF','ON'][ptformatter.pprint]
2587 2586
2588 2587 #......................................................................
2589 2588 # Functions to implement unix shell-type things
2590 2589
2591 2590 @skip_doctest
2592 2591 def magic_alias(self, parameter_s = ''):
2593 2592 """Define an alias for a system command.
2594 2593
2595 2594 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2596 2595
2597 2596 Then, typing 'alias_name params' will execute the system command 'cmd
2598 2597 params' (from your underlying operating system).
2599 2598
2600 2599 Aliases have lower precedence than magic functions and Python normal
2601 2600 variables, so if 'foo' is both a Python variable and an alias, the
2602 2601 alias can not be executed until 'del foo' removes the Python variable.
2603 2602
2604 2603 You can use the %l specifier in an alias definition to represent the
2605 2604 whole line when the alias is called. For example:
2606 2605
2607 2606 In [2]: alias bracket echo "Input in brackets: <%l>"
2608 2607 In [3]: bracket hello world
2609 2608 Input in brackets: <hello world>
2610 2609
2611 2610 You can also define aliases with parameters using %s specifiers (one
2612 2611 per parameter):
2613 2612
2614 2613 In [1]: alias parts echo first %s second %s
2615 2614 In [2]: %parts A B
2616 2615 first A second B
2617 2616 In [3]: %parts A
2618 2617 Incorrect number of arguments: 2 expected.
2619 2618 parts is an alias to: 'echo first %s second %s'
2620 2619
2621 2620 Note that %l and %s are mutually exclusive. You can only use one or
2622 2621 the other in your aliases.
2623 2622
2624 2623 Aliases expand Python variables just like system calls using ! or !!
2625 2624 do: all expressions prefixed with '$' get expanded. For details of
2626 2625 the semantic rules, see PEP-215:
2627 2626 http://www.python.org/peps/pep-0215.html. This is the library used by
2628 2627 IPython for variable expansion. If you want to access a true shell
2629 2628 variable, an extra $ is necessary to prevent its expansion by IPython:
2630 2629
2631 2630 In [6]: alias show echo
2632 2631 In [7]: PATH='A Python string'
2633 2632 In [8]: show $PATH
2634 2633 A Python string
2635 2634 In [9]: show $$PATH
2636 2635 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2637 2636
2638 2637 You can use the alias facility to acess all of $PATH. See the %rehash
2639 2638 and %rehashx functions, which automatically create aliases for the
2640 2639 contents of your $PATH.
2641 2640
2642 2641 If called with no parameters, %alias prints the current alias table."""
2643 2642
2644 2643 par = parameter_s.strip()
2645 2644 if not par:
2646 2645 stored = self.db.get('stored_aliases', {} )
2647 2646 aliases = sorted(self.shell.alias_manager.aliases)
2648 2647 # for k, v in stored:
2649 2648 # atab.append(k, v[0])
2650 2649
2651 2650 print "Total number of aliases:", len(aliases)
2652 2651 sys.stdout.flush()
2653 2652 return aliases
2654 2653
2655 2654 # Now try to define a new one
2656 2655 try:
2657 2656 alias,cmd = par.split(None, 1)
2658 2657 except:
2659 2658 print oinspect.getdoc(self.magic_alias)
2660 2659 else:
2661 2660 self.shell.alias_manager.soft_define_alias(alias, cmd)
2662 2661 # end magic_alias
2663 2662
2664 2663 def magic_unalias(self, parameter_s = ''):
2665 2664 """Remove an alias"""
2666 2665
2667 2666 aname = parameter_s.strip()
2668 2667 self.shell.alias_manager.undefine_alias(aname)
2669 2668 stored = self.db.get('stored_aliases', {} )
2670 2669 if aname in stored:
2671 2670 print "Removing %stored alias",aname
2672 2671 del stored[aname]
2673 2672 self.db['stored_aliases'] = stored
2674 2673
2675 2674 def magic_rehashx(self, parameter_s = ''):
2676 2675 """Update the alias table with all executable files in $PATH.
2677 2676
2678 2677 This version explicitly checks that every entry in $PATH is a file
2679 2678 with execute access (os.X_OK), so it is much slower than %rehash.
2680 2679
2681 2680 Under Windows, it checks executability as a match agains a
2682 2681 '|'-separated string of extensions, stored in the IPython config
2683 2682 variable win_exec_ext. This defaults to 'exe|com|bat'.
2684 2683
2685 2684 This function also resets the root module cache of module completer,
2686 2685 used on slow filesystems.
2687 2686 """
2688 2687 from IPython.core.alias import InvalidAliasError
2689 2688
2690 2689 # for the benefit of module completer in ipy_completers.py
2691 2690 del self.shell.db['rootmodules']
2692 2691
2693 2692 path = [os.path.abspath(os.path.expanduser(p)) for p in
2694 2693 os.environ.get('PATH','').split(os.pathsep)]
2695 2694 path = filter(os.path.isdir,path)
2696 2695
2697 2696 syscmdlist = []
2698 2697 # Now define isexec in a cross platform manner.
2699 2698 if os.name == 'posix':
2700 2699 isexec = lambda fname:os.path.isfile(fname) and \
2701 2700 os.access(fname,os.X_OK)
2702 2701 else:
2703 2702 try:
2704 2703 winext = os.environ['pathext'].replace(';','|').replace('.','')
2705 2704 except KeyError:
2706 2705 winext = 'exe|com|bat|py'
2707 2706 if 'py' not in winext:
2708 2707 winext += '|py'
2709 2708 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2710 2709 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2711 2710 savedir = os.getcwdu()
2712 2711
2713 2712 # Now walk the paths looking for executables to alias.
2714 2713 try:
2715 2714 # write the whole loop for posix/Windows so we don't have an if in
2716 2715 # the innermost part
2717 2716 if os.name == 'posix':
2718 2717 for pdir in path:
2719 2718 os.chdir(pdir)
2720 2719 for ff in os.listdir(pdir):
2721 2720 if isexec(ff):
2722 2721 try:
2723 2722 # Removes dots from the name since ipython
2724 2723 # will assume names with dots to be python.
2725 2724 self.shell.alias_manager.define_alias(
2726 2725 ff.replace('.',''), ff)
2727 2726 except InvalidAliasError:
2728 2727 pass
2729 2728 else:
2730 2729 syscmdlist.append(ff)
2731 2730 else:
2732 2731 no_alias = self.shell.alias_manager.no_alias
2733 2732 for pdir in path:
2734 2733 os.chdir(pdir)
2735 2734 for ff in os.listdir(pdir):
2736 2735 base, ext = os.path.splitext(ff)
2737 2736 if isexec(ff) and base.lower() not in no_alias:
2738 2737 if ext.lower() == '.exe':
2739 2738 ff = base
2740 2739 try:
2741 2740 # Removes dots from the name since ipython
2742 2741 # will assume names with dots to be python.
2743 2742 self.shell.alias_manager.define_alias(
2744 2743 base.lower().replace('.',''), ff)
2745 2744 except InvalidAliasError:
2746 2745 pass
2747 2746 syscmdlist.append(ff)
2748 2747 self.shell.db['syscmdlist'] = syscmdlist
2749 2748 finally:
2750 2749 os.chdir(savedir)
2751 2750
2752 2751 @skip_doctest
2753 2752 def magic_pwd(self, parameter_s = ''):
2754 2753 """Return the current working directory path.
2755 2754
2756 2755 Examples
2757 2756 --------
2758 2757 ::
2759 2758
2760 2759 In [9]: pwd
2761 2760 Out[9]: '/home/tsuser/sprint/ipython'
2762 2761 """
2763 2762 return os.getcwdu()
2764 2763
2765 2764 @skip_doctest
2766 2765 def magic_cd(self, parameter_s=''):
2767 2766 """Change the current working directory.
2768 2767
2769 2768 This command automatically maintains an internal list of directories
2770 2769 you visit during your IPython session, in the variable _dh. The
2771 2770 command %dhist shows this history nicely formatted. You can also
2772 2771 do 'cd -<tab>' to see directory history conveniently.
2773 2772
2774 2773 Usage:
2775 2774
2776 2775 cd 'dir': changes to directory 'dir'.
2777 2776
2778 2777 cd -: changes to the last visited directory.
2779 2778
2780 2779 cd -<n>: changes to the n-th directory in the directory history.
2781 2780
2782 2781 cd --foo: change to directory that matches 'foo' in history
2783 2782
2784 2783 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2785 2784 (note: cd <bookmark_name> is enough if there is no
2786 2785 directory <bookmark_name>, but a bookmark with the name exists.)
2787 2786 'cd -b <tab>' allows you to tab-complete bookmark names.
2788 2787
2789 2788 Options:
2790 2789
2791 2790 -q: quiet. Do not print the working directory after the cd command is
2792 2791 executed. By default IPython's cd command does print this directory,
2793 2792 since the default prompts do not display path information.
2794 2793
2795 2794 Note that !cd doesn't work for this purpose because the shell where
2796 2795 !command runs is immediately discarded after executing 'command'.
2797 2796
2798 2797 Examples
2799 2798 --------
2800 2799 ::
2801 2800
2802 2801 In [10]: cd parent/child
2803 2802 /home/tsuser/parent/child
2804 2803 """
2805 2804
2806 2805 parameter_s = parameter_s.strip()
2807 2806 #bkms = self.shell.persist.get("bookmarks",{})
2808 2807
2809 2808 oldcwd = os.getcwdu()
2810 2809 numcd = re.match(r'(-)(\d+)$',parameter_s)
2811 2810 # jump in directory history by number
2812 2811 if numcd:
2813 2812 nn = int(numcd.group(2))
2814 2813 try:
2815 2814 ps = self.shell.user_ns['_dh'][nn]
2816 2815 except IndexError:
2817 2816 print 'The requested directory does not exist in history.'
2818 2817 return
2819 2818 else:
2820 2819 opts = {}
2821 2820 elif parameter_s.startswith('--'):
2822 2821 ps = None
2823 2822 fallback = None
2824 2823 pat = parameter_s[2:]
2825 2824 dh = self.shell.user_ns['_dh']
2826 2825 # first search only by basename (last component)
2827 2826 for ent in reversed(dh):
2828 2827 if pat in os.path.basename(ent) and os.path.isdir(ent):
2829 2828 ps = ent
2830 2829 break
2831 2830
2832 2831 if fallback is None and pat in ent and os.path.isdir(ent):
2833 2832 fallback = ent
2834 2833
2835 2834 # if we have no last part match, pick the first full path match
2836 2835 if ps is None:
2837 2836 ps = fallback
2838 2837
2839 2838 if ps is None:
2840 2839 print "No matching entry in directory history"
2841 2840 return
2842 2841 else:
2843 2842 opts = {}
2844 2843
2845 2844
2846 2845 else:
2847 2846 #turn all non-space-escaping backslashes to slashes,
2848 2847 # for c:\windows\directory\names\
2849 2848 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2850 2849 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2851 2850 # jump to previous
2852 2851 if ps == '-':
2853 2852 try:
2854 2853 ps = self.shell.user_ns['_dh'][-2]
2855 2854 except IndexError:
2856 2855 raise UsageError('%cd -: No previous directory to change to.')
2857 2856 # jump to bookmark if needed
2858 2857 else:
2859 2858 if not os.path.isdir(ps) or opts.has_key('b'):
2860 2859 bkms = self.db.get('bookmarks', {})
2861 2860
2862 2861 if bkms.has_key(ps):
2863 2862 target = bkms[ps]
2864 2863 print '(bookmark:%s) -> %s' % (ps,target)
2865 2864 ps = target
2866 2865 else:
2867 2866 if opts.has_key('b'):
2868 2867 raise UsageError("Bookmark '%s' not found. "
2869 2868 "Use '%%bookmark -l' to see your bookmarks." % ps)
2870 2869
2871 2870 # strip extra quotes on Windows, because os.chdir doesn't like them
2872 2871 ps = unquote_filename(ps)
2873 2872 # at this point ps should point to the target dir
2874 2873 if ps:
2875 2874 try:
2876 2875 os.chdir(os.path.expanduser(ps))
2877 2876 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2878 2877 set_term_title('IPython: ' + abbrev_cwd())
2879 2878 except OSError:
2880 2879 print sys.exc_info()[1]
2881 2880 else:
2882 2881 cwd = os.getcwdu()
2883 2882 dhist = self.shell.user_ns['_dh']
2884 2883 if oldcwd != cwd:
2885 2884 dhist.append(cwd)
2886 2885 self.db['dhist'] = compress_dhist(dhist)[-100:]
2887 2886
2888 2887 else:
2889 2888 os.chdir(self.shell.home_dir)
2890 2889 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2891 2890 set_term_title('IPython: ' + '~')
2892 2891 cwd = os.getcwdu()
2893 2892 dhist = self.shell.user_ns['_dh']
2894 2893
2895 2894 if oldcwd != cwd:
2896 2895 dhist.append(cwd)
2897 2896 self.db['dhist'] = compress_dhist(dhist)[-100:]
2898 2897 if not 'q' in opts and self.shell.user_ns['_dh']:
2899 2898 print self.shell.user_ns['_dh'][-1]
2900 2899
2901 2900
2902 2901 def magic_env(self, parameter_s=''):
2903 2902 """List environment variables."""
2904 2903
2905 2904 return os.environ.data
2906 2905
2907 2906 def magic_pushd(self, parameter_s=''):
2908 2907 """Place the current dir on stack and change directory.
2909 2908
2910 2909 Usage:\\
2911 2910 %pushd ['dirname']
2912 2911 """
2913 2912
2914 2913 dir_s = self.shell.dir_stack
2915 2914 tgt = os.path.expanduser(unquote_filename(parameter_s))
2916 2915 cwd = os.getcwdu().replace(self.home_dir,'~')
2917 2916 if tgt:
2918 2917 self.magic_cd(parameter_s)
2919 2918 dir_s.insert(0,cwd)
2920 2919 return self.magic_dirs()
2921 2920
2922 2921 def magic_popd(self, parameter_s=''):
2923 2922 """Change to directory popped off the top of the stack.
2924 2923 """
2925 2924 if not self.shell.dir_stack:
2926 2925 raise UsageError("%popd on empty stack")
2927 2926 top = self.shell.dir_stack.pop(0)
2928 2927 self.magic_cd(top)
2929 2928 print "popd ->",top
2930 2929
2931 2930 def magic_dirs(self, parameter_s=''):
2932 2931 """Return the current directory stack."""
2933 2932
2934 2933 return self.shell.dir_stack
2935 2934
2936 2935 def magic_dhist(self, parameter_s=''):
2937 2936 """Print your history of visited directories.
2938 2937
2939 2938 %dhist -> print full history\\
2940 2939 %dhist n -> print last n entries only\\
2941 2940 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2942 2941
2943 2942 This history is automatically maintained by the %cd command, and
2944 2943 always available as the global list variable _dh. You can use %cd -<n>
2945 2944 to go to directory number <n>.
2946 2945
2947 2946 Note that most of time, you should view directory history by entering
2948 2947 cd -<TAB>.
2949 2948
2950 2949 """
2951 2950
2952 2951 dh = self.shell.user_ns['_dh']
2953 2952 if parameter_s:
2954 2953 try:
2955 2954 args = map(int,parameter_s.split())
2956 2955 except:
2957 2956 self.arg_err(Magic.magic_dhist)
2958 2957 return
2959 2958 if len(args) == 1:
2960 2959 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2961 2960 elif len(args) == 2:
2962 2961 ini,fin = args
2963 2962 else:
2964 2963 self.arg_err(Magic.magic_dhist)
2965 2964 return
2966 2965 else:
2967 2966 ini,fin = 0,len(dh)
2968 2967 nlprint(dh,
2969 2968 header = 'Directory history (kept in _dh)',
2970 2969 start=ini,stop=fin)
2971 2970
2972 2971 @skip_doctest
2973 2972 def magic_sc(self, parameter_s=''):
2974 2973 """Shell capture - execute a shell command and capture its output.
2975 2974
2976 2975 DEPRECATED. Suboptimal, retained for backwards compatibility.
2977 2976
2978 2977 You should use the form 'var = !command' instead. Example:
2979 2978
2980 2979 "%sc -l myfiles = ls ~" should now be written as
2981 2980
2982 2981 "myfiles = !ls ~"
2983 2982
2984 2983 myfiles.s, myfiles.l and myfiles.n still apply as documented
2985 2984 below.
2986 2985
2987 2986 --
2988 2987 %sc [options] varname=command
2989 2988
2990 2989 IPython will run the given command using commands.getoutput(), and
2991 2990 will then update the user's interactive namespace with a variable
2992 2991 called varname, containing the value of the call. Your command can
2993 2992 contain shell wildcards, pipes, etc.
2994 2993
2995 2994 The '=' sign in the syntax is mandatory, and the variable name you
2996 2995 supply must follow Python's standard conventions for valid names.
2997 2996
2998 2997 (A special format without variable name exists for internal use)
2999 2998
3000 2999 Options:
3001 3000
3002 3001 -l: list output. Split the output on newlines into a list before
3003 3002 assigning it to the given variable. By default the output is stored
3004 3003 as a single string.
3005 3004
3006 3005 -v: verbose. Print the contents of the variable.
3007 3006
3008 3007 In most cases you should not need to split as a list, because the
3009 3008 returned value is a special type of string which can automatically
3010 3009 provide its contents either as a list (split on newlines) or as a
3011 3010 space-separated string. These are convenient, respectively, either
3012 3011 for sequential processing or to be passed to a shell command.
3013 3012
3014 3013 For example:
3015 3014
3016 3015 # all-random
3017 3016
3018 3017 # Capture into variable a
3019 3018 In [1]: sc a=ls *py
3020 3019
3021 3020 # a is a string with embedded newlines
3022 3021 In [2]: a
3023 3022 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
3024 3023
3025 3024 # which can be seen as a list:
3026 3025 In [3]: a.l
3027 3026 Out[3]: ['setup.py', 'win32_manual_post_install.py']
3028 3027
3029 3028 # or as a whitespace-separated string:
3030 3029 In [4]: a.s
3031 3030 Out[4]: 'setup.py win32_manual_post_install.py'
3032 3031
3033 3032 # a.s is useful to pass as a single command line:
3034 3033 In [5]: !wc -l $a.s
3035 3034 146 setup.py
3036 3035 130 win32_manual_post_install.py
3037 3036 276 total
3038 3037
3039 3038 # while the list form is useful to loop over:
3040 3039 In [6]: for f in a.l:
3041 3040 ...: !wc -l $f
3042 3041 ...:
3043 3042 146 setup.py
3044 3043 130 win32_manual_post_install.py
3045 3044
3046 3045 Similiarly, the lists returned by the -l option are also special, in
3047 3046 the sense that you can equally invoke the .s attribute on them to
3048 3047 automatically get a whitespace-separated string from their contents:
3049 3048
3050 3049 In [7]: sc -l b=ls *py
3051 3050
3052 3051 In [8]: b
3053 3052 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3054 3053
3055 3054 In [9]: b.s
3056 3055 Out[9]: 'setup.py win32_manual_post_install.py'
3057 3056
3058 3057 In summary, both the lists and strings used for ouptut capture have
3059 3058 the following special attributes:
3060 3059
3061 3060 .l (or .list) : value as list.
3062 3061 .n (or .nlstr): value as newline-separated string.
3063 3062 .s (or .spstr): value as space-separated string.
3064 3063 """
3065 3064
3066 3065 opts,args = self.parse_options(parameter_s,'lv')
3067 3066 # Try to get a variable name and command to run
3068 3067 try:
3069 3068 # the variable name must be obtained from the parse_options
3070 3069 # output, which uses shlex.split to strip options out.
3071 3070 var,_ = args.split('=',1)
3072 3071 var = var.strip()
3073 3072 # But the the command has to be extracted from the original input
3074 3073 # parameter_s, not on what parse_options returns, to avoid the
3075 3074 # quote stripping which shlex.split performs on it.
3076 3075 _,cmd = parameter_s.split('=',1)
3077 3076 except ValueError:
3078 3077 var,cmd = '',''
3079 3078 # If all looks ok, proceed
3080 3079 split = 'l' in opts
3081 3080 out = self.shell.getoutput(cmd, split=split)
3082 3081 if opts.has_key('v'):
3083 3082 print '%s ==\n%s' % (var,pformat(out))
3084 3083 if var:
3085 3084 self.shell.user_ns.update({var:out})
3086 3085 else:
3087 3086 return out
3088 3087
3089 3088 def magic_sx(self, parameter_s=''):
3090 3089 """Shell execute - run a shell command and capture its output.
3091 3090
3092 3091 %sx command
3093 3092
3094 3093 IPython will run the given command using commands.getoutput(), and
3095 3094 return the result formatted as a list (split on '\\n'). Since the
3096 3095 output is _returned_, it will be stored in ipython's regular output
3097 3096 cache Out[N] and in the '_N' automatic variables.
3098 3097
3099 3098 Notes:
3100 3099
3101 3100 1) If an input line begins with '!!', then %sx is automatically
3102 3101 invoked. That is, while:
3103 3102 !ls
3104 3103 causes ipython to simply issue system('ls'), typing
3105 3104 !!ls
3106 3105 is a shorthand equivalent to:
3107 3106 %sx ls
3108 3107
3109 3108 2) %sx differs from %sc in that %sx automatically splits into a list,
3110 3109 like '%sc -l'. The reason for this is to make it as easy as possible
3111 3110 to process line-oriented shell output via further python commands.
3112 3111 %sc is meant to provide much finer control, but requires more
3113 3112 typing.
3114 3113
3115 3114 3) Just like %sc -l, this is a list with special attributes:
3116 3115
3117 3116 .l (or .list) : value as list.
3118 3117 .n (or .nlstr): value as newline-separated string.
3119 3118 .s (or .spstr): value as whitespace-separated string.
3120 3119
3121 3120 This is very useful when trying to use such lists as arguments to
3122 3121 system commands."""
3123 3122
3124 3123 if parameter_s:
3125 3124 return self.shell.getoutput(parameter_s)
3126 3125
3127 3126
3128 3127 def magic_bookmark(self, parameter_s=''):
3129 3128 """Manage IPython's bookmark system.
3130 3129
3131 3130 %bookmark <name> - set bookmark to current dir
3132 3131 %bookmark <name> <dir> - set bookmark to <dir>
3133 3132 %bookmark -l - list all bookmarks
3134 3133 %bookmark -d <name> - remove bookmark
3135 3134 %bookmark -r - remove all bookmarks
3136 3135
3137 3136 You can later on access a bookmarked folder with:
3138 3137 %cd -b <name>
3139 3138 or simply '%cd <name>' if there is no directory called <name> AND
3140 3139 there is such a bookmark defined.
3141 3140
3142 3141 Your bookmarks persist through IPython sessions, but they are
3143 3142 associated with each profile."""
3144 3143
3145 3144 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3146 3145 if len(args) > 2:
3147 3146 raise UsageError("%bookmark: too many arguments")
3148 3147
3149 3148 bkms = self.db.get('bookmarks',{})
3150 3149
3151 3150 if opts.has_key('d'):
3152 3151 try:
3153 3152 todel = args[0]
3154 3153 except IndexError:
3155 3154 raise UsageError(
3156 3155 "%bookmark -d: must provide a bookmark to delete")
3157 3156 else:
3158 3157 try:
3159 3158 del bkms[todel]
3160 3159 except KeyError:
3161 3160 raise UsageError(
3162 3161 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3163 3162
3164 3163 elif opts.has_key('r'):
3165 3164 bkms = {}
3166 3165 elif opts.has_key('l'):
3167 3166 bks = bkms.keys()
3168 3167 bks.sort()
3169 3168 if bks:
3170 3169 size = max(map(len,bks))
3171 3170 else:
3172 3171 size = 0
3173 3172 fmt = '%-'+str(size)+'s -> %s'
3174 3173 print 'Current bookmarks:'
3175 3174 for bk in bks:
3176 3175 print fmt % (bk,bkms[bk])
3177 3176 else:
3178 3177 if not args:
3179 3178 raise UsageError("%bookmark: You must specify the bookmark name")
3180 3179 elif len(args)==1:
3181 3180 bkms[args[0]] = os.getcwdu()
3182 3181 elif len(args)==2:
3183 3182 bkms[args[0]] = args[1]
3184 3183 self.db['bookmarks'] = bkms
3185 3184
3186 3185 def magic_pycat(self, parameter_s=''):
3187 3186 """Show a syntax-highlighted file through a pager.
3188 3187
3189 3188 This magic is similar to the cat utility, but it will assume the file
3190 3189 to be Python source and will show it with syntax highlighting. """
3191 3190
3192 3191 try:
3193 3192 filename = get_py_filename(parameter_s)
3194 3193 cont = file_read(filename)
3195 3194 except IOError:
3196 3195 try:
3197 3196 cont = eval(parameter_s,self.user_ns)
3198 3197 except NameError:
3199 3198 cont = None
3200 3199 if cont is None:
3201 3200 print "Error: no such file or variable"
3202 3201 return
3203 3202
3204 3203 page.page(self.shell.pycolorize(cont))
3205 3204
3206 def _rerun_pasted(self):
3207 """ Rerun a previously pasted command.
3208 """
3209 b = self.user_ns.get('pasted_block', None)
3210 if b is None:
3211 raise UsageError('No previous pasted block available')
3212 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3213 exec b in self.user_ns
3214
3215 def _get_pasted_lines(self, sentinel):
3216 """ Yield pasted lines until the user enters the given sentinel value.
3217 """
3218 from IPython.core import interactiveshell
3219 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3220 while True:
3221 try:
3222 l = self.shell.raw_input_original(':')
3223 if l == sentinel:
3224 return
3225 else:
3226 yield l
3227 except EOFError:
3228 print '<EOF>'
3229 return
3230
3231 def _strip_pasted_lines_for_code(self, raw_lines):
3232 """ Strip non-code parts of a sequence of lines to return a block of
3233 code.
3234 """
3235 # Regular expressions that declare text we strip from the input:
3236 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3237 r'^\s*(\s?>)+', # Python input prompt
3238 r'^\s*\.{3,}', # Continuation prompts
3239 r'^\++',
3240 ]
3241
3242 strip_from_start = map(re.compile,strip_re)
3243
3244 lines = []
3245 for l in raw_lines:
3246 for pat in strip_from_start:
3247 l = pat.sub('',l)
3248 lines.append(l)
3249
3250 block = "\n".join(lines) + '\n'
3251 #print "block:\n",block
3252 return block
3253
3254 def _execute_block(self, block, par):
3255 """ Execute a block, or store it in a variable, per the user's request.
3256 """
3257 if not par:
3258 b = textwrap.dedent(block)
3259 self.user_ns['pasted_block'] = b
3260 self.run_cell(b)
3261 else:
3262 self.user_ns[par] = SList(block.splitlines())
3263 print "Block assigned to '%s'" % par
3264
3265 3205 def magic_quickref(self,arg):
3266 3206 """ Show a quick reference sheet """
3267 3207 import IPython.core.usage
3268 3208 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3269 3209
3270 3210 page.page(qr)
3271 3211
3272 3212 def magic_doctest_mode(self,parameter_s=''):
3273 3213 """Toggle doctest mode on and off.
3274 3214
3275 3215 This mode is intended to make IPython behave as much as possible like a
3276 3216 plain Python shell, from the perspective of how its prompts, exceptions
3277 3217 and output look. This makes it easy to copy and paste parts of a
3278 3218 session into doctests. It does so by:
3279 3219
3280 3220 - Changing the prompts to the classic ``>>>`` ones.
3281 3221 - Changing the exception reporting mode to 'Plain'.
3282 3222 - Disabling pretty-printing of output.
3283 3223
3284 3224 Note that IPython also supports the pasting of code snippets that have
3285 3225 leading '>>>' and '...' prompts in them. This means that you can paste
3286 3226 doctests from files or docstrings (even if they have leading
3287 3227 whitespace), and the code will execute correctly. You can then use
3288 3228 '%history -t' to see the translated history; this will give you the
3289 3229 input after removal of all the leading prompts and whitespace, which
3290 3230 can be pasted back into an editor.
3291 3231
3292 3232 With these features, you can switch into this mode easily whenever you
3293 3233 need to do testing and changes to doctests, without having to leave
3294 3234 your existing IPython session.
3295 3235 """
3296 3236
3297 3237 from IPython.utils.ipstruct import Struct
3298 3238
3299 3239 # Shorthands
3300 3240 shell = self.shell
3301 3241 oc = shell.displayhook
3302 3242 meta = shell.meta
3303 3243 disp_formatter = self.shell.display_formatter
3304 3244 ptformatter = disp_formatter.formatters['text/plain']
3305 3245 # dstore is a data store kept in the instance metadata bag to track any
3306 3246 # changes we make, so we can undo them later.
3307 3247 dstore = meta.setdefault('doctest_mode',Struct())
3308 3248 save_dstore = dstore.setdefault
3309 3249
3310 3250 # save a few values we'll need to recover later
3311 3251 mode = save_dstore('mode',False)
3312 3252 save_dstore('rc_pprint',ptformatter.pprint)
3313 3253 save_dstore('xmode',shell.InteractiveTB.mode)
3314 3254 save_dstore('rc_separate_out',shell.separate_out)
3315 3255 save_dstore('rc_separate_out2',shell.separate_out2)
3316 3256 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3317 3257 save_dstore('rc_separate_in',shell.separate_in)
3318 3258 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
3319 3259
3320 3260 if mode == False:
3321 3261 # turn on
3322 3262 oc.prompt1.p_template = '>>> '
3323 3263 oc.prompt2.p_template = '... '
3324 3264 oc.prompt_out.p_template = ''
3325 3265
3326 3266 # Prompt separators like plain python
3327 3267 oc.input_sep = oc.prompt1.sep = ''
3328 3268 oc.output_sep = ''
3329 3269 oc.output_sep2 = ''
3330 3270
3331 3271 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3332 3272 oc.prompt_out.pad_left = False
3333 3273
3334 3274 ptformatter.pprint = False
3335 3275 disp_formatter.plain_text_only = True
3336 3276
3337 3277 shell.magic_xmode('Plain')
3338 3278 else:
3339 3279 # turn off
3340 3280 oc.prompt1.p_template = shell.prompt_in1
3341 3281 oc.prompt2.p_template = shell.prompt_in2
3342 3282 oc.prompt_out.p_template = shell.prompt_out
3343 3283
3344 3284 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3345 3285
3346 3286 oc.output_sep = dstore.rc_separate_out
3347 3287 oc.output_sep2 = dstore.rc_separate_out2
3348 3288
3349 3289 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3350 3290 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3351 3291
3352 3292 ptformatter.pprint = dstore.rc_pprint
3353 3293 disp_formatter.plain_text_only = dstore.rc_plain_text_only
3354 3294
3355 3295 shell.magic_xmode(dstore.xmode)
3356 3296
3357 3297 # Store new mode and inform
3358 3298 dstore.mode = bool(1-int(mode))
3359 3299 mode_label = ['OFF','ON'][dstore.mode]
3360 3300 print 'Doctest mode is:', mode_label
3361 3301
3362 3302 def magic_gui(self, parameter_s=''):
3363 3303 """Enable or disable IPython GUI event loop integration.
3364 3304
3365 3305 %gui [GUINAME]
3366 3306
3367 3307 This magic replaces IPython's threaded shells that were activated
3368 3308 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3369 3309 can now be enabled, disabled and changed at runtime and keyboard
3370 3310 interrupts should work without any problems. The following toolkits
3371 3311 are supported: wxPython, PyQt4, PyGTK, and Tk::
3372 3312
3373 3313 %gui wx # enable wxPython event loop integration
3374 3314 %gui qt4|qt # enable PyQt4 event loop integration
3375 3315 %gui gtk # enable PyGTK event loop integration
3376 3316 %gui tk # enable Tk event loop integration
3377 3317 %gui # disable all event loop integration
3378 3318
3379 3319 WARNING: after any of these has been called you can simply create
3380 3320 an application object, but DO NOT start the event loop yourself, as
3381 3321 we have already handled that.
3382 3322 """
3383 3323 from IPython.lib.inputhook import enable_gui
3384 3324 opts, arg = self.parse_options(parameter_s, '')
3385 3325 if arg=='': arg = None
3386 3326 return enable_gui(arg)
3387 3327
3388 3328 def magic_load_ext(self, module_str):
3389 3329 """Load an IPython extension by its module name."""
3390 3330 return self.extension_manager.load_extension(module_str)
3391 3331
3392 3332 def magic_unload_ext(self, module_str):
3393 3333 """Unload an IPython extension by its module name."""
3394 3334 self.extension_manager.unload_extension(module_str)
3395 3335
3396 3336 def magic_reload_ext(self, module_str):
3397 3337 """Reload an IPython extension by its module name."""
3398 3338 self.extension_manager.reload_extension(module_str)
3399 3339
3400 3340 @skip_doctest
3401 3341 def magic_install_profiles(self, s):
3402 3342 """Install the default IPython profiles into the .ipython dir.
3403 3343
3404 3344 If the default profiles have already been installed, they will not
3405 3345 be overwritten. You can force overwriting them by using the ``-o``
3406 3346 option::
3407 3347
3408 3348 In [1]: %install_profiles -o
3409 3349 """
3410 3350 if '-o' in s:
3411 3351 overwrite = True
3412 3352 else:
3413 3353 overwrite = False
3414 3354 from IPython.config import profile
3415 3355 profile_dir = os.path.dirname(profile.__file__)
3416 3356 ipython_dir = self.ipython_dir
3417 3357 print "Installing profiles to: %s [overwrite=%s]"%(ipython_dir,overwrite)
3418 3358 for src in os.listdir(profile_dir):
3419 3359 if src.startswith('profile_'):
3420 3360 name = src.replace('profile_', '')
3421 3361 print " %s"%name
3422 3362 pd = ProfileDir.create_profile_dir_by_name(ipython_dir, name)
3423 3363 pd.copy_config_file('ipython_config.py', path=src,
3424 3364 overwrite=overwrite)
3425 3365
3426 3366 @skip_doctest
3427 3367 def magic_install_default_config(self, s):
3428 3368 """Install IPython's default config file into the .ipython dir.
3429 3369
3430 3370 If the default config file (:file:`ipython_config.py`) is already
3431 3371 installed, it will not be overwritten. You can force overwriting
3432 3372 by using the ``-o`` option::
3433 3373
3434 3374 In [1]: %install_default_config
3435 3375 """
3436 3376 if '-o' in s:
3437 3377 overwrite = True
3438 3378 else:
3439 3379 overwrite = False
3440 3380 pd = self.shell.profile_dir
3441 3381 print "Installing default config file in: %s" % pd.location
3442 3382 pd.copy_config_file('ipython_config.py', overwrite=overwrite)
3443 3383
3444 3384 # Pylab support: simple wrappers that activate pylab, load gui input
3445 3385 # handling and modify slightly %run
3446 3386
3447 3387 @skip_doctest
3448 3388 def _pylab_magic_run(self, parameter_s=''):
3449 3389 Magic.magic_run(self, parameter_s,
3450 3390 runner=mpl_runner(self.shell.safe_execfile))
3451 3391
3452 3392 _pylab_magic_run.__doc__ = magic_run.__doc__
3453 3393
3454 3394 @skip_doctest
3455 3395 def magic_pylab(self, s):
3456 3396 """Load numpy and matplotlib to work interactively.
3457 3397
3458 3398 %pylab [GUINAME]
3459 3399
3460 3400 This function lets you activate pylab (matplotlib, numpy and
3461 3401 interactive support) at any point during an IPython session.
3462 3402
3463 3403 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3464 3404 pylab and mlab, as well as all names from numpy and pylab.
3465 3405
3466 3406 If you are using the inline matplotlib backend for embedded figures,
3467 3407 you can adjust its behavior via the %config magic::
3468 3408
3469 3409 # enable SVG figures, necessary for SVG+XHTML export in the qtconsole
3470 3410 In [1]: %config InlineBackend.figure_format = 'svg'
3471 3411
3472 3412 # change the behavior of closing all figures at the end of each
3473 3413 # execution (cell), or allowing reuse of active figures across
3474 3414 # cells:
3475 3415 In [2]: %config InlineBackend.close_figures = False
3476 3416
3477 3417 Parameters
3478 3418 ----------
3479 3419 guiname : optional
3480 3420 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk', 'osx' or
3481 3421 'tk'). If given, the corresponding Matplotlib backend is used,
3482 3422 otherwise matplotlib's default (which you can override in your
3483 3423 matplotlib config file) is used.
3484 3424
3485 3425 Examples
3486 3426 --------
3487 3427 In this case, where the MPL default is TkAgg::
3488 3428
3489 3429 In [2]: %pylab
3490 3430
3491 3431 Welcome to pylab, a matplotlib-based Python environment.
3492 3432 Backend in use: TkAgg
3493 3433 For more information, type 'help(pylab)'.
3494 3434
3495 3435 But you can explicitly request a different backend::
3496 3436
3497 3437 In [3]: %pylab qt
3498 3438
3499 3439 Welcome to pylab, a matplotlib-based Python environment.
3500 3440 Backend in use: Qt4Agg
3501 3441 For more information, type 'help(pylab)'.
3502 3442 """
3503 3443
3504 3444 if Application.initialized():
3505 3445 app = Application.instance()
3506 3446 try:
3507 3447 import_all_status = app.pylab_import_all
3508 3448 except AttributeError:
3509 3449 import_all_status = True
3510 3450 else:
3511 3451 import_all_status = True
3512 3452
3513 3453 self.shell.enable_pylab(s,import_all=import_all_status)
3514 3454
3515 3455 def magic_tb(self, s):
3516 3456 """Print the last traceback with the currently active exception mode.
3517 3457
3518 3458 See %xmode for changing exception reporting modes."""
3519 3459 self.shell.showtraceback()
3520 3460
3521 3461 @skip_doctest
3522 3462 def magic_precision(self, s=''):
3523 3463 """Set floating point precision for pretty printing.
3524 3464
3525 3465 Can set either integer precision or a format string.
3526 3466
3527 3467 If numpy has been imported and precision is an int,
3528 3468 numpy display precision will also be set, via ``numpy.set_printoptions``.
3529 3469
3530 3470 If no argument is given, defaults will be restored.
3531 3471
3532 3472 Examples
3533 3473 --------
3534 3474 ::
3535 3475
3536 3476 In [1]: from math import pi
3537 3477
3538 3478 In [2]: %precision 3
3539 3479 Out[2]: u'%.3f'
3540 3480
3541 3481 In [3]: pi
3542 3482 Out[3]: 3.142
3543 3483
3544 3484 In [4]: %precision %i
3545 3485 Out[4]: u'%i'
3546 3486
3547 3487 In [5]: pi
3548 3488 Out[5]: 3
3549 3489
3550 3490 In [6]: %precision %e
3551 3491 Out[6]: u'%e'
3552 3492
3553 3493 In [7]: pi**10
3554 3494 Out[7]: 9.364805e+04
3555 3495
3556 3496 In [8]: %precision
3557 3497 Out[8]: u'%r'
3558 3498
3559 3499 In [9]: pi**10
3560 3500 Out[9]: 93648.047476082982
3561 3501
3562 3502 """
3563 3503
3564 3504 ptformatter = self.shell.display_formatter.formatters['text/plain']
3565 3505 ptformatter.float_precision = s
3566 3506 return ptformatter.float_format
3567 3507
3568 3508
3569 3509 @magic_arguments.magic_arguments()
3570 3510 @magic_arguments.argument(
3571 3511 '-e', '--export', action='store_true', default=False,
3572 3512 help='Export IPython history as a notebook. The filename argument '
3573 3513 'is used to specify the notebook name and format. For example '
3574 3514 'a filename of notebook.ipynb will result in a notebook name '
3575 3515 'of "notebook" and a format of "xml". Likewise using a ".json" '
3576 3516 'or ".py" file extension will write the notebook in the json '
3577 3517 'or py formats.'
3578 3518 )
3579 3519 @magic_arguments.argument(
3580 3520 '-f', '--format',
3581 3521 help='Convert an existing IPython notebook to a new format. This option '
3582 3522 'specifies the new format and can have the values: xml, json, py. '
3583 3523 'The target filename is choosen automatically based on the new '
3584 3524 'format. The filename argument gives the name of the source file.'
3585 3525 )
3586 3526 @magic_arguments.argument(
3587 3527 'filename', type=unicode,
3588 3528 help='Notebook name or filename'
3589 3529 )
3590 3530 def magic_notebook(self, s):
3591 3531 """Export and convert IPython notebooks.
3592 3532
3593 3533 This function can export the current IPython history to a notebook file
3594 3534 or can convert an existing notebook file into a different format. For
3595 3535 example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb".
3596 3536 To export the history to "foo.py" do "%notebook -e foo.py". To convert
3597 3537 "foo.ipynb" to "foo.json" do "%notebook -f json foo.ipynb". Possible
3598 3538 formats include (json/ipynb, py).
3599 3539 """
3600 3540 args = magic_arguments.parse_argstring(self.magic_notebook, s)
3601 3541
3602 3542 from IPython.nbformat import current
3603 3543 args.filename = unquote_filename(args.filename)
3604 3544 if args.export:
3605 3545 fname, name, format = current.parse_filename(args.filename)
3606 3546 cells = []
3607 3547 hist = list(self.history_manager.get_range())
3608 3548 for session, prompt_number, input in hist[:-1]:
3609 3549 cells.append(current.new_code_cell(prompt_number=prompt_number, input=input))
3610 3550 worksheet = current.new_worksheet(cells=cells)
3611 3551 nb = current.new_notebook(name=name,worksheets=[worksheet])
3612 3552 with open(fname, 'w') as f:
3613 3553 current.write(nb, f, format);
3614 3554 elif args.format is not None:
3615 3555 old_fname, old_name, old_format = current.parse_filename(args.filename)
3616 3556 new_format = args.format
3617 3557 if new_format == u'xml':
3618 3558 raise ValueError('Notebooks cannot be written as xml.')
3619 3559 elif new_format == u'ipynb' or new_format == u'json':
3620 3560 new_fname = old_name + u'.ipynb'
3621 3561 new_format = u'json'
3622 3562 elif new_format == u'py':
3623 3563 new_fname = old_name + u'.py'
3624 3564 else:
3625 3565 raise ValueError('Invalid notebook format: %s' % new_format)
3626 3566 with open(old_fname, 'r') as f:
3627 3567 s = f.read()
3628 3568 try:
3629 3569 nb = current.reads(s, old_format)
3630 3570 except:
3631 3571 nb = current.reads(s, u'xml')
3632 3572 with open(new_fname, 'w') as f:
3633 3573 current.write(nb, f, new_format)
3634 3574
3635 3575 def magic_config(self, s):
3636 3576 """configure IPython
3637 3577
3638 3578 %config Class[.trait=value]
3639 3579
3640 3580 This magic exposes most of the IPython config system. Any
3641 3581 Configurable class should be able to be configured with the simple
3642 3582 line::
3643 3583
3644 3584 %config Class.trait=value
3645 3585
3646 3586 Where `value` will be resolved in the user's namespace, if it is an
3647 3587 expression or variable name.
3648 3588
3649 3589 Examples
3650 3590 --------
3651 3591
3652 3592 To see what classes are availabe for config, pass no arguments::
3653 3593
3654 3594 In [1]: %config
3655 3595 Available objects for config:
3656 3596 TerminalInteractiveShell
3657 3597 HistoryManager
3658 3598 PrefilterManager
3659 3599 AliasManager
3660 3600 IPCompleter
3661 3601 DisplayFormatter
3662 3602
3663 3603 To view what is configurable on a given class, just pass the class name::
3664 3604
3665 3605 In [2]: %config IPCompleter
3666 3606 IPCompleter options
3667 3607 -----------------
3668 3608 IPCompleter.omit__names=<Enum>
3669 3609 Current: 2
3670 3610 Choices: (0, 1, 2)
3671 3611 Instruct the completer to omit private method names
3672 3612 Specifically, when completing on ``object.<tab>``.
3673 3613 When 2 [default]: all names that start with '_' will be excluded.
3674 3614 When 1: all 'magic' names (``__foo__``) will be excluded.
3675 3615 When 0: nothing will be excluded.
3676 3616 IPCompleter.merge_completions=<CBool>
3677 3617 Current: True
3678 3618 Whether to merge completion results into a single list
3679 3619 If False, only the completion results from the first non-empty completer
3680 3620 will be returned.
3681 3621 IPCompleter.greedy=<CBool>
3682 3622 Current: False
3683 3623 Activate greedy completion
3684 3624 This will enable completion on elements of lists, results of function calls,
3685 3625 etc., but can be unsafe because the code is actually evaluated on TAB.
3686 3626
3687 3627 but the real use is in setting values::
3688 3628
3689 3629 In [3]: %config IPCompleter.greedy = True
3690 3630
3691 3631 and these values are read from the user_ns if they are variables::
3692 3632
3693 3633 In [4]: feeling_greedy=False
3694 3634
3695 3635 In [5]: %config IPCompleter.greedy = feeling_greedy
3696 3636
3697 3637 """
3698 3638 from IPython.config.loader import Config
3699 3639 # some IPython objects are Configurable, but do not yet have
3700 3640 # any configurable traits. Exclude them from the effects of
3701 3641 # this magic, as their presence is just noise:
3702 3642 configurables = [ c for c in self.configurables if c.__class__.class_traits(config=True) ]
3703 3643 classnames = [ c.__class__.__name__ for c in configurables ]
3704 3644
3705 3645 line = s.strip()
3706 3646 if not line:
3707 3647 # print available configurable names
3708 3648 print "Available objects for config:"
3709 3649 for name in classnames:
3710 3650 print " ", name
3711 3651 return
3712 3652 elif line in classnames:
3713 3653 # `%config TerminalInteractiveShell` will print trait info for
3714 3654 # TerminalInteractiveShell
3715 3655 c = configurables[classnames.index(line)]
3716 3656 cls = c.__class__
3717 3657 help = cls.class_get_help(c)
3718 3658 # strip leading '--' from cl-args:
3719 3659 help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
3720 3660 print help
3721 3661 return
3722 3662 elif '=' not in line:
3723 3663 raise UsageError("Invalid config statement: %r, should be Class.trait = value" % line)
3724 3664
3725 3665
3726 3666 # otherwise, assume we are setting configurables.
3727 3667 # leave quotes on args when splitting, because we want
3728 3668 # unquoted args to eval in user_ns
3729 3669 cfg = Config()
3730 3670 exec "cfg."+line in locals(), self.user_ns
3731 3671
3732 3672 for configurable in configurables:
3733 3673 try:
3734 3674 configurable.update_config(cfg)
3735 3675 except Exception as e:
3736 3676 error(e)
3737 3677
3738 3678 # end Magic
@@ -1,462 +1,463 b''
1 1 """Tests for various magic functions.
2 2
3 3 Needs to be run by nose (to make ipython session available).
4 4 """
5 5 from __future__ import absolute_import
6 6
7 7 #-----------------------------------------------------------------------------
8 8 # Imports
9 9 #-----------------------------------------------------------------------------
10 10
11 11 import os
12 12 import sys
13 13 import tempfile
14 14 import types
15 15 from StringIO import StringIO
16 16
17 17 import nose.tools as nt
18 18
19 19 from IPython.utils.path import get_long_path_name
20 20 from IPython.testing import decorators as dec
21 21 from IPython.testing import tools as tt
22 22 from IPython.utils import py3compat
23 23
24 24 #-----------------------------------------------------------------------------
25 25 # Test functions begin
26 26 #-----------------------------------------------------------------------------
27 27 def test_rehashx():
28 28 # clear up everything
29 29 _ip = get_ipython()
30 30 _ip.alias_manager.alias_table.clear()
31 31 del _ip.db['syscmdlist']
32 32
33 33 _ip.magic('rehashx')
34 34 # Practically ALL ipython development systems will have more than 10 aliases
35 35
36 36 yield (nt.assert_true, len(_ip.alias_manager.alias_table) > 10)
37 37 for key, val in _ip.alias_manager.alias_table.iteritems():
38 38 # we must strip dots from alias names
39 39 nt.assert_true('.' not in key)
40 40
41 41 # rehashx must fill up syscmdlist
42 42 scoms = _ip.db['syscmdlist']
43 43 yield (nt.assert_true, len(scoms) > 10)
44 44
45 45
46 46 def test_magic_parse_options():
47 47 """Test that we don't mangle paths when parsing magic options."""
48 48 ip = get_ipython()
49 49 path = 'c:\\x'
50 50 opts = ip.parse_options('-f %s' % path,'f:')[0]
51 51 # argv splitting is os-dependent
52 52 if os.name == 'posix':
53 53 expected = 'c:x'
54 54 else:
55 55 expected = path
56 56 nt.assert_equals(opts['f'], expected)
57 57
58 58
59 59 @dec.skip_without('sqlite3')
60 60 def doctest_hist_f():
61 61 """Test %hist -f with temporary filename.
62 62
63 63 In [9]: import tempfile
64 64
65 65 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
66 66
67 67 In [11]: %hist -nl -f $tfile 3
68 68
69 69 In [13]: import os; os.unlink(tfile)
70 70 """
71 71
72 72
73 73 @dec.skip_without('sqlite3')
74 74 def doctest_hist_r():
75 75 """Test %hist -r
76 76
77 77 XXX - This test is not recording the output correctly. For some reason, in
78 78 testing mode the raw history isn't getting populated. No idea why.
79 79 Disabling the output checking for now, though at least we do run it.
80 80
81 81 In [1]: 'hist' in _ip.lsmagic()
82 82 Out[1]: True
83 83
84 84 In [2]: x=1
85 85
86 86 In [3]: %hist -rl 2
87 87 x=1 # random
88 88 %hist -r 2
89 89 """
90 90
91 91
92 92 @dec.skip_without('sqlite3')
93 93 def doctest_hist_op():
94 94 """Test %hist -op
95 95
96 96 In [1]: class b(float):
97 97 ...: pass
98 98 ...:
99 99
100 100 In [2]: class s(object):
101 101 ...: def __str__(self):
102 102 ...: return 's'
103 103 ...:
104 104
105 105 In [3]:
106 106
107 107 In [4]: class r(b):
108 108 ...: def __repr__(self):
109 109 ...: return 'r'
110 110 ...:
111 111
112 112 In [5]: class sr(s,r): pass
113 113 ...:
114 114
115 115 In [6]:
116 116
117 117 In [7]: bb=b()
118 118
119 119 In [8]: ss=s()
120 120
121 121 In [9]: rr=r()
122 122
123 123 In [10]: ssrr=sr()
124 124
125 125 In [11]: 4.5
126 126 Out[11]: 4.5
127 127
128 128 In [12]: str(ss)
129 129 Out[12]: 's'
130 130
131 131 In [13]:
132 132
133 133 In [14]: %hist -op
134 134 >>> class b:
135 135 ... pass
136 136 ...
137 137 >>> class s(b):
138 138 ... def __str__(self):
139 139 ... return 's'
140 140 ...
141 141 >>>
142 142 >>> class r(b):
143 143 ... def __repr__(self):
144 144 ... return 'r'
145 145 ...
146 146 >>> class sr(s,r): pass
147 147 >>>
148 148 >>> bb=b()
149 149 >>> ss=s()
150 150 >>> rr=r()
151 151 >>> ssrr=sr()
152 152 >>> 4.5
153 153 4.5
154 154 >>> str(ss)
155 155 's'
156 156 >>>
157 157 """
158 158
159 159
160 160 @dec.skip_without('sqlite3')
161 161 def test_macro():
162 162 ip = get_ipython()
163 163 ip.history_manager.reset() # Clear any existing history.
164 164 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
165 165 for i, cmd in enumerate(cmds, start=1):
166 166 ip.history_manager.store_inputs(i, cmd)
167 167 ip.magic("macro test 1-3")
168 168 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
169 169
170 170 # List macros.
171 171 assert "test" in ip.magic("macro")
172 172
173 173
174 174 @dec.skip_without('sqlite3')
175 175 def test_macro_run():
176 176 """Test that we can run a multi-line macro successfully."""
177 177 ip = get_ipython()
178 178 ip.history_manager.reset()
179 179 cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"),
180 180 "%macro test 2-3"]
181 181 for cmd in cmds:
182 182 ip.run_cell(cmd, store_history=True)
183 183 nt.assert_equal(ip.user_ns["test"].value,
184 184 py3compat.doctest_refactor_print("a+=1\nprint a\n"))
185 185 with tt.AssertPrints("12"):
186 186 ip.run_cell("test")
187 187 with tt.AssertPrints("13"):
188 188 ip.run_cell("test")
189 189
190 190
191 191 # XXX failing for now, until we get clearcmd out of quarantine. But we should
192 192 # fix this and revert the skip to happen only if numpy is not around.
193 193 #@dec.skipif_not_numpy
194 194 @dec.skip_known_failure
195 195 def test_numpy_clear_array_undec():
196 196 from IPython.extensions import clearcmd
197 197
198 198 _ip.ex('import numpy as np')
199 199 _ip.ex('a = np.empty(2)')
200 200 yield (nt.assert_true, 'a' in _ip.user_ns)
201 201 _ip.magic('clear array')
202 202 yield (nt.assert_false, 'a' in _ip.user_ns)
203 203
204 204
205 205 # Multiple tests for clipboard pasting
206 206 @dec.parametric
207 207 def test_paste():
208 208 _ip = get_ipython()
209 209 def paste(txt, flags='-q'):
210 210 """Paste input text, by default in quiet mode"""
211 211 hooks.clipboard_get = lambda : txt
212 212 _ip.magic('paste '+flags)
213 213
214 214 # Inject fake clipboard hook but save original so we can restore it later
215 215 hooks = _ip.hooks
216 216 user_ns = _ip.user_ns
217 217 original_clip = hooks.clipboard_get
218 218
219 219 try:
220 220 # Run tests with fake clipboard function
221 221 user_ns.pop('x', None)
222 222 paste('x=1')
223 223 yield nt.assert_equal(user_ns['x'], 1)
224 224
225 225 user_ns.pop('x', None)
226 226 paste('>>> x=2')
227 227 yield nt.assert_equal(user_ns['x'], 2)
228 228
229 229 paste("""
230 230 >>> x = [1,2,3]
231 231 >>> y = []
232 232 >>> for i in x:
233 233 ... y.append(i**2)
234 234 ...
235 235 """)
236 236 yield nt.assert_equal(user_ns['x'], [1,2,3])
237 237 yield nt.assert_equal(user_ns['y'], [1,4,9])
238 238
239 239 # Now, test that paste -r works
240 240 user_ns.pop('x', None)
241 241 yield nt.assert_false('x' in user_ns)
242 242 _ip.magic('paste -r')
243 243 yield nt.assert_equal(user_ns['x'], [1,2,3])
244 244
245 245 # Also test paste echoing, by temporarily faking the writer
246 246 w = StringIO()
247 247 writer = _ip.write
248 248 _ip.write = w.write
249 249 code = """
250 250 a = 100
251 251 b = 200"""
252 252 try:
253 253 paste(code,'')
254 254 out = w.getvalue()
255 255 finally:
256 256 _ip.write = writer
257 257 yield nt.assert_equal(user_ns['a'], 100)
258 258 yield nt.assert_equal(user_ns['b'], 200)
259 259 yield nt.assert_equal(out, code+"\n## -- End pasted text --\n")
260 260
261 261 finally:
262 262 # Restore original hook
263 263 hooks.clipboard_get = original_clip
264 264
265 265
266 266 def test_time():
267 267 _ip.magic('time None')
268 268
269 269
270 270 @py3compat.doctest_refactor_print
271 271 def doctest_time():
272 272 """
273 273 In [10]: %time None
274 274 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
275 275 Wall time: 0.00 s
276 276
277 277 In [11]: def f(kmjy):
278 278 ....: %time print 2*kmjy
279 279
280 280 In [12]: f(3)
281 281 6
282 282 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
283 283 Wall time: 0.00 s
284 284 """
285 285
286 286
287 287 def test_doctest_mode():
288 288 "Toggle doctest_mode twice, it should be a no-op and run without error"
289 289 _ip.magic('doctest_mode')
290 290 _ip.magic('doctest_mode')
291 291
292 292
293 293 def test_parse_options():
294 294 """Tests for basic options parsing in magics."""
295 295 # These are only the most minimal of tests, more should be added later. At
296 296 # the very least we check that basic text/unicode calls work OK.
297 297 nt.assert_equal(_ip.parse_options('foo', '')[1], 'foo')
298 298 nt.assert_equal(_ip.parse_options(u'foo', '')[1], u'foo')
299 299
300 300
301 301 def test_dirops():
302 302 """Test various directory handling operations."""
303 303 # curpath = lambda :os.path.splitdrive(os.getcwdu())[1].replace('\\','/')
304 304 curpath = os.getcwdu
305 305 startdir = os.getcwdu()
306 306 ipdir = _ip.ipython_dir
307 307 try:
308 308 _ip.magic('cd "%s"' % ipdir)
309 309 nt.assert_equal(curpath(), ipdir)
310 310 _ip.magic('cd -')
311 311 nt.assert_equal(curpath(), startdir)
312 312 _ip.magic('pushd "%s"' % ipdir)
313 313 nt.assert_equal(curpath(), ipdir)
314 314 _ip.magic('popd')
315 315 nt.assert_equal(curpath(), startdir)
316 316 finally:
317 317 os.chdir(startdir)
318 318
319 319
320 320 def check_cpaste(code, should_fail=False):
321 321 """Execute code via 'cpaste' and ensure it was executed, unless
322 322 should_fail is set.
323 323 """
324 324 _ip.user_ns['code_ran'] = False
325 325
326 326 src = StringIO()
327 327 if not hasattr(src, 'encoding'):
328 328 # IPython expects stdin to have an encoding attribute
329 329 src.encoding = None
330 330 src.write('\n')
331 331 src.write(code)
332 332 src.write('\n--\n')
333 333 src.seek(0)
334 334
335 335 stdin_save = sys.stdin
336 336 sys.stdin = src
337 337
338 338 try:
339 339 context = tt.AssertPrints if should_fail else tt.AssertNotPrints
340 340 with context("Traceback (most recent call last)"):
341 341 _ip.magic('cpaste')
342 342
343 343 if not should_fail:
344 344 assert _ip.user_ns['code_ran']
345 345 finally:
346 346 sys.stdin = stdin_save
347 347
348 348
349 349 def test_cpaste():
350 350 """Test cpaste magic"""
351 351
352 352 def run():
353 353 """Marker function: sets a flag when executed.
354 354 """
355 355 _ip.user_ns['code_ran'] = True
356 356 return 'run' # return string so '+ run()' doesn't result in success
357 357
358 tests = {'pass': ["> > > run()",
359 ">>> > run()",
360 "+++ run()",
361 "++ run()",
362 " >>> run()"],
363
364 'fail': ["+ + run()",
358 tests = {'pass': ["run()",
359 "In [1]: run()",
360 "In [1]: if 1:\n ...: run()",
361 ">>> run()",
362 " >>> run()",
363 ],
364
365 'fail': ["1 + run()",
365 366 " ++ run()"]}
366 367
367 368 _ip.user_ns['run'] = run
368 369
369 370 for code in tests['pass']:
370 371 check_cpaste(code)
371 372
372 373 for code in tests['fail']:
373 374 check_cpaste(code, should_fail=True)
374 375
375 376 def test_xmode():
376 377 # Calling xmode three times should be a no-op
377 378 xmode = _ip.InteractiveTB.mode
378 379 for i in range(3):
379 380 _ip.magic("xmode")
380 381 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
381 382
382 383 def test_reset_hard():
383 384 monitor = []
384 385 class A(object):
385 386 def __del__(self):
386 387 monitor.append(1)
387 388 def __repr__(self):
388 389 return "<A instance>"
389 390
390 391 _ip.user_ns["a"] = A()
391 392 _ip.run_cell("a")
392 393
393 394 nt.assert_equal(monitor, [])
394 395 _ip.magic_reset("-f")
395 396 nt.assert_equal(monitor, [1])
396 397
397 398 class TestXdel(tt.TempFileMixin):
398 399 def test_xdel(self):
399 400 """Test that references from %run are cleared by xdel."""
400 401 src = ("class A(object):\n"
401 402 " monitor = []\n"
402 403 " def __del__(self):\n"
403 404 " self.monitor.append(1)\n"
404 405 "a = A()\n")
405 406 self.mktmp(src)
406 407 # %run creates some hidden references...
407 408 _ip.magic("run %s" % self.fname)
408 409 # ... as does the displayhook.
409 410 _ip.run_cell("a")
410 411
411 412 monitor = _ip.user_ns["A"].monitor
412 413 nt.assert_equal(monitor, [])
413 414
414 415 _ip.magic("xdel a")
415 416
416 417 # Check that a's __del__ method has been called.
417 418 nt.assert_equal(monitor, [1])
418 419
419 420 def doctest_who():
420 421 """doctest for %who
421 422
422 423 In [1]: %reset -f
423 424
424 425 In [2]: alpha = 123
425 426
426 427 In [3]: beta = 'beta'
427 428
428 429 In [4]: %who int
429 430 alpha
430 431
431 432 In [5]: %who str
432 433 beta
433 434
434 435 In [6]: %whos
435 436 Variable Type Data/Info
436 437 ----------------------------
437 438 alpha int 123
438 439 beta str beta
439 440
440 441 In [7]: %who_ls
441 442 Out[7]: ['alpha', 'beta']
442 443 """
443 444
444 445 @py3compat.u_format
445 446 def doctest_precision():
446 447 """doctest for %precision
447 448
448 449 In [1]: f = get_ipython().shell.display_formatter.formatters['text/plain']
449 450
450 451 In [2]: %precision 5
451 452 Out[2]: {u}'%.5f'
452 453
453 454 In [3]: f.float_format
454 455 Out[3]: {u}'%.5f'
455 456
456 457 In [4]: %precision %e
457 458 Out[4]: {u}'%e'
458 459
459 460 In [5]: f(3.1415927)
460 461 Out[5]: {u}'3.141593e+00'
461 462 """
462 463
@@ -1,646 +1,686 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Subclass of InteractiveShell for terminal based frontends."""
3 3
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 7 # Copyright (C) 2008-2011 The IPython Development Team
8 8 #
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16
17 17 import __builtin__
18 18 import bdb
19 19 import os
20 20 import re
21 21 import sys
22 import textwrap
22 23
23 24 try:
24 25 from contextlib import nested
25 26 except:
26 27 from IPython.utils.nested_context import nested
27 28
28 29 from IPython.core.error import TryNext
29 30 from IPython.core.usage import interactive_usage, default_banner
30 31 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
31 32 from IPython.lib.inputhook import enable_gui
32 33 from IPython.lib.pylabtools import pylab_activate
33 34 from IPython.testing.skipdoctest import skip_doctest
34 35 from IPython.utils import py3compat
35 36 from IPython.utils.terminal import toggle_set_term_title, set_term_title
36 37 from IPython.utils.process import abbrev_cwd
37 38 from IPython.utils.warn import warn, error
38 from IPython.utils.text import num_ini_spaces
39 from IPython.utils.text import num_ini_spaces, SList
39 40 from IPython.utils.traitlets import Integer, CBool, Unicode
40 41
41 42 #-----------------------------------------------------------------------------
42 43 # Utilities
43 44 #-----------------------------------------------------------------------------
44 45
45 46 def get_default_editor():
46 47 try:
47 48 ed = os.environ['EDITOR']
48 49 except KeyError:
49 50 if os.name == 'posix':
50 51 ed = 'vi' # the only one guaranteed to be there!
51 52 else:
52 53 ed = 'notepad' # same in Windows!
53 54 return ed
54 55
56
57 def get_pasted_lines(sentinel, input=raw_input):
58 """ Yield pasted lines until the user enters the given sentinel value.
59 """
60 print "Pasting code; enter '%s' alone on the line to stop or use Ctrl-D." \
61 % sentinel
62 while True:
63 try:
64 l = input(':')
65 if l == sentinel:
66 return
67 else:
68 yield l
69 except EOFError:
70 print '<EOF>'
71 return
72
73
74 def store_or_execute(shell, block, name):
75 """ Execute a block, or store it in a variable, per the user's request.
76 """
77 if name:
78 # If storing it for further editing, run the prefilter on it
79 shell.user_ns[name] = SList(shell.prefilter(block).splitlines())
80 print "Block assigned to '%s'" % name
81 else:
82 # For execution we just dedent it, as all other filtering is
83 # automatically applied by run_cell
84 b = textwrap.dedent(block)
85 shell.user_ns['pasted_block'] = b
86 shell.run_cell(b)
87
88
89 def rerun_pasted(shell):
90 """ Rerun a previously pasted command.
91 """
92 b = shell.user_ns.get('pasted_block')
93 if b is None:
94 raise UsageError('No previous pasted block available')
95 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
96 shell.run_cell(b)
97
55 98 #-----------------------------------------------------------------------------
56 99 # Main class
57 100 #-----------------------------------------------------------------------------
58 101
59 102 class TerminalInteractiveShell(InteractiveShell):
60 103
61 104 autoedit_syntax = CBool(False, config=True,
62 105 help="auto editing of files with syntax errors.")
63 106 banner = Unicode('')
64 107 banner1 = Unicode(default_banner, config=True,
65 108 help="""The part of the banner to be printed before the profile"""
66 109 )
67 110 banner2 = Unicode('', config=True,
68 111 help="""The part of the banner to be printed after the profile"""
69 112 )
70 113 confirm_exit = CBool(True, config=True,
71 114 help="""
72 115 Set to confirm when you try to exit IPython with an EOF (Control-D
73 116 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
74 117 you can force a direct exit without any confirmation.""",
75 118 )
76 119 # This display_banner only controls whether or not self.show_banner()
77 120 # is called when mainloop/interact are called. The default is False
78 121 # because for the terminal based application, the banner behavior
79 122 # is controlled by Global.display_banner, which IPythonApp looks at
80 123 # to determine if *it* should call show_banner() by hand or not.
81 124 display_banner = CBool(False) # This isn't configurable!
82 125 embedded = CBool(False)
83 126 embedded_active = CBool(False)
84 127 editor = Unicode(get_default_editor(), config=True,
85 128 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
86 129 )
87 130 pager = Unicode('less', config=True,
88 131 help="The shell program to be used for paging.")
89 132
90 133 screen_length = Integer(0, config=True,
91 134 help=
92 135 """Number of lines of your screen, used to control printing of very
93 136 long strings. Strings longer than this number of lines will be sent
94 137 through a pager instead of directly printed. The default value for
95 138 this is 0, which means IPython will auto-detect your screen size every
96 139 time it needs to print certain potentially long strings (this doesn't
97 140 change the behavior of the 'print' keyword, it's only triggered
98 141 internally). If for some reason this isn't working well (it needs
99 142 curses support), specify it yourself. Otherwise don't change the
100 143 default.""",
101 144 )
102 145 term_title = CBool(False, config=True,
103 146 help="Enable auto setting the terminal title."
104 147 )
105 148
106 149 def __init__(self, config=None, ipython_dir=None, profile_dir=None, user_ns=None,
107 150 user_global_ns=None, custom_exceptions=((),None),
108 151 usage=None, banner1=None, banner2=None,
109 152 display_banner=None):
110 153
111 154 super(TerminalInteractiveShell, self).__init__(
112 155 config=config, profile_dir=profile_dir, user_ns=user_ns,
113 156 user_global_ns=user_global_ns, custom_exceptions=custom_exceptions
114 157 )
115 158 # use os.system instead of utils.process.system by default,
116 159 # because piped system doesn't make sense in the Terminal:
117 160 self.system = self.system_raw
118 161
119 162 self.init_term_title()
120 163 self.init_usage(usage)
121 164 self.init_banner(banner1, banner2, display_banner)
122 165
123 166 #-------------------------------------------------------------------------
124 167 # Things related to the terminal
125 168 #-------------------------------------------------------------------------
126 169
127 170 @property
128 171 def usable_screen_length(self):
129 172 if self.screen_length == 0:
130 173 return 0
131 174 else:
132 175 num_lines_bot = self.separate_in.count('\n')+1
133 176 return self.screen_length - num_lines_bot
134 177
135 178 def init_term_title(self):
136 179 # Enable or disable the terminal title.
137 180 if self.term_title:
138 181 toggle_set_term_title(True)
139 182 set_term_title('IPython: ' + abbrev_cwd())
140 183 else:
141 184 toggle_set_term_title(False)
142 185
143 186 #-------------------------------------------------------------------------
144 187 # Things related to aliases
145 188 #-------------------------------------------------------------------------
146 189
147 190 def init_alias(self):
148 191 # The parent class defines aliases that can be safely used with any
149 192 # frontend.
150 193 super(TerminalInteractiveShell, self).init_alias()
151 194
152 195 # Now define aliases that only make sense on the terminal, because they
153 196 # need direct access to the console in a way that we can't emulate in
154 197 # GUI or web frontend
155 198 if os.name == 'posix':
156 199 aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'),
157 200 ('man', 'man')]
158 201 elif os.name == 'nt':
159 202 aliases = [('cls', 'cls')]
160 203
161 204
162 205 for name, cmd in aliases:
163 206 self.alias_manager.define_alias(name, cmd)
164 207
165 208 #-------------------------------------------------------------------------
166 209 # Things related to the banner and usage
167 210 #-------------------------------------------------------------------------
168 211
169 212 def _banner1_changed(self):
170 213 self.compute_banner()
171 214
172 215 def _banner2_changed(self):
173 216 self.compute_banner()
174 217
175 218 def _term_title_changed(self, name, new_value):
176 219 self.init_term_title()
177 220
178 221 def init_banner(self, banner1, banner2, display_banner):
179 222 if banner1 is not None:
180 223 self.banner1 = banner1
181 224 if banner2 is not None:
182 225 self.banner2 = banner2
183 226 if display_banner is not None:
184 227 self.display_banner = display_banner
185 228 self.compute_banner()
186 229
187 230 def show_banner(self, banner=None):
188 231 if banner is None:
189 232 banner = self.banner
190 233 self.write(banner)
191 234
192 235 def compute_banner(self):
193 236 self.banner = self.banner1
194 237 if self.profile and self.profile != 'default':
195 238 self.banner += '\nIPython profile: %s\n' % self.profile
196 239 if self.banner2:
197 240 self.banner += '\n' + self.banner2
198 241
199 242 def init_usage(self, usage=None):
200 243 if usage is None:
201 244 self.usage = interactive_usage
202 245 else:
203 246 self.usage = usage
204 247
205 248 #-------------------------------------------------------------------------
206 249 # Mainloop and code execution logic
207 250 #-------------------------------------------------------------------------
208 251
209 252 def mainloop(self, display_banner=None):
210 253 """Start the mainloop.
211 254
212 255 If an optional banner argument is given, it will override the
213 256 internally created default banner.
214 257 """
215 258
216 259 with nested(self.builtin_trap, self.display_trap):
217 260
218 261 while 1:
219 262 try:
220 263 self.interact(display_banner=display_banner)
221 264 #self.interact_with_readline()
222 265 # XXX for testing of a readline-decoupled repl loop, call
223 266 # interact_with_readline above
224 267 break
225 268 except KeyboardInterrupt:
226 269 # this should not be necessary, but KeyboardInterrupt
227 270 # handling seems rather unpredictable...
228 271 self.write("\nKeyboardInterrupt in interact()\n")
229 272
230 273 def _replace_rlhist_multiline(self, source_raw, hlen_before_cell):
231 274 """Store multiple lines as a single entry in history"""
232 275
233 276 # do nothing without readline or disabled multiline
234 277 if not self.has_readline or not self.multiline_history:
235 278 return hlen_before_cell
236 279
237 280 # windows rl has no remove_history_item
238 281 if not hasattr(self.readline, "remove_history_item"):
239 282 return hlen_before_cell
240 283
241 284 # skip empty cells
242 285 if not source_raw.rstrip():
243 286 return hlen_before_cell
244 287
245 288 # nothing changed do nothing, e.g. when rl removes consecutive dups
246 289 hlen = self.readline.get_current_history_length()
247 290 if hlen == hlen_before_cell:
248 291 return hlen_before_cell
249 292
250 293 for i in range(hlen - hlen_before_cell):
251 294 self.readline.remove_history_item(hlen - i - 1)
252 295 stdin_encoding = sys.stdin.encoding or "utf-8"
253 296 self.readline.add_history(py3compat.unicode_to_str(source_raw.rstrip(),
254 297 stdin_encoding))
255 298 return self.readline.get_current_history_length()
256 299
257 300 def interact(self, display_banner=None):
258 301 """Closely emulate the interactive Python console."""
259 302
260 303 # batch run -> do not interact
261 304 if self.exit_now:
262 305 return
263 306
264 307 if display_banner is None:
265 308 display_banner = self.display_banner
266 309
267 310 if isinstance(display_banner, basestring):
268 311 self.show_banner(display_banner)
269 312 elif display_banner:
270 313 self.show_banner()
271 314
272 315 more = False
273 316
274 317 # Mark activity in the builtins
275 318 __builtin__.__dict__['__IPYTHON__active'] += 1
276 319
277 320 if self.has_readline:
278 321 self.readline_startup_hook(self.pre_readline)
279 322 hlen_b4_cell = self.readline.get_current_history_length()
280 323 else:
281 324 hlen_b4_cell = 0
282 325 # exit_now is set by a call to %Exit or %Quit, through the
283 326 # ask_exit callback.
284 327
285 328 while not self.exit_now:
286 329 self.hooks.pre_prompt_hook()
287 330 if more:
288 331 try:
289 332 prompt = self.hooks.generate_prompt(True)
290 333 except:
291 334 self.showtraceback()
292 335 if self.autoindent:
293 336 self.rl_do_indent = True
294 337
295 338 else:
296 339 try:
297 340 prompt = self.hooks.generate_prompt(False)
298 341 except:
299 342 self.showtraceback()
300 343 try:
301 344 line = self.raw_input(prompt)
302 345 if self.exit_now:
303 346 # quick exit on sys.std[in|out] close
304 347 break
305 348 if self.autoindent:
306 349 self.rl_do_indent = False
307 350
308 351 except KeyboardInterrupt:
309 352 #double-guard against keyboardinterrupts during kbdint handling
310 353 try:
311 354 self.write('\nKeyboardInterrupt\n')
312 355 source_raw = self.input_splitter.source_raw_reset()[1]
313 356 hlen_b4_cell = \
314 357 self._replace_rlhist_multiline(source_raw, hlen_b4_cell)
315 358 more = False
316 359 except KeyboardInterrupt:
317 360 pass
318 361 except EOFError:
319 362 if self.autoindent:
320 363 self.rl_do_indent = False
321 364 if self.has_readline:
322 365 self.readline_startup_hook(None)
323 366 self.write('\n')
324 367 self.exit()
325 368 except bdb.BdbQuit:
326 369 warn('The Python debugger has exited with a BdbQuit exception.\n'
327 370 'Because of how pdb handles the stack, it is impossible\n'
328 371 'for IPython to properly format this particular exception.\n'
329 372 'IPython will resume normal operation.')
330 373 except:
331 374 # exceptions here are VERY RARE, but they can be triggered
332 375 # asynchronously by signal handlers, for example.
333 376 self.showtraceback()
334 377 else:
335 378 self.input_splitter.push(line)
336 379 more = self.input_splitter.push_accepts_more()
337 380 if (self.SyntaxTB.last_syntax_error and
338 381 self.autoedit_syntax):
339 382 self.edit_syntax_error()
340 383 if not more:
341 384 source_raw = self.input_splitter.source_raw_reset()[1]
342 385 self.run_cell(source_raw, store_history=True)
343 386 hlen_b4_cell = \
344 387 self._replace_rlhist_multiline(source_raw, hlen_b4_cell)
345 388
346 389 # We are off again...
347 390 __builtin__.__dict__['__IPYTHON__active'] -= 1
348 391
349 392 # Turn off the exit flag, so the mainloop can be restarted if desired
350 393 self.exit_now = False
351 394
352 395 def raw_input(self, prompt=''):
353 396 """Write a prompt and read a line.
354 397
355 398 The returned line does not include the trailing newline.
356 399 When the user enters the EOF key sequence, EOFError is raised.
357 400
358 401 Optional inputs:
359 402
360 403 - prompt(''): a string to be printed to prompt the user.
361 404
362 405 - continue_prompt(False): whether this line is the first one or a
363 406 continuation in a sequence of inputs.
364 407 """
365 408 # Code run by the user may have modified the readline completer state.
366 409 # We must ensure that our completer is back in place.
367 410
368 411 if self.has_readline:
369 412 self.set_readline_completer()
370 413
371 414 try:
372 415 line = py3compat.str_to_unicode(self.raw_input_original(prompt))
373 416 except ValueError:
374 417 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
375 418 " or sys.stdout.close()!\nExiting IPython!")
376 419 self.ask_exit()
377 420 return ""
378 421
379 422 # Try to be reasonably smart about not re-indenting pasted input more
380 423 # than necessary. We do this by trimming out the auto-indent initial
381 424 # spaces, if the user's actual input started itself with whitespace.
382 425 if self.autoindent:
383 426 if num_ini_spaces(line) > self.indent_current_nsp:
384 427 line = line[self.indent_current_nsp:]
385 428 self.indent_current_nsp = 0
386 429
387 430 return line
388 431
389 432 #-------------------------------------------------------------------------
390 433 # Methods to support auto-editing of SyntaxErrors.
391 434 #-------------------------------------------------------------------------
392 435
393 436 def edit_syntax_error(self):
394 437 """The bottom half of the syntax error handler called in the main loop.
395 438
396 439 Loop until syntax error is fixed or user cancels.
397 440 """
398 441
399 442 while self.SyntaxTB.last_syntax_error:
400 443 # copy and clear last_syntax_error
401 444 err = self.SyntaxTB.clear_err_state()
402 445 if not self._should_recompile(err):
403 446 return
404 447 try:
405 448 # may set last_syntax_error again if a SyntaxError is raised
406 449 self.safe_execfile(err.filename,self.user_ns)
407 450 except:
408 451 self.showtraceback()
409 452 else:
410 453 try:
411 454 f = file(err.filename)
412 455 try:
413 456 # This should be inside a display_trap block and I
414 457 # think it is.
415 458 sys.displayhook(f.read())
416 459 finally:
417 460 f.close()
418 461 except:
419 462 self.showtraceback()
420 463
421 464 def _should_recompile(self,e):
422 465 """Utility routine for edit_syntax_error"""
423 466
424 467 if e.filename in ('<ipython console>','<input>','<string>',
425 468 '<console>','<BackgroundJob compilation>',
426 469 None):
427 470
428 471 return False
429 472 try:
430 473 if (self.autoedit_syntax and
431 474 not self.ask_yes_no('Return to editor to correct syntax error? '
432 475 '[Y/n] ','y')):
433 476 return False
434 477 except EOFError:
435 478 return False
436 479
437 480 def int0(x):
438 481 try:
439 482 return int(x)
440 483 except TypeError:
441 484 return 0
442 485 # always pass integer line and offset values to editor hook
443 486 try:
444 487 self.hooks.fix_error_editor(e.filename,
445 488 int0(e.lineno),int0(e.offset),e.msg)
446 489 except TryNext:
447 490 warn('Could not open editor')
448 491 return False
449 492 return True
450 493
451 494 #-------------------------------------------------------------------------
452 495 # Things related to GUI support and pylab
453 496 #-------------------------------------------------------------------------
454 497
455 498 def enable_pylab(self, gui=None, import_all=True):
456 499 """Activate pylab support at runtime.
457 500
458 501 This turns on support for matplotlib, preloads into the interactive
459 502 namespace all of numpy and pylab, and configures IPython to correcdtly
460 503 interact with the GUI event loop. The GUI backend to be used can be
461 504 optionally selected with the optional :param:`gui` argument.
462 505
463 506 Parameters
464 507 ----------
465 508 gui : optional, string
466 509
467 510 If given, dictates the choice of matplotlib GUI backend to use
468 511 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
469 512 'gtk'), otherwise we use the default chosen by matplotlib (as
470 513 dictated by the matplotlib build-time options plus the user's
471 514 matplotlibrc configuration file).
472 515 """
473 516 # We want to prevent the loading of pylab to pollute the user's
474 517 # namespace as shown by the %who* magics, so we execute the activation
475 518 # code in an empty namespace, and we update *both* user_ns and
476 519 # user_ns_hidden with this information.
477 520 ns = {}
478 521 try:
479 522 gui = pylab_activate(ns, gui, import_all)
480 523 except KeyError:
481 524 error("Backend %r not supported" % gui)
482 525 return
483 526 self.user_ns.update(ns)
484 527 self.user_ns_hidden.update(ns)
485 528 # Now we must activate the gui pylab wants to use, and fix %run to take
486 529 # plot updates into account
487 530 enable_gui(gui)
488 531 self.magic_run = self._pylab_magic_run
489 532
490 533 #-------------------------------------------------------------------------
491 534 # Things related to exiting
492 535 #-------------------------------------------------------------------------
493 536
494 537 def ask_exit(self):
495 538 """ Ask the shell to exit. Can be overiden and used as a callback. """
496 539 self.exit_now = True
497 540
498 541 def exit(self):
499 542 """Handle interactive exit.
500 543
501 544 This method calls the ask_exit callback."""
502 545 if self.confirm_exit:
503 546 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
504 547 self.ask_exit()
505 548 else:
506 549 self.ask_exit()
507 550
508 551 #------------------------------------------------------------------------
509 552 # Magic overrides
510 553 #------------------------------------------------------------------------
511 554 # Once the base class stops inheriting from magic, this code needs to be
512 555 # moved into a separate machinery as well. For now, at least isolate here
513 556 # the magics which this class needs to implement differently from the base
514 557 # class, or that are unique to it.
515 558
516 559 def magic_autoindent(self, parameter_s = ''):
517 560 """Toggle autoindent on/off (if available)."""
518 561
519 562 self.shell.set_autoindent()
520 563 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
521 564
522 565 @skip_doctest
523 566 def magic_cpaste(self, parameter_s=''):
524 567 """Paste & execute a pre-formatted code block from clipboard.
525 568
526 You must terminate the block with '--' (two minus-signs) or Ctrl-D alone on the
527 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
528 is the new sentinel for this operation)
569 You must terminate the block with '--' (two minus-signs) or Ctrl-D
570 alone on the line. You can also provide your own sentinel with '%paste
571 -s %%' ('%%' is the new sentinel for this operation)
529 572
530 573 The block is dedented prior to execution to enable execution of method
531 574 definitions. '>' and '+' characters at the beginning of a line are
532 575 ignored, to allow pasting directly from e-mails, diff files and
533 576 doctests (the '...' continuation prompt is also stripped). The
534 577 executed block is also assigned to variable named 'pasted_block' for
535 578 later editing with '%edit pasted_block'.
536 579
537 580 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
538 581 This assigns the pasted block to variable 'foo' as string, without
539 582 dedenting or executing it (preceding >>> and + is still stripped)
540 583
541 584 '%cpaste -r' re-executes the block previously entered by cpaste.
542 585
543 586 Do not be alarmed by garbled output on Windows (it's a readline bug).
544 587 Just press enter and type -- (and press enter again) and the block
545 588 will be what was just pasted.
546 589
547 590 IPython statements (magics, shell escapes) are not supported (yet).
548 591
549 592 See also
550 593 --------
551 594 paste: automatically pull code from clipboard.
552 595
553 596 Examples
554 597 --------
555 598 ::
556 599
557 600 In [8]: %cpaste
558 601 Pasting code; enter '--' alone on the line to stop.
559 602 :>>> a = ["world!", "Hello"]
560 603 :>>> print " ".join(sorted(a))
561 604 :--
562 605 Hello world!
563 606 """
564 607
565 608 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
566 par = args.strip()
567 if opts.has_key('r'):
568 self._rerun_pasted()
609 name = args.strip()
610 if 'r' in opts:
611 rerun_pasted(self.shell)
569 612 return
570 613
571 614 sentinel = opts.get('s','--')
572
573 block = self._strip_pasted_lines_for_code(
574 self._get_pasted_lines(sentinel))
575
576 self._execute_block(block, par)
615 block = '\n'.join(get_pasted_lines(sentinel))
616 store_or_execute(self.shell, block, name)
577 617
578 618 def magic_paste(self, parameter_s=''):
579 619 """Paste & execute a pre-formatted code block from clipboard.
580 620
581 621 The text is pulled directly from the clipboard without user
582 622 intervention and printed back on the screen before execution (unless
583 623 the -q flag is given to force quiet mode).
584 624
585 625 The block is dedented prior to execution to enable execution of method
586 626 definitions. '>' and '+' characters at the beginning of a line are
587 627 ignored, to allow pasting directly from e-mails, diff files and
588 628 doctests (the '...' continuation prompt is also stripped). The
589 629 executed block is also assigned to variable named 'pasted_block' for
590 630 later editing with '%edit pasted_block'.
591 631
592 632 You can also pass a variable name as an argument, e.g. '%paste foo'.
593 633 This assigns the pasted block to variable 'foo' as string, without
594 634 dedenting or executing it (preceding >>> and + is still stripped)
595 635
596 636 Options
597 637 -------
598 638
599 639 -r: re-executes the block previously entered by cpaste.
600 640
601 641 -q: quiet mode: do not echo the pasted text back to the terminal.
602 642
603 643 IPython statements (magics, shell escapes) are not supported (yet).
604 644
605 645 See also
606 646 --------
607 647 cpaste: manually paste code into terminal until you mark its end.
608 648 """
609 649 opts,args = self.parse_options(parameter_s,'rq',mode='string')
610 par = args.strip()
611 if opts.has_key('r'):
612 self._rerun_pasted()
650 name = args.strip()
651 if 'r' in opts:
652 rerun_pasted(self.shell)
613 653 return
614 654 try:
615 655 text = self.shell.hooks.clipboard_get()
616 656 block = self._strip_pasted_lines_for_code(text.splitlines())
617 657 except TryNext as clipboard_exc:
618 658 message = getattr(clipboard_exc, 'args')
619 659 if message:
620 660 error(message[0])
621 661 else:
622 662 error('Could not get text from the clipboard.')
623 663 return
624 664
625 665 # By default, echo back to terminal unless quiet mode is requested
626 if not opts.has_key('q'):
666 if 'q' not in opts:
627 667 write = self.shell.write
628 668 write(self.shell.pycolorize(block))
629 669 if not block.endswith('\n'):
630 670 write('\n')
631 671 write("## -- End pasted text --\n")
632 672
633 self._execute_block(block, par)
673 store_or_execute(self.shell, block, name)
634 674
635 675 if sys.platform == 'win32':
636 676 def magic_cls(self, s):
637 677 """Clear screen.
638 678 """
639 679 os.system("cls")
640 680
641 681 def showindentationerror(self):
642 682 super(TerminalInteractiveShell, self).showindentationerror()
643 683 print("If you want to paste code into IPython, try the %paste magic function.")
644 684
645 685
646 686 InteractiveShellABC.register(TerminalInteractiveShell)
General Comments 0
You need to be logged in to leave comments. Login now