/IPyShell/IPython/Magic.py

http://editra-plugins.googlecode.com/ · Python · 3381 lines · 2923 code · 208 blank · 250 comment · 213 complexity · f05c5ae5bdacb4008a80cd1cee87f2da MD5 · raw file

Large files are truncated click here to view the full file

  1. # -*- coding: utf-8 -*-
  2. """Magic functions for InteractiveShell.
  3. $Id: Magic.py 645 2008-10-25 00:05:08Z CodyPrecord $"""
  4. #*****************************************************************************
  5. # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
  6. # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
  7. #
  8. # Distributed under the terms of the BSD License. The full license is in
  9. # the file COPYING, distributed as part of this software.
  10. #*****************************************************************************
  11. #****************************************************************************
  12. # Modules and globals
  13. from IPython import Release
  14. __author__ = '%s <%s>\n%s <%s>' % \
  15. ( Release.authors['Janko'] + Release.authors['Fernando'] )
  16. __license__ = Release.license
  17. # Python standard modules
  18. import __builtin__
  19. import bdb
  20. import inspect
  21. import os
  22. import pdb
  23. import pydoc
  24. import sys
  25. import re
  26. import tempfile
  27. import time
  28. import cPickle as pickle
  29. import textwrap
  30. from cStringIO import StringIO
  31. from getopt import getopt,GetoptError
  32. from pprint import pprint, pformat
  33. try:
  34. Set = set
  35. except NameError:
  36. from sets import Set
  37. # cProfile was added in Python2.5
  38. try:
  39. import cProfile as profile
  40. import pstats
  41. except ImportError:
  42. # profile isn't bundled by default in Debian for license reasons
  43. try:
  44. import profile,pstats
  45. except ImportError:
  46. profile = pstats = None
  47. # Homebrewed
  48. import IPython
  49. from IPython import Debugger, OInspect, wildcard
  50. from IPython.FakeModule import FakeModule
  51. from IPython.Itpl import Itpl, itpl, printpl,itplns
  52. from IPython.PyColorize import Parser
  53. from IPython.ipstruct import Struct
  54. from IPython.macro import Macro
  55. from IPython.genutils import *
  56. from IPython import platutils
  57. import IPython.generics
  58. import IPython.ipapi
  59. from IPython.ipapi import UsageError
  60. from IPython.testing import decorators as testdec
  61. #***************************************************************************
  62. # Utility functions
  63. def on_off(tag):
  64. """Return an ON/OFF string for a 1/0 input. Simple utility function."""
  65. return ['OFF','ON'][tag]
  66. class Bunch: pass
  67. def compress_dhist(dh):
  68. head, tail = dh[:-10], dh[-10:]
  69. newhead = []
  70. done = Set()
  71. for h in head:
  72. if h in done:
  73. continue
  74. newhead.append(h)
  75. done.add(h)
  76. return newhead + tail
  77. #***************************************************************************
  78. # Main class implementing Magic functionality
  79. class Magic:
  80. """Magic functions for InteractiveShell.
  81. Shell functions which can be reached as %function_name. All magic
  82. functions should accept a string, which they can parse for their own
  83. needs. This can make some functions easier to type, eg `%cd ../`
  84. vs. `%cd("../")`
  85. ALL definitions MUST begin with the prefix magic_. The user won't need it
  86. at the command line, but it is is needed in the definition. """
  87. # class globals
  88. auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
  89. 'Automagic is ON, % prefix NOT needed for magic functions.']
  90. #......................................................................
  91. # some utility functions
  92. def __init__(self,shell):
  93. self.options_table = {}
  94. if profile is None:
  95. self.magic_prun = self.profile_missing_notice
  96. self.shell = shell
  97. # namespace for holding state we may need
  98. self._magic_state = Bunch()
  99. def profile_missing_notice(self, *args, **kwargs):
  100. error("""\
  101. The profile module could not be found. It has been removed from the standard
  102. python packages because of its non-free license. To use profiling, install the
  103. python-profiler package from non-free.""")
  104. def default_option(self,fn,optstr):
  105. """Make an entry in the options_table for fn, with value optstr"""
  106. if fn not in self.lsmagic():
  107. error("%s is not a magic function" % fn)
  108. self.options_table[fn] = optstr
  109. def lsmagic(self):
  110. """Return a list of currently available magic functions.
  111. Gives a list of the bare names after mangling (['ls','cd', ...], not
  112. ['magic_ls','magic_cd',...]"""
  113. # FIXME. This needs a cleanup, in the way the magics list is built.
  114. # magics in class definition
  115. class_magic = lambda fn: fn.startswith('magic_') and \
  116. callable(Magic.__dict__[fn])
  117. # in instance namespace (run-time user additions)
  118. inst_magic = lambda fn: fn.startswith('magic_') and \
  119. callable(self.__dict__[fn])
  120. # and bound magics by user (so they can access self):
  121. inst_bound_magic = lambda fn: fn.startswith('magic_') and \
  122. callable(self.__class__.__dict__[fn])
  123. magics = filter(class_magic,Magic.__dict__.keys()) + \
  124. filter(inst_magic,self.__dict__.keys()) + \
  125. filter(inst_bound_magic,self.__class__.__dict__.keys())
  126. out = []
  127. for fn in Set(magics):
  128. out.append(fn.replace('magic_','',1))
  129. out.sort()
  130. return out
  131. def extract_input_slices(self,slices,raw=False):
  132. """Return as a string a set of input history slices.
  133. Inputs:
  134. - slices: the set of slices is given as a list of strings (like
  135. ['1','4:8','9'], since this function is for use by magic functions
  136. which get their arguments as strings.
  137. Optional inputs:
  138. - raw(False): by default, the processed input is used. If this is
  139. true, the raw input history is used instead.
  140. Note that slices can be called with two notations:
  141. N:M -> standard python form, means including items N...(M-1).
  142. N-M -> include items N..M (closed endpoint)."""
  143. if raw:
  144. hist = self.shell.input_hist_raw
  145. else:
  146. hist = self.shell.input_hist
  147. cmds = []
  148. for chunk in slices:
  149. if ':' in chunk:
  150. ini,fin = map(int,chunk.split(':'))
  151. elif '-' in chunk:
  152. ini,fin = map(int,chunk.split('-'))
  153. fin += 1
  154. else:
  155. ini = int(chunk)
  156. fin = ini+1
  157. cmds.append(hist[ini:fin])
  158. return cmds
  159. def _ofind(self, oname, namespaces=None):
  160. """Find an object in the available namespaces.
  161. self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
  162. Has special code to detect magic functions.
  163. """
  164. oname = oname.strip()
  165. alias_ns = None
  166. if namespaces is None:
  167. # Namespaces to search in:
  168. # Put them in a list. The order is important so that we
  169. # find things in the same order that Python finds them.
  170. namespaces = [ ('Interactive', self.shell.user_ns),
  171. ('IPython internal', self.shell.internal_ns),
  172. ('Python builtin', __builtin__.__dict__),
  173. ('Alias', self.shell.alias_table),
  174. ]
  175. alias_ns = self.shell.alias_table
  176. # initialize results to 'null'
  177. found = 0; obj = None; ospace = None; ds = None;
  178. ismagic = 0; isalias = 0; parent = None
  179. # Look for the given name by splitting it in parts. If the head is
  180. # found, then we look for all the remaining parts as members, and only
  181. # declare success if we can find them all.
  182. oname_parts = oname.split('.')
  183. oname_head, oname_rest = oname_parts[0],oname_parts[1:]
  184. for nsname,ns in namespaces:
  185. try:
  186. obj = ns[oname_head]
  187. except KeyError:
  188. continue
  189. else:
  190. #print 'oname_rest:', oname_rest # dbg
  191. for part in oname_rest:
  192. try:
  193. parent = obj
  194. obj = getattr(obj,part)
  195. except:
  196. # Blanket except b/c some badly implemented objects
  197. # allow __getattr__ to raise exceptions other than
  198. # AttributeError, which then crashes IPython.
  199. break
  200. else:
  201. # If we finish the for loop (no break), we got all members
  202. found = 1
  203. ospace = nsname
  204. if ns == alias_ns:
  205. isalias = 1
  206. break # namespace loop
  207. # Try to see if it's magic
  208. if not found:
  209. if oname.startswith(self.shell.ESC_MAGIC):
  210. oname = oname[1:]
  211. obj = getattr(self,'magic_'+oname,None)
  212. if obj is not None:
  213. found = 1
  214. ospace = 'IPython internal'
  215. ismagic = 1
  216. # Last try: special-case some literals like '', [], {}, etc:
  217. if not found and oname_head in ["''",'""','[]','{}','()']:
  218. obj = eval(oname_head)
  219. found = 1
  220. ospace = 'Interactive'
  221. return {'found':found, 'obj':obj, 'namespace':ospace,
  222. 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
  223. def arg_err(self,func):
  224. """Print docstring if incorrect arguments were passed"""
  225. print 'Error in arguments:'
  226. print OInspect.getdoc(func)
  227. def format_latex(self,strng):
  228. """Format a string for latex inclusion."""
  229. # Characters that need to be escaped for latex:
  230. escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
  231. # Magic command names as headers:
  232. cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
  233. re.MULTILINE)
  234. # Magic commands
  235. cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
  236. re.MULTILINE)
  237. # Paragraph continue
  238. par_re = re.compile(r'\\$',re.MULTILINE)
  239. # The "\n" symbol
  240. newline_re = re.compile(r'\\n')
  241. # Now build the string for output:
  242. #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
  243. strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
  244. strng)
  245. strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
  246. strng = par_re.sub(r'\\\\',strng)
  247. strng = escape_re.sub(r'\\\1',strng)
  248. strng = newline_re.sub(r'\\textbackslash{}n',strng)
  249. return strng
  250. def format_screen(self,strng):
  251. """Format a string for screen printing.
  252. This removes some latex-type format codes."""
  253. # Paragraph continue
  254. par_re = re.compile(r'\\$',re.MULTILINE)
  255. strng = par_re.sub('',strng)
  256. return strng
  257. def parse_options(self,arg_str,opt_str,*long_opts,**kw):
  258. """Parse options passed to an argument string.
  259. The interface is similar to that of getopt(), but it returns back a
  260. Struct with the options as keys and the stripped argument string still
  261. as a string.
  262. arg_str is quoted as a true sys.argv vector by using shlex.split.
  263. This allows us to easily expand variables, glob files, quote
  264. arguments, etc.
  265. Options:
  266. -mode: default 'string'. If given as 'list', the argument string is
  267. returned as a list (split on whitespace) instead of a string.
  268. -list_all: put all option values in lists. Normally only options
  269. appearing more than once are put in a list.
  270. -posix (True): whether to split the input line in POSIX mode or not,
  271. as per the conventions outlined in the shlex module from the
  272. standard library."""
  273. # inject default options at the beginning of the input line
  274. caller = sys._getframe(1).f_code.co_name.replace('magic_','')
  275. arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
  276. mode = kw.get('mode','string')
  277. if mode not in ['string','list']:
  278. raise ValueError,'incorrect mode given: %s' % mode
  279. # Get options
  280. list_all = kw.get('list_all',0)
  281. posix = kw.get('posix',True)
  282. # Check if we have more than one argument to warrant extra processing:
  283. odict = {} # Dictionary with options
  284. args = arg_str.split()
  285. if len(args) >= 1:
  286. # If the list of inputs only has 0 or 1 thing in it, there's no
  287. # need to look for options
  288. argv = arg_split(arg_str,posix)
  289. # Do regular option processing
  290. try:
  291. opts,args = getopt(argv,opt_str,*long_opts)
  292. except GetoptError,e:
  293. raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
  294. " ".join(long_opts)))
  295. for o,a in opts:
  296. if o.startswith('--'):
  297. o = o[2:]
  298. else:
  299. o = o[1:]
  300. try:
  301. odict[o].append(a)
  302. except AttributeError:
  303. odict[o] = [odict[o],a]
  304. except KeyError:
  305. if list_all:
  306. odict[o] = [a]
  307. else:
  308. odict[o] = a
  309. # Prepare opts,args for return
  310. opts = Struct(odict)
  311. if mode == 'string':
  312. args = ' '.join(args)
  313. return opts,args
  314. #......................................................................
  315. # And now the actual magic functions
  316. # Functions for IPython shell work (vars,funcs, config, etc)
  317. def magic_lsmagic(self, parameter_s = ''):
  318. """List currently available magic functions."""
  319. mesc = self.shell.ESC_MAGIC
  320. print 'Available magic functions:\n'+mesc+\
  321. (' '+mesc).join(self.lsmagic())
  322. print '\n' + Magic.auto_status[self.shell.rc.automagic]
  323. return None
  324. def magic_magic(self, parameter_s = ''):
  325. """Print information about the magic function system.
  326. Supported formats: -latex, -brief, -rest
  327. """
  328. mode = ''
  329. try:
  330. if parameter_s.split()[0] == '-latex':
  331. mode = 'latex'
  332. if parameter_s.split()[0] == '-brief':
  333. mode = 'brief'
  334. if parameter_s.split()[0] == '-rest':
  335. mode = 'rest'
  336. rest_docs = []
  337. except:
  338. pass
  339. magic_docs = []
  340. for fname in self.lsmagic():
  341. mname = 'magic_' + fname
  342. for space in (Magic,self,self.__class__):
  343. try:
  344. fn = space.__dict__[mname]
  345. except KeyError:
  346. pass
  347. else:
  348. break
  349. if mode == 'brief':
  350. # only first line
  351. if fn.__doc__:
  352. fndoc = fn.__doc__.split('\n',1)[0]
  353. else:
  354. fndoc = 'No documentation'
  355. else:
  356. fndoc = fn.__doc__.rstrip()
  357. if mode == 'rest':
  358. rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(self.shell.ESC_MAGIC,
  359. fname,fndoc))
  360. else:
  361. magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
  362. fname,fndoc))
  363. magic_docs = ''.join(magic_docs)
  364. if mode == 'rest':
  365. return "".join(rest_docs)
  366. if mode == 'latex':
  367. print self.format_latex(magic_docs)
  368. return
  369. else:
  370. magic_docs = self.format_screen(magic_docs)
  371. if mode == 'brief':
  372. return magic_docs
  373. outmsg = """
  374. IPython's 'magic' functions
  375. ===========================
  376. The magic function system provides a series of functions which allow you to
  377. control the behavior of IPython itself, plus a lot of system-type
  378. features. All these functions are prefixed with a % character, but parameters
  379. are given without parentheses or quotes.
  380. NOTE: If you have 'automagic' enabled (via the command line option or with the
  381. %automagic function), you don't need to type in the % explicitly. By default,
  382. IPython ships with automagic on, so you should only rarely need the % escape.
  383. Example: typing '%cd mydir' (without the quotes) changes you working directory
  384. to 'mydir', if it exists.
  385. You can define your own magic functions to extend the system. See the supplied
  386. ipythonrc and example-magic.py files for details (in your ipython
  387. configuration directory, typically $HOME/.ipython/).
  388. You can also define your own aliased names for magic functions. In your
  389. ipythonrc file, placing a line like:
  390. execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
  391. will define %pf as a new name for %profile.
  392. You can also call magics in code using the ipmagic() function, which IPython
  393. automatically adds to the builtin namespace. Type 'ipmagic?' for details.
  394. For a list of the available magic functions, use %lsmagic. For a description
  395. of any of them, type %magic_name?, e.g. '%cd?'.
  396. Currently the magic system has the following functions:\n"""
  397. mesc = self.shell.ESC_MAGIC
  398. outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
  399. "\n\n%s%s\n\n%s" % (outmsg,
  400. magic_docs,mesc,mesc,
  401. (' '+mesc).join(self.lsmagic()),
  402. Magic.auto_status[self.shell.rc.automagic] ) )
  403. page(outmsg,screen_lines=self.shell.rc.screen_length)
  404. def magic_autoindent(self, parameter_s = ''):
  405. """Toggle autoindent on/off (if available)."""
  406. self.shell.set_autoindent()
  407. print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
  408. def magic_automagic(self, parameter_s = ''):
  409. """Make magic functions callable without having to type the initial %.
  410. Without argumentsl toggles on/off (when off, you must call it as
  411. %automagic, of course). With arguments it sets the value, and you can
  412. use any of (case insensitive):
  413. - on,1,True: to activate
  414. - off,0,False: to deactivate.
  415. Note that magic functions have lowest priority, so if there's a
  416. variable whose name collides with that of a magic fn, automagic won't
  417. work for that function (you get the variable instead). However, if you
  418. delete the variable (del var), the previously shadowed magic function
  419. becomes visible to automagic again."""
  420. rc = self.shell.rc
  421. arg = parameter_s.lower()
  422. if parameter_s in ('on','1','true'):
  423. rc.automagic = True
  424. elif parameter_s in ('off','0','false'):
  425. rc.automagic = False
  426. else:
  427. rc.automagic = not rc.automagic
  428. print '\n' + Magic.auto_status[rc.automagic]
  429. @testdec.skip_doctest
  430. def magic_autocall(self, parameter_s = ''):
  431. """Make functions callable without having to type parentheses.
  432. Usage:
  433. %autocall [mode]
  434. The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
  435. value is toggled on and off (remembering the previous state).
  436. In more detail, these values mean:
  437. 0 -> fully disabled
  438. 1 -> active, but do not apply if there are no arguments on the line.
  439. In this mode, you get:
  440. In [1]: callable
  441. Out[1]: <built-in function callable>
  442. In [2]: callable 'hello'
  443. ------> callable('hello')
  444. Out[2]: False
  445. 2 -> Active always. Even if no arguments are present, the callable
  446. object is called:
  447. In [2]: float
  448. ------> float()
  449. Out[2]: 0.0
  450. Note that even with autocall off, you can still use '/' at the start of
  451. a line to treat the first argument on the command line as a function
  452. and add parentheses to it:
  453. In [8]: /str 43
  454. ------> str(43)
  455. Out[8]: '43'
  456. # all-random (note for auto-testing)
  457. """
  458. rc = self.shell.rc
  459. if parameter_s:
  460. arg = int(parameter_s)
  461. else:
  462. arg = 'toggle'
  463. if not arg in (0,1,2,'toggle'):
  464. error('Valid modes: (0->Off, 1->Smart, 2->Full')
  465. return
  466. if arg in (0,1,2):
  467. rc.autocall = arg
  468. else: # toggle
  469. if rc.autocall:
  470. self._magic_state.autocall_save = rc.autocall
  471. rc.autocall = 0
  472. else:
  473. try:
  474. rc.autocall = self._magic_state.autocall_save
  475. except AttributeError:
  476. rc.autocall = self._magic_state.autocall_save = 1
  477. print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
  478. def magic_system_verbose(self, parameter_s = ''):
  479. """Set verbose printing of system calls.
  480. If called without an argument, act as a toggle"""
  481. if parameter_s:
  482. val = bool(eval(parameter_s))
  483. else:
  484. val = None
  485. self.shell.rc_set_toggle('system_verbose',val)
  486. print "System verbose printing is:",\
  487. ['OFF','ON'][self.shell.rc.system_verbose]
  488. def magic_page(self, parameter_s=''):
  489. """Pretty print the object and display it through a pager.
  490. %page [options] OBJECT
  491. If no object is given, use _ (last output).
  492. Options:
  493. -r: page str(object), don't pretty-print it."""
  494. # After a function contributed by Olivier Aubert, slightly modified.
  495. # Process options/args
  496. opts,args = self.parse_options(parameter_s,'r')
  497. raw = 'r' in opts
  498. oname = args and args or '_'
  499. info = self._ofind(oname)
  500. if info['found']:
  501. txt = (raw and str or pformat)( info['obj'] )
  502. page(txt)
  503. else:
  504. print 'Object `%s` not found' % oname
  505. def magic_profile(self, parameter_s=''):
  506. """Print your currently active IPyhton profile."""
  507. if self.shell.rc.profile:
  508. printpl('Current IPython profile: $self.shell.rc.profile.')
  509. else:
  510. print 'No profile active.'
  511. def magic_pinfo(self, parameter_s='', namespaces=None):
  512. """Provide detailed information about an object.
  513. '%pinfo object' is just a synonym for object? or ?object."""
  514. #print 'pinfo par: <%s>' % parameter_s # dbg
  515. # detail_level: 0 -> obj? , 1 -> obj??
  516. detail_level = 0
  517. # We need to detect if we got called as 'pinfo pinfo foo', which can
  518. # happen if the user types 'pinfo foo?' at the cmd line.
  519. pinfo,qmark1,oname,qmark2 = \
  520. re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
  521. if pinfo or qmark1 or qmark2:
  522. detail_level = 1
  523. if "*" in oname:
  524. self.magic_psearch(oname)
  525. else:
  526. self._inspect('pinfo', oname, detail_level=detail_level,
  527. namespaces=namespaces)
  528. def magic_pdef(self, parameter_s='', namespaces=None):
  529. """Print the definition header for any callable object.
  530. If the object is a class, print the constructor information."""
  531. self._inspect('pdef',parameter_s, namespaces)
  532. def magic_pdoc(self, parameter_s='', namespaces=None):
  533. """Print the docstring for an object.
  534. If the given object is a class, it will print both the class and the
  535. constructor docstrings."""
  536. self._inspect('pdoc',parameter_s, namespaces)
  537. def magic_psource(self, parameter_s='', namespaces=None):
  538. """Print (or run through pager) the source code for an object."""
  539. self._inspect('psource',parameter_s, namespaces)
  540. def magic_pfile(self, parameter_s=''):
  541. """Print (or run through pager) the file where an object is defined.
  542. The file opens at the line where the object definition begins. IPython
  543. will honor the environment variable PAGER if set, and otherwise will
  544. do its best to print the file in a convenient form.
  545. If the given argument is not an object currently defined, IPython will
  546. try to interpret it as a filename (automatically adding a .py extension
  547. if needed). You can thus use %pfile as a syntax highlighting code
  548. viewer."""
  549. # first interpret argument as an object name
  550. out = self._inspect('pfile',parameter_s)
  551. # if not, try the input as a filename
  552. if out == 'not found':
  553. try:
  554. filename = get_py_filename(parameter_s)
  555. except IOError,msg:
  556. print msg
  557. return
  558. page(self.shell.inspector.format(file(filename).read()))
  559. def _inspect(self,meth,oname,namespaces=None,**kw):
  560. """Generic interface to the inspector system.
  561. This function is meant to be called by pdef, pdoc & friends."""
  562. #oname = oname.strip()
  563. #print '1- oname: <%r>' % oname # dbg
  564. try:
  565. oname = oname.strip().encode('ascii')
  566. #print '2- oname: <%r>' % oname # dbg
  567. except UnicodeEncodeError:
  568. print 'Python identifiers can only contain ascii characters.'
  569. return 'not found'
  570. info = Struct(self._ofind(oname, namespaces))
  571. if info.found:
  572. try:
  573. IPython.generics.inspect_object(info.obj)
  574. return
  575. except IPython.ipapi.TryNext:
  576. pass
  577. # Get the docstring of the class property if it exists.
  578. path = oname.split('.')
  579. root = '.'.join(path[:-1])
  580. if info.parent is not None:
  581. try:
  582. target = getattr(info.parent, '__class__')
  583. # The object belongs to a class instance.
  584. try:
  585. target = getattr(target, path[-1])
  586. # The class defines the object.
  587. if isinstance(target, property):
  588. oname = root + '.__class__.' + path[-1]
  589. info = Struct(self._ofind(oname))
  590. except AttributeError: pass
  591. except AttributeError: pass
  592. pmethod = getattr(self.shell.inspector,meth)
  593. formatter = info.ismagic and self.format_screen or None
  594. if meth == 'pdoc':
  595. pmethod(info.obj,oname,formatter)
  596. elif meth == 'pinfo':
  597. pmethod(info.obj,oname,formatter,info,**kw)
  598. else:
  599. pmethod(info.obj,oname)
  600. else:
  601. print 'Object `%s` not found.' % oname
  602. return 'not found' # so callers can take other action
  603. def magic_psearch(self, parameter_s=''):
  604. """Search for object in namespaces by wildcard.
  605. %psearch [options] PATTERN [OBJECT TYPE]
  606. Note: ? can be used as a synonym for %psearch, at the beginning or at
  607. the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
  608. rest of the command line must be unchanged (options come first), so
  609. for example the following forms are equivalent
  610. %psearch -i a* function
  611. -i a* function?
  612. ?-i a* function
  613. Arguments:
  614. PATTERN
  615. where PATTERN is a string containing * as a wildcard similar to its
  616. use in a shell. The pattern is matched in all namespaces on the
  617. search path. By default objects starting with a single _ are not
  618. matched, many IPython generated objects have a single
  619. underscore. The default is case insensitive matching. Matching is
  620. also done on the attributes of objects and not only on the objects
  621. in a module.
  622. [OBJECT TYPE]
  623. Is the name of a python type from the types module. The name is
  624. given in lowercase without the ending type, ex. StringType is
  625. written string. By adding a type here only objects matching the
  626. given type are matched. Using all here makes the pattern match all
  627. types (this is the default).
  628. Options:
  629. -a: makes the pattern match even objects whose names start with a
  630. single underscore. These names are normally ommitted from the
  631. search.
  632. -i/-c: make the pattern case insensitive/sensitive. If neither of
  633. these options is given, the default is read from your ipythonrc
  634. file. The option name which sets this value is
  635. 'wildcards_case_sensitive'. If this option is not specified in your
  636. ipythonrc file, IPython's internal default is to do a case sensitive
  637. search.
  638. -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
  639. specifiy can be searched in any of the following namespaces:
  640. 'builtin', 'user', 'user_global','internal', 'alias', where
  641. 'builtin' and 'user' are the search defaults. Note that you should
  642. not use quotes when specifying namespaces.
  643. 'Builtin' contains the python module builtin, 'user' contains all
  644. user data, 'alias' only contain the shell aliases and no python
  645. objects, 'internal' contains objects used by IPython. The
  646. 'user_global' namespace is only used by embedded IPython instances,
  647. and it contains module-level globals. You can add namespaces to the
  648. search with -s or exclude them with -e (these options can be given
  649. more than once).
  650. Examples:
  651. %psearch a* -> objects beginning with an a
  652. %psearch -e builtin a* -> objects NOT in the builtin space starting in a
  653. %psearch a* function -> all functions beginning with an a
  654. %psearch re.e* -> objects beginning with an e in module re
  655. %psearch r*.e* -> objects that start with e in modules starting in r
  656. %psearch r*.* string -> all strings in modules beginning with r
  657. Case sensitve search:
  658. %psearch -c a* list all object beginning with lower case a
  659. Show objects beginning with a single _:
  660. %psearch -a _* list objects beginning with a single underscore"""
  661. try:
  662. parameter_s = parameter_s.encode('ascii')
  663. except UnicodeEncodeError:
  664. print 'Python identifiers can only contain ascii characters.'
  665. return
  666. # default namespaces to be searched
  667. def_search = ['user','builtin']
  668. # Process options/args
  669. opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
  670. opt = opts.get
  671. shell = self.shell
  672. psearch = shell.inspector.psearch
  673. # select case options
  674. if opts.has_key('i'):
  675. ignore_case = True
  676. elif opts.has_key('c'):
  677. ignore_case = False
  678. else:
  679. ignore_case = not shell.rc.wildcards_case_sensitive
  680. # Build list of namespaces to search from user options
  681. def_search.extend(opt('s',[]))
  682. ns_exclude = ns_exclude=opt('e',[])
  683. ns_search = [nm for nm in def_search if nm not in ns_exclude]
  684. # Call the actual search
  685. try:
  686. psearch(args,shell.ns_table,ns_search,
  687. show_all=opt('a'),ignore_case=ignore_case)
  688. except:
  689. shell.showtraceback()
  690. def magic_who_ls(self, parameter_s=''):
  691. """Return a sorted list of all interactive variables.
  692. If arguments are given, only variables of types matching these
  693. arguments are returned."""
  694. user_ns = self.shell.user_ns
  695. internal_ns = self.shell.internal_ns
  696. user_config_ns = self.shell.user_config_ns
  697. out = []
  698. typelist = parameter_s.split()
  699. for i in user_ns:
  700. if not (i.startswith('_') or i.startswith('_i')) \
  701. and not (i in internal_ns or i in user_config_ns):
  702. if typelist:
  703. if type(user_ns[i]).__name__ in typelist:
  704. out.append(i)
  705. else:
  706. out.append(i)
  707. out.sort()
  708. return out
  709. def magic_who(self, parameter_s=''):
  710. """Print all interactive variables, with some minimal formatting.
  711. If any arguments are given, only variables whose type matches one of
  712. these are printed. For example:
  713. %who function str
  714. will only list functions and strings, excluding all other types of
  715. variables. To find the proper type names, simply use type(var) at a
  716. command line to see how python prints type names. For example:
  717. In [1]: type('hello')\\
  718. Out[1]: <type 'str'>
  719. indicates that the type name for strings is 'str'.
  720. %who always excludes executed names loaded through your configuration
  721. file and things which are internal to IPython.
  722. This is deliberate, as typically you may load many modules and the
  723. purpose of %who is to show you only what you've manually defined."""
  724. varlist = self.magic_who_ls(parameter_s)
  725. if not varlist:
  726. if parameter_s:
  727. print 'No variables match your requested type.'
  728. else:
  729. print 'Interactive namespace is empty.'
  730. return
  731. # if we have variables, move on...
  732. count = 0
  733. for i in varlist:
  734. print i+'\t',
  735. count += 1
  736. if count > 8:
  737. count = 0
  738. print
  739. print
  740. def magic_whos(self, parameter_s=''):
  741. """Like %who, but gives some extra information about each variable.
  742. The same type filtering of %who can be applied here.
  743. For all variables, the type is printed. Additionally it prints:
  744. - For {},[],(): their length.
  745. - For numpy and Numeric arrays, a summary with shape, number of
  746. elements, typecode and size in memory.
  747. - Everything else: a string representation, snipping their middle if
  748. too long."""
  749. varnames = self.magic_who_ls(parameter_s)
  750. if not varnames:
  751. if parameter_s:
  752. print 'No variables match your requested type.'
  753. else:
  754. print 'Interactive namespace is empty.'
  755. return
  756. # if we have variables, move on...
  757. # for these types, show len() instead of data:
  758. seq_types = [types.DictType,types.ListType,types.TupleType]
  759. # for numpy/Numeric arrays, display summary info
  760. try:
  761. import numpy
  762. except ImportError:
  763. ndarray_type = None
  764. else:
  765. ndarray_type = numpy.ndarray.__name__
  766. try:
  767. import Numeric
  768. except ImportError:
  769. array_type = None
  770. else:
  771. array_type = Numeric.ArrayType.__name__
  772. # Find all variable names and types so we can figure out column sizes
  773. def get_vars(i):
  774. return self.shell.user_ns[i]
  775. # some types are well known and can be shorter
  776. abbrevs = {'IPython.macro.Macro' : 'Macro'}
  777. def type_name(v):
  778. tn = type(v).__name__
  779. return abbrevs.get(tn,tn)
  780. varlist = map(get_vars,varnames)
  781. typelist = []
  782. for vv in varlist:
  783. tt = type_name(vv)
  784. if tt=='instance':
  785. typelist.append( abbrevs.get(str(vv.__class__),
  786. str(vv.__class__)))
  787. else:
  788. typelist.append(tt)
  789. # column labels and # of spaces as separator
  790. varlabel = 'Variable'
  791. typelabel = 'Type'
  792. datalabel = 'Data/Info'
  793. colsep = 3
  794. # variable format strings
  795. vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
  796. vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
  797. aformat = "%s: %s elems, type `%s`, %s bytes"
  798. # find the size of the columns to format the output nicely
  799. varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
  800. typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
  801. # table header
  802. print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
  803. ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
  804. # and the table itself
  805. kb = 1024
  806. Mb = 1048576 # kb**2
  807. for vname,var,vtype in zip(varnames,varlist,typelist):
  808. print itpl(vformat),
  809. if vtype in seq_types:
  810. print len(var)
  811. elif vtype in [array_type,ndarray_type]:
  812. vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
  813. if vtype==ndarray_type:
  814. # numpy
  815. vsize = var.size
  816. vbytes = vsize*var.itemsize
  817. vdtype = var.dtype
  818. else:
  819. # Numeric
  820. vsize = Numeric.size(var)
  821. vbytes = vsize*var.itemsize()
  822. vdtype = var.typecode()
  823. if vbytes < 100000:
  824. print aformat % (vshape,vsize,vdtype,vbytes)
  825. else:
  826. print aformat % (vshape,vsize,vdtype,vbytes),
  827. if vbytes < Mb:
  828. print '(%s kb)' % (vbytes/kb,)
  829. else:
  830. print '(%s Mb)' % (vbytes/Mb,)
  831. else:
  832. try:
  833. vstr = str(var)
  834. except UnicodeEncodeError:
  835. vstr = unicode(var).encode(sys.getdefaultencoding(),
  836. 'backslashreplace')
  837. vstr = vstr.replace('\n','\\n')
  838. if len(vstr) < 50:
  839. print vstr
  840. else:
  841. printpl(vfmt_short)
  842. def magic_reset(self, parameter_s=''):
  843. """Resets the namespace by removing all names defined by the user.
  844. Input/Output history are left around in case you need them."""
  845. ans = self.shell.ask_yes_no(
  846. "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
  847. if not ans:
  848. print 'Nothing done.'
  849. return
  850. user_ns = self.shell.user_ns
  851. for i in self.magic_who_ls():
  852. del(user_ns[i])
  853. # Also flush the private list of module references kept for script
  854. # execution protection
  855. self.shell._user_main_modules[:] = []
  856. def magic_logstart(self,parameter_s=''):
  857. """Start logging anywhere in a session.
  858. %logstart [-o|-r|-t] [log_name [log_mode]]
  859. If no name is given, it defaults to a file named 'ipython_log.py' in your
  860. current directory, in 'rotate' mode (see below).
  861. '%logstart name' saves to file 'name' in 'backup' mode. It saves your
  862. history up to that point and then continues logging.
  863. %logstart takes a second optional parameter: logging mode. This can be one
  864. of (note that the modes are given unquoted):\\
  865. append: well, that says it.\\
  866. backup: rename (if exists) to name~ and start name.\\
  867. global: single logfile in your home dir, appended to.\\
  868. over : overwrite existing log.\\
  869. rotate: create rotating logs name.1~, name.2~, etc.
  870. Options:
  871. -o: log also IPython's output. In this mode, all commands which
  872. generate an Out[NN] prompt are recorded to the logfile, right after
  873. their corresponding input line. The output lines are always
  874. prepended with a '#[Out]# ' marker, so that the log remains valid
  875. Python code.
  876. Since this marker is always the same, filtering only the output from
  877. a log is very easy, using for example a simple awk call:
  878. awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
  879. -r: log 'raw' input. Normally, IPython's logs contain the processed
  880. input, so that user lines are logged in their final form, converted
  881. into valid Python. For example, %Exit is logged as
  882. '_ip.magic("Exit"). If the -r flag is given, all input is logged
  883. exactly as typed, with no transformations applied.
  884. -t: put timestamps before each input line logged (these are put in
  885. comments)."""
  886. opts,par = self.parse_options(parameter_s,'ort')
  887. log_output = 'o' in opts
  888. log_raw_input = 'r' in opts
  889. timestamp = 't' in opts
  890. rc = self.shell.rc
  891. logger = self.shell.logger
  892. # if no args are given, the defaults set in the logger constructor by
  893. # ipytohn remain valid
  894. if par:
  895. try:
  896. logfname,logmode = par.split()
  897. except:
  898. logfname = par
  899. logmode = 'backup'
  900. else:
  901. logfname = logger.logfname
  902. logmode = logger.logmode
  903. # put logfname into rc struct as if it had been called on the command
  904. # line, so it ends up saved in the log header Save it in case we need
  905. # to restore it...
  906. old_logfile = rc.opts.get('logfile','')
  907. if logfname:
  908. logfname = os.path.expanduser(logfname)
  909. rc.opts.logfile = logfname
  910. loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
  911. try:
  912. started = logger.logstart(logfname,loghead,logmode,
  913. log_output,timestamp,log_raw_input)
  914. except:
  915. rc.opts.logfile = old_logfile
  916. warn("Couldn't start log: %s" % sys.exc_info()[1])
  917. else:
  918. # log input history up to this point, optionally interleaving
  919. # output if requested
  920. if timestamp:
  921. # disable timestamping for the previous history, since we've
  922. # lost those already (no time machine here).
  923. logger.timestamp = False
  924. if log_raw_input:
  925. input_hist = self.shell.input_hist_raw
  926. else:
  927. input_hist = self.shell.input_hist
  928. if log_output:
  929. log_write = logger.log_write
  930. output_hist = self.shell.output_hist
  931. for n in range(1,len(input_hist)-1):
  932. log_write(input_hist[n].rstrip())
  933. if n in output_hist:
  934. log_write(repr(output_hist[n]),'output')
  935. else:
  936. logger.log_write(input_hist[1:])
  937. if timestamp:
  938. # re-enable timestamping
  939. logger.timestamp = True
  940. print ('Activating auto-logging. '
  941. 'Current session state plus future input saved.')
  942. logger.logstate()
  943. def magic_logstop(self,parameter_s=''):
  944. """Fully stop logging and close log file.
  945. In order to start logging again, a new %logstart call needs to be made,
  946. possibly (though not necessarily) with a new filename, mode and other
  947. options."""
  948. self.logger.logstop()
  949. def magic_logoff(self,parameter_s=''):
  950. """Temporarily stop logging.
  951. You must have previously started logging."""
  952. self.shell.logger.switch_log(0)
  953. def magic_logon(self,parameter_s=''):
  954. """Restart logging.
  955. This function is for restarting logging which you've temporarily
  956. stopped with %logoff. For starting logging for the first time, you
  957. must use the %logstart function, which allows you to specify an
  958. optional log filename."""
  959. self.shell.logger.switch_log(1)
  960. def magic_logstate(self,parameter_s=''):
  961. """Print the status of the logging system."""
  962. self.shell.logger.logstate()
  963. def magic_pdb(self, parameter_s=''):
  964. """Control the automatic calling of the pdb interactive debugger.
  965. Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
  966. argument it works as a toggle.
  967. When an exception is triggered, IPython can optionally call the
  968. interactive pdb debugger after the traceback printout. %pdb toggles
  969. this feature on and off.
  970. The initial state of this feature is set in your ipythonrc
  971. configuration file (the variable is called 'pdb').
  972. If you want to just activate the debugger AFTER an exception has fired,
  973. without having to type '%pdb on' and rerunning your code, you can use
  974. the %debug magic."""
  975. par = parameter_s.strip().lower()
  976. if par:
  977. try:
  978. new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
  979. except KeyError:
  980. print ('Incorrect argument. Use on/1, off/0, '
  981. 'or nothing for a toggle.')
  982. return
  983. else:
  984. # toggle
  985. new_pdb = not self.shell.call_pdb
  986. # set on the shell
  987. self.shell.call_pdb = new_pdb
  988. print 'Automatic pdb calling has been turned',on_off(new_pdb)
  989. def magic_debug(self, parameter_s=''):
  990. """Activate the interactive debugger in post-mortem mode.
  991. If an exception has just occurred, this lets you inspect its stack
  992. frames interactively. Note that this will always work only on the last
  993. traceback that occurred, so you must call this quickly after an
  994. exception that you wish to inspect has fired, because if another one
  995. occurs, it clobbers the previous one.
  996. If you want IPython to automatically do this on every exception, see
  997. the %pdb magic for more details.
  998. """
  999. self.shell.debugger(force=True)
  1000. @testdec.skip_doctest
  1001. def magic_prun(self, parameter_s ='',user_mode=1,
  1002. opts=None,arg_lst=None,prog_ns=None):
  1003. """Run a statement through the python code profiler.
  1004. Usage:
  1005. %prun [options] statement
  1006. The given statement (which doesn't require quote marks) is run via the
  1007. python profiler in a manner similar to the profile.run() function.
  1008. Namespaces are internally managed to work correctly; profile.run
  1009. cannot be used in IPython because it makes certain assumptions about
  1010. namespaces which do not hold under IPython.
  1011. Options:
  1012. -l <limit>: you can place restrictions on what or how much of the
  1013. profile gets printed. The limit value can be:
  1014. * A string: only information for function names containing this string
  1015. is printed.
  1016. * An integer: only these many lines are printed.
  1017. * A float (between 0 and 1): this fraction of the report is printed
  1018. (for example, use a limit of 0.4 to see the topmost 40% only).
  1019. You can combine several limits with repeated use of the option. For
  1020. example, '-l __init__ -l 5' will print only the topmost 5 lines of
  1021. information about class constructors.
  1022. -r: return the pstats.Stats object generated by the profiling. This
  1023. object has all the information about the profile in it, and you can
  1024. later use it for further analysis or in other functions.
  1025. -s <key>: sort profile by given key. You can provide more than one key
  1026. by using the option several times: '-s key1 -s key2 -s key3...'. The
  1027. default sorting key is 'time'.
  1028. The following is copied verbatim from the profile documentation
  1029. referenced below:
  1030. When more than one key is provided, additional keys are used as
  1031. secondary criteria when the there is equality in all keys selected
  1032. before them.
  1033. Abbreviations can be used for any key names, as long as the
  1034. abbreviation is unambiguous. The following are the keys currently
  1035. defined:
  1036. Valid Arg Meaning
  1037. "calls" call count
  1038. "cumulative" cumulative time
  1039. "file" file name
  1040. "module" file name
  1041. "pcalls" primitive call count
  1042. "line" line number
  1043. "name" function name
  1044. "nfl" name/file/line
  1045. "stdname" standard name
  1046. "time" internal time
  1047. Note that all sorts on statistics are in descending order (placing
  1048. most time consuming items first), where as name, file, and line number
  1049. searches are in ascending order (i.e., alphabetical). The subtle
  1050. distinction between "nfl" and "stdname" is that the standard name is a
  1051. sort of the name as printed, which means that the embedded line
  1052. numbers get compared in an odd way. For example, lines 3, 20, and 40
  1053. would (if the file names were the same) appear in the string order
  1054. "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
  1055. line numbers. In fact, sort_stats("nfl") is the same as
  1056. sort_stats("name", "file", "line").
  1057. -T <filename>: save profile results as shown on screen to a text
  1058. file. The profile is still shown on screen.
  1059. -D <filename>: save (via dump_stats) profile statistics to given
  1060. filename. This data is in a format understod by the pstats module, and
  1061. is generated by a call to the dump_stats() method of profile
  1062. objects. The profile is still shown on screen.
  1063. If you want to run complete progra