/IPyShell/IPython/Magic.py

http://editra-plugins.googlecode.com/ · Python · 3381 lines · 2923 code · 208 blank · 250 comment · 213 complexity · f05c5ae5bdacb4008a80cd1cee87f2da MD5 · raw 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 programs under the profiler's control, use
  1064. '%run -p [prof_opts] filename.py [args to program]' where prof_opts
  1065. contains profiler specific options as described here.
  1066. You can read the complete documentation for the profile module with::
  1067. In [1]: import profile; profile.help()
  1068. """
  1069. opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
  1070. # protect user quote marks
  1071. parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
  1072. if user_mode: # regular user call
  1073. opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
  1074. list_all=1)
  1075. namespace = self.shell.user_ns
  1076. else: # called to run a program by %run -p
  1077. try:
  1078. filename = get_py_filename(arg_lst[0])
  1079. except IOError,msg:
  1080. error(msg)
  1081. return
  1082. arg_str = 'execfile(filename,prog_ns)'
  1083. namespace = locals()
  1084. opts.merge(opts_def)
  1085. prof = profile.Profile()
  1086. try:
  1087. prof = prof.runctx(arg_str,namespace,namespace)
  1088. sys_exit = ''
  1089. except SystemExit:
  1090. sys_exit = """*** SystemExit exception caught in code being profiled."""
  1091. stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
  1092. lims = opts.l
  1093. if lims:
  1094. lims = [] # rebuild lims with ints/floats/strings
  1095. for lim in opts.l:
  1096. try:
  1097. lims.append(int(lim))
  1098. except ValueError:
  1099. try:
  1100. lims.append(float(lim))
  1101. except ValueError:
  1102. lims.append(lim)
  1103. # Trap output.
  1104. stdout_trap = StringIO()
  1105. if hasattr(stats,'stream'):
  1106. # In newer versions of python, the stats object has a 'stream'
  1107. # attribute to write into.
  1108. stats.stream = stdout_trap
  1109. stats.print_stats(*lims)
  1110. else:
  1111. # For older versions, we manually redirect stdout during printing
  1112. sys_stdout = sys.stdout
  1113. try:
  1114. sys.stdout = stdout_trap
  1115. stats.print_stats(*lims)
  1116. finally:
  1117. sys.stdout = sys_stdout
  1118. output = stdout_trap.getvalue()
  1119. output = output.rstrip()
  1120. page(output,screen_lines=self.shell.rc.screen_length)
  1121. print sys_exit,
  1122. dump_file = opts.D[0]
  1123. text_file = opts.T[0]
  1124. if dump_file:
  1125. prof.dump_stats(dump_file)
  1126. print '\n*** Profile stats marshalled to file',\
  1127. `dump_file`+'.',sys_exit
  1128. if text_file:
  1129. pfile = file(text_file,'w')
  1130. pfile.write(output)
  1131. pfile.close()
  1132. print '\n*** Profile printout saved to text file',\
  1133. `text_file`+'.',sys_exit
  1134. if opts.has_key('r'):
  1135. return stats
  1136. else:
  1137. return None
  1138. @testdec.skip_doctest
  1139. def magic_run(self, parameter_s ='',runner=None):
  1140. """Run the named file inside IPython as a program.
  1141. Usage:\\
  1142. %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
  1143. Parameters after the filename are passed as command-line arguments to
  1144. the program (put in sys.argv). Then, control returns to IPython's
  1145. prompt.
  1146. This is similar to running at a system prompt:\\
  1147. $ python file args\\
  1148. but with the advantage of giving you IPython's tracebacks, and of
  1149. loading all variables into your interactive namespace for further use
  1150. (unless -p is used, see below).
  1151. The file is executed in a namespace initially consisting only of
  1152. __name__=='__main__' and sys.argv constructed as indicated. It thus
  1153. sees its environment as if it were being run as a stand-alone program
  1154. (except for sharing global objects such as previously imported
  1155. modules). But after execution, the IPython interactive namespace gets
  1156. updated with all variables defined in the program (except for __name__
  1157. and sys.argv). This allows for very convenient loading of code for
  1158. interactive work, while giving each program a 'clean sheet' to run in.
  1159. Options:
  1160. -n: __name__ is NOT set to '__main__', but to the running file's name
  1161. without extension (as python does under import). This allows running
  1162. scripts and reloading the definitions in them without calling code
  1163. protected by an ' if __name__ == "__main__" ' clause.
  1164. -i: run the file in IPython's namespace instead of an empty one. This
  1165. is useful if you are experimenting with code written in a text editor
  1166. which depends on variables defined interactively.
  1167. -e: ignore sys.exit() calls or SystemExit exceptions in the script
  1168. being run. This is particularly useful if IPython is being used to
  1169. run unittests, which always exit with a sys.exit() call. In such
  1170. cases you are interested in the output of the test results, not in
  1171. seeing a traceback of the unittest module.
  1172. -t: print timing information at the end of the run. IPython will give
  1173. you an estimated CPU time consumption for your script, which under
  1174. Unix uses the resource module to avoid the wraparound problems of
  1175. time.clock(). Under Unix, an estimate of time spent on system tasks
  1176. is also given (for Windows platforms this is reported as 0.0).
  1177. If -t is given, an additional -N<N> option can be given, where <N>
  1178. must be an integer indicating how many times you want the script to
  1179. run. The final timing report will include total and per run results.
  1180. For example (testing the script uniq_stable.py):
  1181. In [1]: run -t uniq_stable
  1182. IPython CPU timings (estimated):\\
  1183. User : 0.19597 s.\\
  1184. System: 0.0 s.\\
  1185. In [2]: run -t -N5 uniq_stable
  1186. IPython CPU timings (estimated):\\
  1187. Total runs performed: 5\\
  1188. Times : Total Per run\\
  1189. User : 0.910862 s, 0.1821724 s.\\
  1190. System: 0.0 s, 0.0 s.
  1191. -d: run your program under the control of pdb, the Python debugger.
  1192. This allows you to execute your program step by step, watch variables,
  1193. etc. Internally, what IPython does is similar to calling:
  1194. pdb.run('execfile("YOURFILENAME")')
  1195. with a breakpoint set on line 1 of your file. You can change the line
  1196. number for this automatic breakpoint to be <N> by using the -bN option
  1197. (where N must be an integer). For example:
  1198. %run -d -b40 myscript
  1199. will set the first breakpoint at line 40 in myscript.py. Note that
  1200. the first breakpoint must be set on a line which actually does
  1201. something (not a comment or docstring) for it to stop execution.
  1202. When the pdb debugger starts, you will see a (Pdb) prompt. You must
  1203. first enter 'c' (without qoutes) to start execution up to the first
  1204. breakpoint.
  1205. Entering 'help' gives information about the use of the debugger. You
  1206. can easily see pdb's full documentation with "import pdb;pdb.help()"
  1207. at a prompt.
  1208. -p: run program under the control of the Python profiler module (which
  1209. prints a detailed report of execution times, function calls, etc).
  1210. You can pass other options after -p which affect the behavior of the
  1211. profiler itself. See the docs for %prun for details.
  1212. In this mode, the program's variables do NOT propagate back to the
  1213. IPython interactive namespace (because they remain in the namespace
  1214. where the profiler executes them).
  1215. Internally this triggers a call to %prun, see its documentation for
  1216. details on the options available specifically for profiling.
  1217. There is one special usage for which the text above doesn't apply:
  1218. if the filename ends with .ipy, the file is run as ipython script,
  1219. just as if the commands were written on IPython prompt.
  1220. """
  1221. # get arguments and set sys.argv for program to be run.
  1222. opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
  1223. mode='list',list_all=1)
  1224. try:
  1225. filename = get_py_filename(arg_lst[0])
  1226. except IndexError:
  1227. warn('you must provide at least a filename.')
  1228. print '\n%run:\n',OInspect.getdoc(self.magic_run)
  1229. return
  1230. except IOError,msg:
  1231. error(msg)
  1232. return
  1233. if filename.lower().endswith('.ipy'):
  1234. self.api.runlines(open(filename).read())
  1235. return
  1236. # Control the response to exit() calls made by the script being run
  1237. exit_ignore = opts.has_key('e')
  1238. # Make sure that the running script gets a proper sys.argv as if it
  1239. # were run from a system shell.
  1240. save_argv = sys.argv # save it for later restoring
  1241. sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
  1242. if opts.has_key('i'):
  1243. # Run in user's interactive namespace
  1244. prog_ns = self.shell.user_ns
  1245. __name__save = self.shell.user_ns['__name__']
  1246. prog_ns['__name__'] = '__main__'
  1247. main_mod = FakeModule(prog_ns)
  1248. else:
  1249. # Run in a fresh, empty namespace
  1250. if opts.has_key('n'):
  1251. name = os.path.splitext(os.path.basename(filename))[0]
  1252. else:
  1253. name = '__main__'
  1254. main_mod = FakeModule()
  1255. prog_ns = main_mod.__dict__
  1256. prog_ns['__name__'] = name
  1257. # The shell MUST hold a reference to main_mod so after %run exits,
  1258. # the python deletion mechanism doesn't zero it out (leaving
  1259. # dangling references)
  1260. self.shell._user_main_modules.append(main_mod)
  1261. # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
  1262. # set the __file__ global in the script's namespace
  1263. prog_ns['__file__'] = filename
  1264. # pickle fix. See iplib for an explanation. But we need to make sure
  1265. # that, if we overwrite __main__, we replace it at the end
  1266. main_mod_name = prog_ns['__name__']
  1267. if main_mod_name == '__main__':
  1268. restore_main = sys.modules['__main__']
  1269. else:
  1270. restore_main = False
  1271. # This needs to be undone at the end to prevent holding references to
  1272. # every single object ever created.
  1273. sys.modules[main_mod_name] = main_mod
  1274. stats = None
  1275. try:
  1276. self.shell.savehist()
  1277. if opts.has_key('p'):
  1278. stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
  1279. else:
  1280. if opts.has_key('d'):
  1281. deb = Debugger.Pdb(self.shell.rc.colors)
  1282. # reset Breakpoint state, which is moronically kept
  1283. # in a class
  1284. bdb.Breakpoint.next = 1
  1285. bdb.Breakpoint.bplist = {}
  1286. bdb.Breakpoint.bpbynumber = [None]
  1287. # Set an initial breakpoint to stop execution
  1288. maxtries = 10
  1289. bp = int(opts.get('b',[1])[0])
  1290. checkline = deb.checkline(filename,bp)
  1291. if not checkline:
  1292. for bp in range(bp+1,bp+maxtries+1):
  1293. if deb.checkline(filename,bp):
  1294. break
  1295. else:
  1296. msg = ("\nI failed to find a valid line to set "
  1297. "a breakpoint\n"
  1298. "after trying up to line: %s.\n"
  1299. "Please set a valid breakpoint manually "
  1300. "with the -b option." % bp)
  1301. error(msg)
  1302. return
  1303. # if we find a good linenumber, set the breakpoint
  1304. deb.do_break('%s:%s' % (filename,bp))
  1305. # Start file run
  1306. print "NOTE: Enter 'c' at the",
  1307. print "%s prompt to start your script." % deb.prompt
  1308. try:
  1309. deb.run('execfile("%s")' % filename,prog_ns)
  1310. except:
  1311. etype, value, tb = sys.exc_info()
  1312. # Skip three frames in the traceback: the %run one,
  1313. # one inside bdb.py, and the command-line typed by the
  1314. # user (run by exec in pdb itself).
  1315. self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
  1316. else:
  1317. if runner is None:
  1318. runner = self.shell.safe_execfile
  1319. if opts.has_key('t'):
  1320. # timed execution
  1321. try:
  1322. nruns = int(opts['N'][0])
  1323. if nruns < 1:
  1324. error('Number of runs must be >=1')
  1325. return
  1326. except (KeyError):
  1327. nruns = 1
  1328. if nruns == 1:
  1329. t0 = clock2()
  1330. runner(filename,prog_ns,prog_ns,
  1331. exit_ignore=exit_ignore)
  1332. t1 = clock2()
  1333. t_usr = t1[0]-t0[0]
  1334. t_sys = t1[1]-t1[1]
  1335. print "\nIPython CPU timings (estimated):"
  1336. print " User : %10s s." % t_usr
  1337. print " System: %10s s." % t_sys
  1338. else:
  1339. runs = range(nruns)
  1340. t0 = clock2()
  1341. for nr in runs:
  1342. runner(filename,prog_ns,prog_ns,
  1343. exit_ignore=exit_ignore)
  1344. t1 = clock2()
  1345. t_usr = t1[0]-t0[0]
  1346. t_sys = t1[1]-t1[1]
  1347. print "\nIPython CPU timings (estimated):"
  1348. print "Total runs performed:",nruns
  1349. print " Times : %10s %10s" % ('Total','Per run')
  1350. print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
  1351. print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
  1352. else:
  1353. # regular execution
  1354. runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
  1355. if opts.has_key('i'):
  1356. self.shell.user_ns['__name__'] = __name__save
  1357. else:
  1358. # update IPython interactive namespace
  1359. del prog_ns['__name__']
  1360. self.shell.user_ns.update(prog_ns)
  1361. finally:
  1362. # Ensure key global structures are restored
  1363. sys.argv = save_argv
  1364. if restore_main:
  1365. sys.modules['__main__'] = restore_main
  1366. else:
  1367. # Remove from sys.modules the reference to main_mod we'd
  1368. # added. Otherwise it will trap references to objects
  1369. # contained therein.
  1370. del sys.modules[main_mod_name]
  1371. self.shell.reloadhist()
  1372. return stats
  1373. def magic_runlog(self, parameter_s =''):
  1374. """Run files as logs.
  1375. Usage:\\
  1376. %runlog file1 file2 ...
  1377. Run the named files (treating them as log files) in sequence inside
  1378. the interpreter, and return to the prompt. This is much slower than
  1379. %run because each line is executed in a try/except block, but it
  1380. allows running files with syntax errors in them.
  1381. Normally IPython will guess when a file is one of its own logfiles, so
  1382. you can typically use %run even for logs. This shorthand allows you to
  1383. force any file to be treated as a log file."""
  1384. for f in parameter_s.split():
  1385. self.shell.safe_execfile(f,self.shell.user_ns,
  1386. self.shell.user_ns,islog=1)
  1387. @testdec.skip_doctest
  1388. def magic_timeit(self, parameter_s =''):
  1389. """Time execution of a Python statement or expression
  1390. Usage:\\
  1391. %timeit [-n<N> -r<R> [-t|-c]] statement
  1392. Time execution of a Python statement or expression using the timeit
  1393. module.
  1394. Options:
  1395. -n<N>: execute the given statement <N> times in a loop. If this value
  1396. is not given, a fitting value is chosen.
  1397. -r<R>: repeat the loop iteration <R> times and take the best result.
  1398. Default: 3
  1399. -t: use time.time to measure the time, which is the default on Unix.
  1400. This function measures wall time.
  1401. -c: use time.clock to measure the time, which is the default on
  1402. Windows and measures wall time. On Unix, resource.getrusage is used
  1403. instead and returns the CPU user time.
  1404. -p<P>: use a precision of <P> digits to display the timing result.
  1405. Default: 3
  1406. Examples:
  1407. In [1]: %timeit pass
  1408. 10000000 loops, best of 3: 53.3 ns per loop
  1409. In [2]: u = None
  1410. In [3]: %timeit u is None
  1411. 10000000 loops, best of 3: 184 ns per loop
  1412. In [4]: %timeit -r 4 u == None
  1413. 1000000 loops, best of 4: 242 ns per loop
  1414. In [5]: import time
  1415. In [6]: %timeit -n1 time.sleep(2)
  1416. 1 loops, best of 3: 2 s per loop
  1417. The times reported by %timeit will be slightly higher than those
  1418. reported by the timeit.py script when variables are accessed. This is
  1419. due to the fact that %timeit executes the statement in the namespace
  1420. of the shell, compared with timeit.py, which uses a single setup
  1421. statement to import function or create variables. Generally, the bias
  1422. does not matter as long as results from timeit.py are not mixed with
  1423. those from %timeit."""
  1424. import timeit
  1425. import math
  1426. units = [u"s", u"ms", u"\xb5s", u"ns"]
  1427. scaling = [1, 1e3, 1e6, 1e9]
  1428. opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
  1429. posix=False)
  1430. if stmt == "":
  1431. return
  1432. timefunc = timeit.default_timer
  1433. number = int(getattr(opts, "n", 0))
  1434. repeat = int(getattr(opts, "r", timeit.default_repeat))
  1435. precision = int(getattr(opts, "p", 3))
  1436. if hasattr(opts, "t"):
  1437. timefunc = time.time
  1438. if hasattr(opts, "c"):
  1439. timefunc = clock
  1440. timer = timeit.Timer(timer=timefunc)
  1441. # this code has tight coupling to the inner workings of timeit.Timer,
  1442. # but is there a better way to achieve that the code stmt has access
  1443. # to the shell namespace?
  1444. src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
  1445. 'setup': "pass"}
  1446. # Track compilation time so it can be reported if too long
  1447. # Minimum time above which compilation time will be reported
  1448. tc_min = 0.1
  1449. t0 = clock()
  1450. code = compile(src, "<magic-timeit>", "exec")
  1451. tc = clock()-t0
  1452. ns = {}
  1453. exec code in self.shell.user_ns, ns
  1454. timer.inner = ns["inner"]
  1455. if number == 0:
  1456. # determine number so that 0.2 <= total time < 2.0
  1457. number = 1
  1458. for i in range(1, 10):
  1459. number *= 10
  1460. if timer.timeit(number) >= 0.2:
  1461. break
  1462. best = min(timer.repeat(repeat, number)) / number
  1463. if best > 0.0:
  1464. order = min(-int(math.floor(math.log10(best)) // 3), 3)
  1465. else:
  1466. order = 3
  1467. print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
  1468. precision,
  1469. best * scaling[order],
  1470. units[order])
  1471. if tc > tc_min:
  1472. print "Compiler time: %.2f s" % tc
  1473. @testdec.skip_doctest
  1474. def magic_time(self,parameter_s = ''):
  1475. """Time execution of a Python statement or expression.
  1476. The CPU and wall clock times are printed, and the value of the
  1477. expression (if any) is returned. Note that under Win32, system time
  1478. is always reported as 0, since it can not be measured.
  1479. This function provides very basic timing functionality. In Python
  1480. 2.3, the timeit module offers more control and sophistication, so this
  1481. could be rewritten to use it (patches welcome).
  1482. Some examples:
  1483. In [1]: time 2**128
  1484. CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
  1485. Wall time: 0.00
  1486. Out[1]: 340282366920938463463374607431768211456L
  1487. In [2]: n = 1000000
  1488. In [3]: time sum(range(n))
  1489. CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
  1490. Wall time: 1.37
  1491. Out[3]: 499999500000L
  1492. In [4]: time print 'hello world'
  1493. hello world
  1494. CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
  1495. Wall time: 0.00
  1496. Note that the time needed by Python to compile the given expression
  1497. will be reported if it is more than 0.1s. In this example, the
  1498. actual exponentiation is done by Python at compilation time, so while
  1499. the expression can take a noticeable amount of time to compute, that
  1500. time is purely due to the compilation:
  1501. In [5]: time 3**9999;
  1502. CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
  1503. Wall time: 0.00 s
  1504. In [6]: time 3**999999;
  1505. CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
  1506. Wall time: 0.00 s
  1507. Compiler : 0.78 s
  1508. """
  1509. # fail immediately if the given expression can't be compiled
  1510. expr = self.shell.prefilter(parameter_s,False)
  1511. # Minimum time above which compilation time will be reported
  1512. tc_min = 0.1
  1513. try:
  1514. mode = 'eval'
  1515. t0 = clock()
  1516. code = compile(expr,'<timed eval>',mode)
  1517. tc = clock()-t0
  1518. except SyntaxError:
  1519. mode = 'exec'
  1520. t0 = clock()
  1521. code = compile(expr,'<timed exec>',mode)
  1522. tc = clock()-t0
  1523. # skew measurement as little as possible
  1524. glob = self.shell.user_ns
  1525. clk = clock2
  1526. wtime = time.time
  1527. # time execution
  1528. wall_st = wtime()
  1529. if mode=='eval':
  1530. st = clk()
  1531. out = eval(code,glob)
  1532. end = clk()
  1533. else:
  1534. st = clk()
  1535. exec code in glob
  1536. end = clk()
  1537. out = None
  1538. wall_end = wtime()
  1539. # Compute actual times and report
  1540. wall_time = wall_end-wall_st
  1541. cpu_user = end[0]-st[0]
  1542. cpu_sys = end[1]-st[1]
  1543. cpu_tot = cpu_user+cpu_sys
  1544. print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
  1545. (cpu_user,cpu_sys,cpu_tot)
  1546. print "Wall time: %.2f s" % wall_time
  1547. if tc > tc_min:
  1548. print "Compiler : %.2f s" % tc
  1549. return out
  1550. @testdec.skip_doctest
  1551. def magic_macro(self,parameter_s = ''):
  1552. """Define a set of input lines as a macro for future re-execution.
  1553. Usage:\\
  1554. %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
  1555. Options:
  1556. -r: use 'raw' input. By default, the 'processed' history is used,
  1557. so that magics are loaded in their transformed version to valid
  1558. Python. If this option is given, the raw input as typed as the
  1559. command line is used instead.
  1560. This will define a global variable called `name` which is a string
  1561. made of joining the slices and lines you specify (n1,n2,... numbers
  1562. above) from your input history into a single string. This variable
  1563. acts like an automatic function which re-executes those lines as if
  1564. you had typed them. You just type 'name' at the prompt and the code
  1565. executes.
  1566. The notation for indicating number ranges is: n1-n2 means 'use line
  1567. numbers n1,...n2' (the endpoint is included). That is, '5-7' means
  1568. using the lines numbered 5,6 and 7.
  1569. Note: as a 'hidden' feature, you can also use traditional python slice
  1570. notation, where N:M means numbers N through M-1.
  1571. For example, if your history contains (%hist prints it):
  1572. 44: x=1
  1573. 45: y=3
  1574. 46: z=x+y
  1575. 47: print x
  1576. 48: a=5
  1577. 49: print 'x',x,'y',y
  1578. you can create a macro with lines 44 through 47 (included) and line 49
  1579. called my_macro with:
  1580. In [55]: %macro my_macro 44-47 49
  1581. Now, typing `my_macro` (without quotes) will re-execute all this code
  1582. in one pass.
  1583. You don't need to give the line-numbers in order, and any given line
  1584. number can appear multiple times. You can assemble macros with any
  1585. lines from your input history in any order.
  1586. The macro is a simple object which holds its value in an attribute,
  1587. but IPython's display system checks for macros and executes them as
  1588. code instead of printing them when you type their name.
  1589. You can view a macro's contents by explicitly printing it with:
  1590. 'print macro_name'.
  1591. For one-off cases which DON'T contain magic function calls in them you
  1592. can obtain similar results by explicitly executing slices from your
  1593. input history with:
  1594. In [60]: exec In[44:48]+In[49]"""
  1595. opts,args = self.parse_options(parameter_s,'r',mode='list')
  1596. if not args:
  1597. macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
  1598. macs.sort()
  1599. return macs
  1600. if len(args) == 1:
  1601. raise UsageError(
  1602. "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
  1603. name,ranges = args[0], args[1:]
  1604. #print 'rng',ranges # dbg
  1605. lines = self.extract_input_slices(ranges,opts.has_key('r'))
  1606. macro = Macro(lines)
  1607. self.shell.user_ns.update({name:macro})
  1608. print 'Macro `%s` created. To execute, type its name (without quotes).' % name
  1609. print 'Macro contents:'
  1610. print macro,
  1611. def magic_save(self,parameter_s = ''):
  1612. """Save a set of lines to a given filename.
  1613. Usage:\\
  1614. %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
  1615. Options:
  1616. -r: use 'raw' input. By default, the 'processed' history is used,
  1617. so that magics are loaded in their transformed version to valid
  1618. Python. If this option is given, the raw input as typed as the
  1619. command line is used instead.
  1620. This function uses the same syntax as %macro for line extraction, but
  1621. instead of creating a macro it saves the resulting string to the
  1622. filename you specify.
  1623. It adds a '.py' extension to the file if you don't do so yourself, and
  1624. it asks for confirmation before overwriting existing files."""
  1625. opts,args = self.parse_options(parameter_s,'r',mode='list')
  1626. fname,ranges = args[0], args[1:]
  1627. if not fname.endswith('.py'):
  1628. fname += '.py'
  1629. if os.path.isfile(fname):
  1630. ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
  1631. if ans.lower() not in ['y','yes']:
  1632. print 'Operation cancelled.'
  1633. return
  1634. cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
  1635. f = file(fname,'w')
  1636. f.write(cmds)
  1637. f.close()
  1638. print 'The following commands were written to file `%s`:' % fname
  1639. print cmds
  1640. def _edit_macro(self,mname,macro):
  1641. """open an editor with the macro data in a file"""
  1642. filename = self.shell.mktempfile(macro.value)
  1643. self.shell.hooks.editor(filename)
  1644. # and make a new macro object, to replace the old one
  1645. mfile = open(filename)
  1646. mvalue = mfile.read()
  1647. mfile.close()
  1648. self.shell.user_ns[mname] = Macro(mvalue)
  1649. def magic_ed(self,parameter_s=''):
  1650. """Alias to %edit."""
  1651. return self.magic_edit(parameter_s)
  1652. @testdec.skip_doctest
  1653. def magic_edit(self,parameter_s='',last_call=['','']):
  1654. """Bring up an editor and execute the resulting code.
  1655. Usage:
  1656. %edit [options] [args]
  1657. %edit runs IPython's editor hook. The default version of this hook is
  1658. set to call the __IPYTHON__.rc.editor command. This is read from your
  1659. environment variable $EDITOR. If this isn't found, it will default to
  1660. vi under Linux/Unix and to notepad under Windows. See the end of this
  1661. docstring for how to change the editor hook.
  1662. You can also set the value of this editor via the command line option
  1663. '-editor' or in your ipythonrc file. This is useful if you wish to use
  1664. specifically for IPython an editor different from your typical default
  1665. (and for Windows users who typically don't set environment variables).
  1666. This command allows you to conveniently edit multi-line code right in
  1667. your IPython session.
  1668. If called without arguments, %edit opens up an empty editor with a
  1669. temporary file and will execute the contents of this file when you
  1670. close it (don't forget to save it!).
  1671. Options:
  1672. -n <number>: open the editor at a specified line number. By default,
  1673. the IPython editor hook uses the unix syntax 'editor +N filename', but
  1674. you can configure this by providing your own modified hook if your
  1675. favorite editor supports line-number specifications with a different
  1676. syntax.
  1677. -p: this will call the editor with the same data as the previous time
  1678. it was used, regardless of how long ago (in your current session) it
  1679. was.
  1680. -r: use 'raw' input. This option only applies to input taken from the
  1681. user's history. By default, the 'processed' history is used, so that
  1682. magics are loaded in their transformed version to valid Python. If
  1683. this option is given, the raw input as typed as the command line is
  1684. used instead. When you exit the editor, it will be executed by
  1685. IPython's own processor.
  1686. -x: do not execute the edited code immediately upon exit. This is
  1687. mainly useful if you are editing programs which need to be called with
  1688. command line arguments, which you can then do using %run.
  1689. Arguments:
  1690. If arguments are given, the following possibilites exist:
  1691. - The arguments are numbers or pairs of colon-separated numbers (like
  1692. 1 4:8 9). These are interpreted as lines of previous input to be
  1693. loaded into the editor. The syntax is the same of the %macro command.
  1694. - If the argument doesn't start with a number, it is evaluated as a
  1695. variable and its contents loaded into the editor. You can thus edit
  1696. any string which contains python code (including the result of
  1697. previous edits).
  1698. - If the argument is the name of an object (other than a string),
  1699. IPython will try to locate the file where it was defined and open the
  1700. editor at the point where it is defined. You can use `%edit function`
  1701. to load an editor exactly at the point where 'function' is defined,
  1702. edit it and have the file be executed automatically.
  1703. If the object is a macro (see %macro for details), this opens up your
  1704. specified editor with a temporary file containing the macro's data.
  1705. Upon exit, the macro is reloaded with the contents of the file.
  1706. Note: opening at an exact line is only supported under Unix, and some
  1707. editors (like kedit and gedit up to Gnome 2.8) do not understand the
  1708. '+NUMBER' parameter necessary for this feature. Good editors like
  1709. (X)Emacs, vi, jed, pico and joe all do.
  1710. - If the argument is not found as a variable, IPython will look for a
  1711. file with that name (adding .py if necessary) and load it into the
  1712. editor. It will execute its contents with execfile() when you exit,
  1713. loading any code in the file into your interactive namespace.
  1714. After executing your code, %edit will return as output the code you
  1715. typed in the editor (except when it was an existing file). This way
  1716. you can reload the code in further invocations of %edit as a variable,
  1717. via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
  1718. the output.
  1719. Note that %edit is also available through the alias %ed.
  1720. This is an example of creating a simple function inside the editor and
  1721. then modifying it. First, start up the editor:
  1722. In [1]: ed
  1723. Editing... done. Executing edited code...
  1724. Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
  1725. We can then call the function foo():
  1726. In [2]: foo()
  1727. foo() was defined in an editing session
  1728. Now we edit foo. IPython automatically loads the editor with the
  1729. (temporary) file where foo() was previously defined:
  1730. In [3]: ed foo
  1731. Editing... done. Executing edited code...
  1732. And if we call foo() again we get the modified version:
  1733. In [4]: foo()
  1734. foo() has now been changed!
  1735. Here is an example of how to edit a code snippet successive
  1736. times. First we call the editor:
  1737. In [5]: ed
  1738. Editing... done. Executing edited code...
  1739. hello
  1740. Out[5]: "print 'hello'n"
  1741. Now we call it again with the previous output (stored in _):
  1742. In [6]: ed _
  1743. Editing... done. Executing edited code...
  1744. hello world
  1745. Out[6]: "print 'hello world'n"
  1746. Now we call it with the output #8 (stored in _8, also as Out[8]):
  1747. In [7]: ed _8
  1748. Editing... done. Executing edited code...
  1749. hello again
  1750. Out[7]: "print 'hello again'n"
  1751. Changing the default editor hook:
  1752. If you wish to write your own editor hook, you can put it in a
  1753. configuration file which you load at startup time. The default hook
  1754. is defined in the IPython.hooks module, and you can use that as a
  1755. starting example for further modifications. That file also has
  1756. general instructions on how to set a new hook for use once you've
  1757. defined it."""
  1758. # FIXME: This function has become a convoluted mess. It needs a
  1759. # ground-up rewrite with clean, simple logic.
  1760. def make_filename(arg):
  1761. "Make a filename from the given args"
  1762. try:
  1763. filename = get_py_filename(arg)
  1764. except IOError:
  1765. if args.endswith('.py'):
  1766. filename = arg
  1767. else:
  1768. filename = None
  1769. return filename
  1770. # custom exceptions
  1771. class DataIsObject(Exception): pass
  1772. opts,args = self.parse_options(parameter_s,'prxn:')
  1773. # Set a few locals from the options for convenience:
  1774. opts_p = opts.has_key('p')
  1775. opts_r = opts.has_key('r')
  1776. # Default line number value
  1777. lineno = opts.get('n',None)
  1778. if opts_p:
  1779. args = '_%s' % last_call[0]
  1780. if not self.shell.user_ns.has_key(args):
  1781. args = last_call[1]
  1782. # use last_call to remember the state of the previous call, but don't
  1783. # let it be clobbered by successive '-p' calls.
  1784. try:
  1785. last_call[0] = self.shell.outputcache.prompt_count
  1786. if not opts_p:
  1787. last_call[1] = parameter_s
  1788. except:
  1789. pass
  1790. # by default this is done with temp files, except when the given
  1791. # arg is a filename
  1792. use_temp = 1
  1793. if re.match(r'\d',args):
  1794. # Mode where user specifies ranges of lines, like in %macro.
  1795. # This means that you can't edit files whose names begin with
  1796. # numbers this way. Tough.
  1797. ranges = args.split()
  1798. data = ''.join(self.extract_input_slices(ranges,opts_r))
  1799. elif args.endswith('.py'):
  1800. filename = make_filename(args)
  1801. data = ''
  1802. use_temp = 0
  1803. elif args:
  1804. try:
  1805. # Load the parameter given as a variable. If not a string,
  1806. # process it as an object instead (below)
  1807. #print '*** args',args,'type',type(args) # dbg
  1808. data = eval(args,self.shell.user_ns)
  1809. if not type(data) in StringTypes:
  1810. raise DataIsObject
  1811. except (NameError,SyntaxError):
  1812. # given argument is not a variable, try as a filename
  1813. filename = make_filename(args)
  1814. if filename is None:
  1815. warn("Argument given (%s) can't be found as a variable "
  1816. "or as a filename." % args)
  1817. return
  1818. data = ''
  1819. use_temp = 0
  1820. except DataIsObject:
  1821. # macros have a special edit function
  1822. if isinstance(data,Macro):
  1823. self._edit_macro(args,data)
  1824. return
  1825. # For objects, try to edit the file where they are defined
  1826. try:
  1827. filename = inspect.getabsfile(data)
  1828. if 'fakemodule' in filename.lower() and inspect.isclass(data):
  1829. # class created by %edit? Try to find source
  1830. # by looking for method definitions instead, the
  1831. # __module__ in those classes is FakeModule.
  1832. attrs = [getattr(data, aname) for aname in dir(data)]
  1833. for attr in attrs:
  1834. if not inspect.ismethod(attr):
  1835. continue
  1836. filename = inspect.getabsfile(attr)
  1837. if filename and 'fakemodule' not in filename.lower():
  1838. # change the attribute to be the edit target instead
  1839. data = attr
  1840. break
  1841. datafile = 1
  1842. except TypeError:
  1843. filename = make_filename(args)
  1844. datafile = 1
  1845. warn('Could not find file where `%s` is defined.\n'
  1846. 'Opening a file named `%s`' % (args,filename))
  1847. # Now, make sure we can actually read the source (if it was in
  1848. # a temp file it's gone by now).
  1849. if datafile:
  1850. try:
  1851. if lineno is None:
  1852. lineno = inspect.getsourcelines(data)[1]
  1853. except IOError:
  1854. filename = make_filename(args)
  1855. if filename is None:
  1856. warn('The file `%s` where `%s` was defined cannot '
  1857. 'be read.' % (filename,data))
  1858. return
  1859. use_temp = 0
  1860. else:
  1861. data = ''
  1862. if use_temp:
  1863. filename = self.shell.mktempfile(data)
  1864. print 'IPython will make a temporary file named:',filename
  1865. # do actual editing here
  1866. print 'Editing...',
  1867. sys.stdout.flush()
  1868. self.shell.hooks.editor(filename,lineno)
  1869. if opts.has_key('x'): # -x prevents actual execution
  1870. print
  1871. else:
  1872. print 'done. Executing edited code...'
  1873. if opts_r:
  1874. self.shell.runlines(file_read(filename))
  1875. else:
  1876. self.shell.safe_execfile(filename,self.shell.user_ns,
  1877. self.shell.user_ns)
  1878. if use_temp:
  1879. try:
  1880. return open(filename).read()
  1881. except IOError,msg:
  1882. if msg.filename == filename:
  1883. warn('File not found. Did you forget to save?')
  1884. return
  1885. else:
  1886. self.shell.showtraceback()
  1887. def magic_xmode(self,parameter_s = ''):
  1888. """Switch modes for the exception handlers.
  1889. Valid modes: Plain, Context and Verbose.
  1890. If called without arguments, acts as a toggle."""
  1891. def xmode_switch_err(name):
  1892. warn('Error changing %s exception modes.\n%s' %
  1893. (name,sys.exc_info()[1]))
  1894. shell = self.shell
  1895. new_mode = parameter_s.strip().capitalize()
  1896. try:
  1897. shell.InteractiveTB.set_mode(mode=new_mode)
  1898. print 'Exception reporting mode:',shell.InteractiveTB.mode
  1899. except:
  1900. xmode_switch_err('user')
  1901. # threaded shells use a special handler in sys.excepthook
  1902. if shell.isthreaded:
  1903. try:
  1904. shell.sys_excepthook.set_mode(mode=new_mode)
  1905. except:
  1906. xmode_switch_err('threaded')
  1907. def magic_colors(self,parameter_s = ''):
  1908. """Switch color scheme for prompts, info system and exception handlers.
  1909. Currently implemented schemes: NoColor, Linux, LightBG.
  1910. Color scheme names are not case-sensitive."""
  1911. def color_switch_err(name):
  1912. warn('Error changing %s color schemes.\n%s' %
  1913. (name,sys.exc_info()[1]))
  1914. new_scheme = parameter_s.strip()
  1915. if not new_scheme:
  1916. raise UsageError(
  1917. "%colors: you must specify a color scheme. See '%colors?'")
  1918. return
  1919. # local shortcut
  1920. shell = self.shell
  1921. import IPython.rlineimpl as readline
  1922. if not readline.have_readline and sys.platform == "win32":
  1923. msg = """\
  1924. Proper color support under MS Windows requires the pyreadline library.
  1925. You can find it at:
  1926. http://ipython.scipy.org/moin/PyReadline/Intro
  1927. Gary's readline needs the ctypes module, from:
  1928. http://starship.python.net/crew/theller/ctypes
  1929. (Note that ctypes is already part of Python versions 2.5 and newer).
  1930. Defaulting color scheme to 'NoColor'"""
  1931. new_scheme = 'NoColor'
  1932. warn(msg)
  1933. # readline option is 0
  1934. if not shell.has_readline:
  1935. new_scheme = 'NoColor'
  1936. # Set prompt colors
  1937. try:
  1938. shell.outputcache.set_colors(new_scheme)
  1939. except:
  1940. color_switch_err('prompt')
  1941. else:
  1942. shell.rc.colors = \
  1943. shell.outputcache.color_table.active_scheme_name
  1944. # Set exception colors
  1945. try:
  1946. shell.InteractiveTB.set_colors(scheme = new_scheme)
  1947. shell.SyntaxTB.set_colors(scheme = new_scheme)
  1948. except:
  1949. color_switch_err('exception')
  1950. # threaded shells use a verbose traceback in sys.excepthook
  1951. if shell.isthreaded:
  1952. try:
  1953. shell.sys_excepthook.set_colors(scheme=new_scheme)
  1954. except:
  1955. color_switch_err('system exception handler')
  1956. # Set info (for 'object?') colors
  1957. if shell.rc.color_info:
  1958. try:
  1959. shell.inspector.set_active_scheme(new_scheme)
  1960. except:
  1961. color_switch_err('object inspector')
  1962. else:
  1963. shell.inspector.set_active_scheme('NoColor')
  1964. def magic_color_info(self,parameter_s = ''):
  1965. """Toggle color_info.
  1966. The color_info configuration parameter controls whether colors are
  1967. used for displaying object details (by things like %psource, %pfile or
  1968. the '?' system). This function toggles this value with each call.
  1969. Note that unless you have a fairly recent pager (less works better
  1970. than more) in your system, using colored object information displays
  1971. will not work properly. Test it and see."""
  1972. self.shell.rc.color_info = 1 - self.shell.rc.color_info
  1973. self.magic_colors(self.shell.rc.colors)
  1974. print 'Object introspection functions have now coloring:',
  1975. print ['OFF','ON'][self.shell.rc.color_info]
  1976. def magic_Pprint(self, parameter_s=''):
  1977. """Toggle pretty printing on/off."""
  1978. self.shell.rc.pprint = 1 - self.shell.rc.pprint
  1979. print 'Pretty printing has been turned', \
  1980. ['OFF','ON'][self.shell.rc.pprint]
  1981. def magic_exit(self, parameter_s=''):
  1982. """Exit IPython, confirming if configured to do so.
  1983. You can configure whether IPython asks for confirmation upon exit by
  1984. setting the confirm_exit flag in the ipythonrc file."""
  1985. self.shell.exit()
  1986. def magic_quit(self, parameter_s=''):
  1987. """Exit IPython, confirming if configured to do so (like %exit)"""
  1988. self.shell.exit()
  1989. def magic_Exit(self, parameter_s=''):
  1990. """Exit IPython without confirmation."""
  1991. self.shell.ask_exit()
  1992. #......................................................................
  1993. # Functions to implement unix shell-type things
  1994. @testdec.skip_doctest
  1995. def magic_alias(self, parameter_s = ''):
  1996. """Define an alias for a system command.
  1997. '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
  1998. Then, typing 'alias_name params' will execute the system command 'cmd
  1999. params' (from your underlying operating system).
  2000. Aliases have lower precedence than magic functions and Python normal
  2001. variables, so if 'foo' is both a Python variable and an alias, the
  2002. alias can not be executed until 'del foo' removes the Python variable.
  2003. You can use the %l specifier in an alias definition to represent the
  2004. whole line when the alias is called. For example:
  2005. In [2]: alias all echo "Input in brackets: <%l>"
  2006. In [3]: all hello world
  2007. Input in brackets: <hello world>
  2008. You can also define aliases with parameters using %s specifiers (one
  2009. per parameter):
  2010. In [1]: alias parts echo first %s second %s
  2011. In [2]: %parts A B
  2012. first A second B
  2013. In [3]: %parts A
  2014. Incorrect number of arguments: 2 expected.
  2015. parts is an alias to: 'echo first %s second %s'
  2016. Note that %l and %s are mutually exclusive. You can only use one or
  2017. the other in your aliases.
  2018. Aliases expand Python variables just like system calls using ! or !!
  2019. do: all expressions prefixed with '$' get expanded. For details of
  2020. the semantic rules, see PEP-215:
  2021. http://www.python.org/peps/pep-0215.html. This is the library used by
  2022. IPython for variable expansion. If you want to access a true shell
  2023. variable, an extra $ is necessary to prevent its expansion by IPython:
  2024. In [6]: alias show echo
  2025. In [7]: PATH='A Python string'
  2026. In [8]: show $PATH
  2027. A Python string
  2028. In [9]: show $$PATH
  2029. /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
  2030. You can use the alias facility to acess all of $PATH. See the %rehash
  2031. and %rehashx functions, which automatically create aliases for the
  2032. contents of your $PATH.
  2033. If called with no parameters, %alias prints the current alias table."""
  2034. par = parameter_s.strip()
  2035. if not par:
  2036. stored = self.db.get('stored_aliases', {} )
  2037. atab = self.shell.alias_table
  2038. aliases = atab.keys()
  2039. aliases.sort()
  2040. res = []
  2041. showlast = []
  2042. for alias in aliases:
  2043. special = False
  2044. try:
  2045. tgt = atab[alias][1]
  2046. except (TypeError, AttributeError):
  2047. # unsubscriptable? probably a callable
  2048. tgt = atab[alias]
  2049. special = True
  2050. # 'interesting' aliases
  2051. if (alias in stored or
  2052. special or
  2053. alias.lower() != os.path.splitext(tgt)[0].lower() or
  2054. ' ' in tgt):
  2055. showlast.append((alias, tgt))
  2056. else:
  2057. res.append((alias, tgt ))
  2058. # show most interesting aliases last
  2059. res.extend(showlast)
  2060. print "Total number of aliases:",len(aliases)
  2061. return res
  2062. try:
  2063. alias,cmd = par.split(None,1)
  2064. except:
  2065. print OInspect.getdoc(self.magic_alias)
  2066. else:
  2067. nargs = cmd.count('%s')
  2068. if nargs>0 and cmd.find('%l')>=0:
  2069. error('The %s and %l specifiers are mutually exclusive '
  2070. 'in alias definitions.')
  2071. else: # all looks OK
  2072. self.shell.alias_table[alias] = (nargs,cmd)
  2073. self.shell.alias_table_validate(verbose=0)
  2074. # end magic_alias
  2075. def magic_unalias(self, parameter_s = ''):
  2076. """Remove an alias"""
  2077. aname = parameter_s.strip()
  2078. if aname in self.shell.alias_table:
  2079. del self.shell.alias_table[aname]
  2080. stored = self.db.get('stored_aliases', {} )
  2081. if aname in stored:
  2082. print "Removing %stored alias",aname
  2083. del stored[aname]
  2084. self.db['stored_aliases'] = stored
  2085. def magic_rehashx(self, parameter_s = ''):
  2086. """Update the alias table with all executable files in $PATH.
  2087. This version explicitly checks that every entry in $PATH is a file
  2088. with execute access (os.X_OK), so it is much slower than %rehash.
  2089. Under Windows, it checks executability as a match agains a
  2090. '|'-separated string of extensions, stored in the IPython config
  2091. variable win_exec_ext. This defaults to 'exe|com|bat'.
  2092. This function also resets the root module cache of module completer,
  2093. used on slow filesystems.
  2094. """
  2095. ip = self.api
  2096. # for the benefit of module completer in ipy_completers.py
  2097. del ip.db['rootmodules']
  2098. path = [os.path.abspath(os.path.expanduser(p)) for p in
  2099. os.environ.get('PATH','').split(os.pathsep)]
  2100. path = filter(os.path.isdir,path)
  2101. alias_table = self.shell.alias_table
  2102. syscmdlist = []
  2103. if os.name == 'posix':
  2104. isexec = lambda fname:os.path.isfile(fname) and \
  2105. os.access(fname,os.X_OK)
  2106. else:
  2107. try:
  2108. winext = os.environ['pathext'].replace(';','|').replace('.','')
  2109. except KeyError:
  2110. winext = 'exe|com|bat|py'
  2111. if 'py' not in winext:
  2112. winext += '|py'
  2113. execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
  2114. isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
  2115. savedir = os.getcwd()
  2116. try:
  2117. # write the whole loop for posix/Windows so we don't have an if in
  2118. # the innermost part
  2119. if os.name == 'posix':
  2120. for pdir in path:
  2121. os.chdir(pdir)
  2122. for ff in os.listdir(pdir):
  2123. if isexec(ff) and ff not in self.shell.no_alias:
  2124. # each entry in the alias table must be (N,name),
  2125. # where N is the number of positional arguments of the
  2126. # alias.
  2127. alias_table[ff] = (0,ff)
  2128. syscmdlist.append(ff)
  2129. else:
  2130. for pdir in path:
  2131. os.chdir(pdir)
  2132. for ff in os.listdir(pdir):
  2133. base, ext = os.path.splitext(ff)
  2134. if isexec(ff) and base.lower() not in self.shell.no_alias:
  2135. if ext.lower() == '.exe':
  2136. ff = base
  2137. alias_table[base.lower()] = (0,ff)
  2138. syscmdlist.append(ff)
  2139. # Make sure the alias table doesn't contain keywords or builtins
  2140. self.shell.alias_table_validate()
  2141. # Call again init_auto_alias() so we get 'rm -i' and other
  2142. # modified aliases since %rehashx will probably clobber them
  2143. # no, we don't want them. if %rehashx clobbers them, good,
  2144. # we'll probably get better versions
  2145. # self.shell.init_auto_alias()
  2146. db = ip.db
  2147. db['syscmdlist'] = syscmdlist
  2148. finally:
  2149. os.chdir(savedir)
  2150. def magic_pwd(self, parameter_s = ''):
  2151. """Return the current working directory path."""
  2152. return os.getcwd()
  2153. def magic_cd(self, parameter_s=''):
  2154. """Change the current working directory.
  2155. This command automatically maintains an internal list of directories
  2156. you visit during your IPython session, in the variable _dh. The
  2157. command %dhist shows this history nicely formatted. You can also
  2158. do 'cd -<tab>' to see directory history conveniently.
  2159. Usage:
  2160. cd 'dir': changes to directory 'dir'.
  2161. cd -: changes to the last visited directory.
  2162. cd -<n>: changes to the n-th directory in the directory history.
  2163. cd --foo: change to directory that matches 'foo' in history
  2164. cd -b <bookmark_name>: jump to a bookmark set by %bookmark
  2165. (note: cd <bookmark_name> is enough if there is no
  2166. directory <bookmark_name>, but a bookmark with the name exists.)
  2167. 'cd -b <tab>' allows you to tab-complete bookmark names.
  2168. Options:
  2169. -q: quiet. Do not print the working directory after the cd command is
  2170. executed. By default IPython's cd command does print this directory,
  2171. since the default prompts do not display path information.
  2172. Note that !cd doesn't work for this purpose because the shell where
  2173. !command runs is immediately discarded after executing 'command'."""
  2174. parameter_s = parameter_s.strip()
  2175. #bkms = self.shell.persist.get("bookmarks",{})
  2176. oldcwd = os.getcwd()
  2177. numcd = re.match(r'(-)(\d+)$',parameter_s)
  2178. # jump in directory history by number
  2179. if numcd:
  2180. nn = int(numcd.group(2))
  2181. try:
  2182. ps = self.shell.user_ns['_dh'][nn]
  2183. except IndexError:
  2184. print 'The requested directory does not exist in history.'
  2185. return
  2186. else:
  2187. opts = {}
  2188. elif parameter_s.startswith('--'):
  2189. ps = None
  2190. fallback = None
  2191. pat = parameter_s[2:]
  2192. dh = self.shell.user_ns['_dh']
  2193. # first search only by basename (last component)
  2194. for ent in reversed(dh):
  2195. if pat in os.path.basename(ent) and os.path.isdir(ent):
  2196. ps = ent
  2197. break
  2198. if fallback is None and pat in ent and os.path.isdir(ent):
  2199. fallback = ent
  2200. # if we have no last part match, pick the first full path match
  2201. if ps is None:
  2202. ps = fallback
  2203. if ps is None:
  2204. print "No matching entry in directory history"
  2205. return
  2206. else:
  2207. opts = {}
  2208. else:
  2209. #turn all non-space-escaping backslashes to slashes,
  2210. # for c:\windows\directory\names\
  2211. parameter_s = re.sub(r'\\(?! )','/', parameter_s)
  2212. opts,ps = self.parse_options(parameter_s,'qb',mode='string')
  2213. # jump to previous
  2214. if ps == '-':
  2215. try:
  2216. ps = self.shell.user_ns['_dh'][-2]
  2217. except IndexError:
  2218. raise UsageError('%cd -: No previous directory to change to.')
  2219. # jump to bookmark if needed
  2220. else:
  2221. if not os.path.isdir(ps) or opts.has_key('b'):
  2222. bkms = self.db.get('bookmarks', {})
  2223. if bkms.has_key(ps):
  2224. target = bkms[ps]
  2225. print '(bookmark:%s) -> %s' % (ps,target)
  2226. ps = target
  2227. else:
  2228. if opts.has_key('b'):
  2229. raise UsageError("Bookmark '%s' not found. "
  2230. "Use '%%bookmark -l' to see your bookmarks." % ps)
  2231. # at this point ps should point to the target dir
  2232. if ps:
  2233. try:
  2234. os.chdir(os.path.expanduser(ps))
  2235. if self.shell.rc.term_title:
  2236. #print 'set term title:',self.shell.rc.term_title # dbg
  2237. platutils.set_term_title('IPy ' + abbrev_cwd())
  2238. except OSError:
  2239. print sys.exc_info()[1]
  2240. else:
  2241. cwd = os.getcwd()
  2242. dhist = self.shell.user_ns['_dh']
  2243. if oldcwd != cwd:
  2244. dhist.append(cwd)
  2245. self.db['dhist'] = compress_dhist(dhist)[-100:]
  2246. else:
  2247. os.chdir(self.shell.home_dir)
  2248. if self.shell.rc.term_title:
  2249. platutils.set_term_title("IPy ~")
  2250. cwd = os.getcwd()
  2251. dhist = self.shell.user_ns['_dh']
  2252. if oldcwd != cwd:
  2253. dhist.append(cwd)
  2254. self.db['dhist'] = compress_dhist(dhist)[-100:]
  2255. if not 'q' in opts and self.shell.user_ns['_dh']:
  2256. print self.shell.user_ns['_dh'][-1]
  2257. def magic_env(self, parameter_s=''):
  2258. """List environment variables."""
  2259. return os.environ.data
  2260. def magic_pushd(self, parameter_s=''):
  2261. """Place the current dir on stack and change directory.
  2262. Usage:\\
  2263. %pushd ['dirname']
  2264. """
  2265. dir_s = self.shell.dir_stack
  2266. tgt = os.path.expanduser(parameter_s)
  2267. cwd = os.getcwd().replace(self.home_dir,'~')
  2268. if tgt:
  2269. self.magic_cd(parameter_s)
  2270. dir_s.insert(0,cwd)
  2271. return self.magic_dirs()
  2272. def magic_popd(self, parameter_s=''):
  2273. """Change to directory popped off the top of the stack.
  2274. """
  2275. if not self.shell.dir_stack:
  2276. raise UsageError("%popd on empty stack")
  2277. top = self.shell.dir_stack.pop(0)
  2278. self.magic_cd(top)
  2279. print "popd ->",top
  2280. def magic_dirs(self, parameter_s=''):
  2281. """Return the current directory stack."""
  2282. return self.shell.dir_stack
  2283. def magic_dhist(self, parameter_s=''):
  2284. """Print your history of visited directories.
  2285. %dhist -> print full history\\
  2286. %dhist n -> print last n entries only\\
  2287. %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
  2288. This history is automatically maintained by the %cd command, and
  2289. always available as the global list variable _dh. You can use %cd -<n>
  2290. to go to directory number <n>.
  2291. Note that most of time, you should view directory history by entering
  2292. cd -<TAB>.
  2293. """
  2294. dh = self.shell.user_ns['_dh']
  2295. if parameter_s:
  2296. try:
  2297. args = map(int,parameter_s.split())
  2298. except:
  2299. self.arg_err(Magic.magic_dhist)
  2300. return
  2301. if len(args) == 1:
  2302. ini,fin = max(len(dh)-(args[0]),0),len(dh)
  2303. elif len(args) == 2:
  2304. ini,fin = args
  2305. else:
  2306. self.arg_err(Magic.magic_dhist)
  2307. return
  2308. else:
  2309. ini,fin = 0,len(dh)
  2310. nlprint(dh,
  2311. header = 'Directory history (kept in _dh)',
  2312. start=ini,stop=fin)
  2313. @testdec.skip_doctest
  2314. def magic_sc(self, parameter_s=''):
  2315. """Shell capture - execute a shell command and capture its output.
  2316. DEPRECATED. Suboptimal, retained for backwards compatibility.
  2317. You should use the form 'var = !command' instead. Example:
  2318. "%sc -l myfiles = ls ~" should now be written as
  2319. "myfiles = !ls ~"
  2320. myfiles.s, myfiles.l and myfiles.n still apply as documented
  2321. below.
  2322. --
  2323. %sc [options] varname=command
  2324. IPython will run the given command using commands.getoutput(), and
  2325. will then update the user's interactive namespace with a variable
  2326. called varname, containing the value of the call. Your command can
  2327. contain shell wildcards, pipes, etc.
  2328. The '=' sign in the syntax is mandatory, and the variable name you
  2329. supply must follow Python's standard conventions for valid names.
  2330. (A special format without variable name exists for internal use)
  2331. Options:
  2332. -l: list output. Split the output on newlines into a list before
  2333. assigning it to the given variable. By default the output is stored
  2334. as a single string.
  2335. -v: verbose. Print the contents of the variable.
  2336. In most cases you should not need to split as a list, because the
  2337. returned value is a special type of string which can automatically
  2338. provide its contents either as a list (split on newlines) or as a
  2339. space-separated string. These are convenient, respectively, either
  2340. for sequential processing or to be passed to a shell command.
  2341. For example:
  2342. # all-random
  2343. # Capture into variable a
  2344. In [1]: sc a=ls *py
  2345. # a is a string with embedded newlines
  2346. In [2]: a
  2347. Out[2]: 'setup.py\\nwin32_manual_post_install.py'
  2348. # which can be seen as a list:
  2349. In [3]: a.l
  2350. Out[3]: ['setup.py', 'win32_manual_post_install.py']
  2351. # or as a whitespace-separated string:
  2352. In [4]: a.s
  2353. Out[4]: 'setup.py win32_manual_post_install.py'
  2354. # a.s is useful to pass as a single command line:
  2355. In [5]: !wc -l $a.s
  2356. 146 setup.py
  2357. 130 win32_manual_post_install.py
  2358. 276 total
  2359. # while the list form is useful to loop over:
  2360. In [6]: for f in a.l:
  2361. ...: !wc -l $f
  2362. ...:
  2363. 146 setup.py
  2364. 130 win32_manual_post_install.py
  2365. Similiarly, the lists returned by the -l option are also special, in
  2366. the sense that you can equally invoke the .s attribute on them to
  2367. automatically get a whitespace-separated string from their contents:
  2368. In [7]: sc -l b=ls *py
  2369. In [8]: b
  2370. Out[8]: ['setup.py', 'win32_manual_post_install.py']
  2371. In [9]: b.s
  2372. Out[9]: 'setup.py win32_manual_post_install.py'
  2373. In summary, both the lists and strings used for ouptut capture have
  2374. the following special attributes:
  2375. .l (or .list) : value as list.
  2376. .n (or .nlstr): value as newline-separated string.
  2377. .s (or .spstr): value as space-separated string.
  2378. """
  2379. opts,args = self.parse_options(parameter_s,'lv')
  2380. # Try to get a variable name and command to run
  2381. try:
  2382. # the variable name must be obtained from the parse_options
  2383. # output, which uses shlex.split to strip options out.
  2384. var,_ = args.split('=',1)
  2385. var = var.strip()
  2386. # But the the command has to be extracted from the original input
  2387. # parameter_s, not on what parse_options returns, to avoid the
  2388. # quote stripping which shlex.split performs on it.
  2389. _,cmd = parameter_s.split('=',1)
  2390. except ValueError:
  2391. var,cmd = '',''
  2392. # If all looks ok, proceed
  2393. out,err = self.shell.getoutputerror(cmd)
  2394. if err:
  2395. print >> Term.cerr,err
  2396. if opts.has_key('l'):
  2397. out = SList(out.split('\n'))
  2398. else:
  2399. out = LSString(out)
  2400. if opts.has_key('v'):
  2401. print '%s ==\n%s' % (var,pformat(out))
  2402. if var:
  2403. self.shell.user_ns.update({var:out})
  2404. else:
  2405. return out
  2406. def magic_sx(self, parameter_s=''):
  2407. """Shell execute - run a shell command and capture its output.
  2408. %sx command
  2409. IPython will run the given command using commands.getoutput(), and
  2410. return the result formatted as a list (split on '\\n'). Since the
  2411. output is _returned_, it will be stored in ipython's regular output
  2412. cache Out[N] and in the '_N' automatic variables.
  2413. Notes:
  2414. 1) If an input line begins with '!!', then %sx is automatically
  2415. invoked. That is, while:
  2416. !ls
  2417. causes ipython to simply issue system('ls'), typing
  2418. !!ls
  2419. is a shorthand equivalent to:
  2420. %sx ls
  2421. 2) %sx differs from %sc in that %sx automatically splits into a list,
  2422. like '%sc -l'. The reason for this is to make it as easy as possible
  2423. to process line-oriented shell output via further python commands.
  2424. %sc is meant to provide much finer control, but requires more
  2425. typing.
  2426. 3) Just like %sc -l, this is a list with special attributes:
  2427. .l (or .list) : value as list.
  2428. .n (or .nlstr): value as newline-separated string.
  2429. .s (or .spstr): value as whitespace-separated string.
  2430. This is very useful when trying to use such lists as arguments to
  2431. system commands."""
  2432. if parameter_s:
  2433. out,err = self.shell.getoutputerror(parameter_s)
  2434. if err:
  2435. print >> Term.cerr,err
  2436. return SList(out.split('\n'))
  2437. def magic_bg(self, parameter_s=''):
  2438. """Run a job in the background, in a separate thread.
  2439. For example,
  2440. %bg myfunc(x,y,z=1)
  2441. will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
  2442. execution starts, a message will be printed indicating the job
  2443. number. If your job number is 5, you can use
  2444. myvar = jobs.result(5) or myvar = jobs[5].result
  2445. to assign this result to variable 'myvar'.
  2446. IPython has a job manager, accessible via the 'jobs' object. You can
  2447. type jobs? to get more information about it, and use jobs.<TAB> to see
  2448. its attributes. All attributes not starting with an underscore are
  2449. meant for public use.
  2450. In particular, look at the jobs.new() method, which is used to create
  2451. new jobs. This magic %bg function is just a convenience wrapper
  2452. around jobs.new(), for expression-based jobs. If you want to create a
  2453. new job with an explicit function object and arguments, you must call
  2454. jobs.new() directly.
  2455. The jobs.new docstring also describes in detail several important
  2456. caveats associated with a thread-based model for background job
  2457. execution. Type jobs.new? for details.
  2458. You can check the status of all jobs with jobs.status().
  2459. The jobs variable is set by IPython into the Python builtin namespace.
  2460. If you ever declare a variable named 'jobs', you will shadow this
  2461. name. You can either delete your global jobs variable to regain
  2462. access to the job manager, or make a new name and assign it manually
  2463. to the manager (stored in IPython's namespace). For example, to
  2464. assign the job manager to the Jobs name, use:
  2465. Jobs = __builtins__.jobs"""
  2466. self.shell.jobs.new(parameter_s,self.shell.user_ns)
  2467. def magic_r(self, parameter_s=''):
  2468. """Repeat previous input.
  2469. Note: Consider using the more powerfull %rep instead!
  2470. If given an argument, repeats the previous command which starts with
  2471. the same string, otherwise it just repeats the previous input.
  2472. Shell escaped commands (with ! as first character) are not recognized
  2473. by this system, only pure python code and magic commands.
  2474. """
  2475. start = parameter_s.strip()
  2476. esc_magic = self.shell.ESC_MAGIC
  2477. # Identify magic commands even if automagic is on (which means
  2478. # the in-memory version is different from that typed by the user).
  2479. if self.shell.rc.automagic:
  2480. start_magic = esc_magic+start
  2481. else:
  2482. start_magic = start
  2483. # Look through the input history in reverse
  2484. for n in range(len(self.shell.input_hist)-2,0,-1):
  2485. input = self.shell.input_hist[n]
  2486. # skip plain 'r' lines so we don't recurse to infinity
  2487. if input != '_ip.magic("r")\n' and \
  2488. (input.startswith(start) or input.startswith(start_magic)):
  2489. #print 'match',`input` # dbg
  2490. print 'Executing:',input,
  2491. self.shell.runlines(input)
  2492. return
  2493. print 'No previous input matching `%s` found.' % start
  2494. def magic_bookmark(self, parameter_s=''):
  2495. """Manage IPython's bookmark system.
  2496. %bookmark <name> - set bookmark to current dir
  2497. %bookmark <name> <dir> - set bookmark to <dir>
  2498. %bookmark -l - list all bookmarks
  2499. %bookmark -d <name> - remove bookmark
  2500. %bookmark -r - remove all bookmarks
  2501. You can later on access a bookmarked folder with:
  2502. %cd -b <name>
  2503. or simply '%cd <name>' if there is no directory called <name> AND
  2504. there is such a bookmark defined.
  2505. Your bookmarks persist through IPython sessions, but they are
  2506. associated with each profile."""
  2507. opts,args = self.parse_options(parameter_s,'drl',mode='list')
  2508. if len(args) > 2:
  2509. raise UsageError("%bookmark: too many arguments")
  2510. bkms = self.db.get('bookmarks',{})
  2511. if opts.has_key('d'):
  2512. try:
  2513. todel = args[0]
  2514. except IndexError:
  2515. raise UsageError(
  2516. "%bookmark -d: must provide a bookmark to delete")
  2517. else:
  2518. try:
  2519. del bkms[todel]
  2520. except KeyError:
  2521. raise UsageError(
  2522. "%%bookmark -d: Can't delete bookmark '%s'" % todel)
  2523. elif opts.has_key('r'):
  2524. bkms = {}
  2525. elif opts.has_key('l'):
  2526. bks = bkms.keys()
  2527. bks.sort()
  2528. if bks:
  2529. size = max(map(len,bks))
  2530. else:
  2531. size = 0
  2532. fmt = '%-'+str(size)+'s -> %s'
  2533. print 'Current bookmarks:'
  2534. for bk in bks:
  2535. print fmt % (bk,bkms[bk])
  2536. else:
  2537. if not args:
  2538. raise UsageError("%bookmark: You must specify the bookmark name")
  2539. elif len(args)==1:
  2540. bkms[args[0]] = os.getcwd()
  2541. elif len(args)==2:
  2542. bkms[args[0]] = args[1]
  2543. self.db['bookmarks'] = bkms
  2544. def magic_pycat(self, parameter_s=''):
  2545. """Show a syntax-highlighted file through a pager.
  2546. This magic is similar to the cat utility, but it will assume the file
  2547. to be Python source and will show it with syntax highlighting. """
  2548. try:
  2549. filename = get_py_filename(parameter_s)
  2550. cont = file_read(filename)
  2551. except IOError:
  2552. try:
  2553. cont = eval(parameter_s,self.user_ns)
  2554. except NameError:
  2555. cont = None
  2556. if cont is None:
  2557. print "Error: no such file or variable"
  2558. return
  2559. page(self.shell.pycolorize(cont),
  2560. screen_lines=self.shell.rc.screen_length)
  2561. def magic_cpaste(self, parameter_s=''):
  2562. """Allows you to paste & execute a pre-formatted code block from clipboard.
  2563. You must terminate the block with '--' (two minus-signs) alone on the
  2564. line. You can also provide your own sentinel with '%paste -s %%' ('%%'
  2565. is the new sentinel for this operation)
  2566. The block is dedented prior to execution to enable execution of method
  2567. definitions. '>' and '+' characters at the beginning of a line are
  2568. ignored, to allow pasting directly from e-mails, diff files and
  2569. doctests (the '...' continuation prompt is also stripped). The
  2570. executed block is also assigned to variable named 'pasted_block' for
  2571. later editing with '%edit pasted_block'.
  2572. You can also pass a variable name as an argument, e.g. '%cpaste foo'.
  2573. This assigns the pasted block to variable 'foo' as string, without
  2574. dedenting or executing it (preceding >>> and + is still stripped)
  2575. Do not be alarmed by garbled output on Windows (it's a readline bug).
  2576. Just press enter and type -- (and press enter again) and the block
  2577. will be what was just pasted.
  2578. IPython statements (magics, shell escapes) are not supported (yet).
  2579. """
  2580. opts,args = self.parse_options(parameter_s,'s:',mode='string')
  2581. par = args.strip()
  2582. sentinel = opts.get('s','--')
  2583. # Regular expressions that declare text we strip from the input:
  2584. strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
  2585. r'^\s*(\s?>)+', # Python input prompt
  2586. r'^\s*\.{3,}', # Continuation prompts
  2587. r'^\++',
  2588. ]
  2589. strip_from_start = map(re.compile,strip_re)
  2590. from IPython import iplib
  2591. lines = []
  2592. print "Pasting code; enter '%s' alone on the line to stop." % sentinel
  2593. while 1:
  2594. l = iplib.raw_input_original(':')
  2595. if l ==sentinel:
  2596. break
  2597. for pat in strip_from_start:
  2598. l = pat.sub('',l)
  2599. lines.append(l)
  2600. block = "\n".join(lines) + '\n'
  2601. #print "block:\n",block
  2602. if not par:
  2603. b = textwrap.dedent(block)
  2604. exec b in self.user_ns
  2605. self.user_ns['pasted_block'] = b
  2606. else:
  2607. self.user_ns[par] = SList(block.splitlines())
  2608. print "Block assigned to '%s'" % par
  2609. def magic_quickref(self,arg):
  2610. """ Show a quick reference sheet """
  2611. import IPython.usage
  2612. qr = IPython.usage.quick_reference + self.magic_magic('-brief')
  2613. page(qr)
  2614. def magic_upgrade(self,arg):
  2615. """ Upgrade your IPython installation
  2616. This will copy the config files that don't yet exist in your
  2617. ipython dir from the system config dir. Use this after upgrading
  2618. IPython if you don't wish to delete your .ipython dir.
  2619. Call with -nolegacy to get rid of ipythonrc* files (recommended for
  2620. new users)
  2621. """
  2622. ip = self.getapi()
  2623. ipinstallation = path(IPython.__file__).dirname()
  2624. upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py')
  2625. src_config = ipinstallation / 'UserConfig'
  2626. userdir = path(ip.options.ipythondir)
  2627. cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
  2628. print ">",cmd
  2629. shell(cmd)
  2630. if arg == '-nolegacy':
  2631. legacy = userdir.files('ipythonrc*')
  2632. print "Nuking legacy files:",legacy
  2633. [p.remove() for p in legacy]
  2634. suffix = (sys.platform == 'win32' and '.ini' or '')
  2635. (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
  2636. def magic_doctest_mode(self,parameter_s=''):
  2637. """Toggle doctest mode on and off.
  2638. This mode allows you to toggle the prompt behavior between normal
  2639. IPython prompts and ones that are as similar to the default IPython
  2640. interpreter as possible.
  2641. It also supports the pasting of code snippets that have leading '>>>'
  2642. and '...' prompts in them. This means that you can paste doctests from
  2643. files or docstrings (even if they have leading whitespace), and the
  2644. code will execute correctly. You can then use '%history -tn' to see
  2645. the translated history without line numbers; this will give you the
  2646. input after removal of all the leading prompts and whitespace, which
  2647. can be pasted back into an editor.
  2648. With these features, you can switch into this mode easily whenever you
  2649. need to do testing and changes to doctests, without having to leave
  2650. your existing IPython session.
  2651. """
  2652. # XXX - Fix this to have cleaner activate/deactivate calls.
  2653. from IPython.Extensions import InterpreterPasteInput as ipaste
  2654. from IPython.ipstruct import Struct
  2655. # Shorthands
  2656. shell = self.shell
  2657. oc = shell.outputcache
  2658. rc = shell.rc
  2659. meta = shell.meta
  2660. # dstore is a data store kept in the instance metadata bag to track any
  2661. # changes we make, so we can undo them later.
  2662. dstore = meta.setdefault('doctest_mode',Struct())
  2663. save_dstore = dstore.setdefault
  2664. # save a few values we'll need to recover later
  2665. mode = save_dstore('mode',False)
  2666. save_dstore('rc_pprint',rc.pprint)
  2667. save_dstore('xmode',shell.InteractiveTB.mode)
  2668. save_dstore('rc_separate_out',rc.separate_out)
  2669. save_dstore('rc_separate_out2',rc.separate_out2)
  2670. save_dstore('rc_prompts_pad_left',rc.prompts_pad_left)
  2671. save_dstore('rc_separate_in',rc.separate_in)
  2672. if mode == False:
  2673. # turn on
  2674. ipaste.activate_prefilter()
  2675. oc.prompt1.p_template = '>>> '
  2676. oc.prompt2.p_template = '... '
  2677. oc.prompt_out.p_template = ''
  2678. # Prompt separators like plain python
  2679. oc.input_sep = oc.prompt1.sep = ''
  2680. oc.output_sep = ''
  2681. oc.output_sep2 = ''
  2682. oc.prompt1.pad_left = oc.prompt2.pad_left = \
  2683. oc.prompt_out.pad_left = False
  2684. rc.pprint = False
  2685. shell.magic_xmode('Plain')
  2686. else:
  2687. # turn off
  2688. ipaste.deactivate_prefilter()
  2689. oc.prompt1.p_template = rc.prompt_in1
  2690. oc.prompt2.p_template = rc.prompt_in2
  2691. oc.prompt_out.p_template = rc.prompt_out
  2692. oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
  2693. oc.output_sep = dstore.rc_separate_out
  2694. oc.output_sep2 = dstore.rc_separate_out2
  2695. oc.prompt1.pad_left = oc.prompt2.pad_left = \
  2696. oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
  2697. rc.pprint = dstore.rc_pprint
  2698. shell.magic_xmode(dstore.xmode)
  2699. # Store new mode and inform
  2700. dstore.mode = bool(1-int(mode))
  2701. print 'Doctest mode is:',
  2702. print ['OFF','ON'][dstore.mode]
  2703. # end Magic