PageRenderTime 70ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 1ms

/pylons-rest-ENV/lib/python2.6/site-packages/IPython/Magic.py

https://bitbucket.org/noahgift/pylons-rest-tutorial
Python | 3526 lines | 3469 code | 23 blank | 34 comment | 27 complexity | e32312778e89911061f36e91c67d3a6f MD5 | raw file
Possible License(s): 0BSD

Large files files are truncated, but you can click here to view the full file

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

Large files files are truncated, but you can click here to view the full file