PageRenderTime 75ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

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

https://bitbucket.org/noahgift/pylons-rest-tutorial
Python | 3526 lines | 3469 code | 23 blank | 34 comment | 27 complexity | e32312778e89911061f36e91c67d3a6f MD5 | raw file
Possible License(s): 0BSD
  1. # -*- coding: utf-8 -*-
  2. """Magic functions for InteractiveShell.
  3. """
  4. #*****************************************************************************
  5. # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
  6. # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
  7. #
  8. # Distributed under the terms of the BSD License. The full license is in
  9. # the file COPYING, distributed as part of this software.
  10. #*****************************************************************************
  11. #****************************************************************************
  12. # Modules and globals
  13. # Python standard modules
  14. import __builtin__
  15. import bdb
  16. import inspect
  17. import os
  18. import pdb
  19. import pydoc
  20. import sys
  21. import re
  22. import tempfile
  23. import time
  24. import cPickle as pickle
  25. import textwrap
  26. from cStringIO import StringIO
  27. from getopt import getopt,GetoptError
  28. from pprint import pprint, pformat
  29. # cProfile was added in Python2.5
  30. try:
  31. import cProfile as profile
  32. import pstats
  33. except ImportError:
  34. # profile isn't bundled by default in Debian for license reasons
  35. try:
  36. import profile,pstats
  37. except ImportError:
  38. profile = pstats = None
  39. # Homebrewed
  40. import IPython
  41. from IPython import Debugger, OInspect, wildcard
  42. from IPython.FakeModule import FakeModule
  43. from IPython.Itpl import Itpl, itpl, printpl,itplns
  44. from IPython.PyColorize import Parser
  45. from IPython.ipstruct import Struct
  46. from IPython.macro import Macro
  47. from IPython.genutils import *
  48. from IPython import platutils
  49. import IPython.generics
  50. import IPython.ipapi
  51. from IPython.ipapi import UsageError
  52. from IPython.testing import decorators as testdec
  53. #***************************************************************************
  54. # Utility functions
  55. def on_off(tag):
  56. """Return an ON/OFF string for a 1/0 input. Simple utility function."""
  57. return ['OFF','ON'][tag]
  58. class Bunch: pass
  59. def compress_dhist(dh):
  60. head, tail = dh[:-10], dh[-10:]
  61. newhead = []
  62. done = set()
  63. for h in head:
  64. if h in done:
  65. continue
  66. newhead.append(h)
  67. done.add(h)
  68. return newhead + tail
  69. #***************************************************************************
  70. # Main class implementing Magic functionality
  71. class Magic:
  72. """Magic functions for InteractiveShell.
  73. Shell functions which can be reached as %function_name. All magic
  74. functions should accept a string, which they can parse for their own
  75. needs. This can make some functions easier to type, eg `%cd ../`
  76. vs. `%cd("../")`
  77. ALL definitions MUST begin with the prefix magic_. The user won't need it
  78. at the command line, but it is is needed in the definition. """
  79. # class globals
  80. auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
  81. 'Automagic is ON, % prefix NOT needed for magic functions.']
  82. #......................................................................
  83. # some utility functions
  84. def __init__(self,shell):
  85. self.options_table = {}
  86. if profile is None:
  87. self.magic_prun = self.profile_missing_notice
  88. self.shell = shell
  89. # namespace for holding state we may need
  90. self._magic_state = Bunch()
  91. def profile_missing_notice(self, *args, **kwargs):
  92. error("""\
  93. The profile module could not be found. It has been removed from the standard
  94. python packages because of its non-free license. To use profiling, install the
  95. python-profiler package from non-free.""")
  96. def default_option(self,fn,optstr):
  97. """Make an entry in the options_table for fn, with value optstr"""
  98. if fn not in self.lsmagic():
  99. error("%s is not a magic function" % fn)
  100. self.options_table[fn] = optstr
  101. def lsmagic(self):
  102. """Return a list of currently available magic functions.
  103. Gives a list of the bare names after mangling (['ls','cd', ...], not
  104. ['magic_ls','magic_cd',...]"""
  105. # FIXME. This needs a cleanup, in the way the magics list is built.
  106. # magics in class definition
  107. class_magic = lambda fn: fn.startswith('magic_') and \
  108. callable(Magic.__dict__[fn])
  109. # in instance namespace (run-time user additions)
  110. inst_magic = lambda fn: fn.startswith('magic_') and \
  111. callable(self.__dict__[fn])
  112. # and bound magics by user (so they can access self):
  113. inst_bound_magic = lambda fn: fn.startswith('magic_') and \
  114. callable(self.__class__.__dict__[fn])
  115. magics = filter(class_magic,Magic.__dict__.keys()) + \
  116. filter(inst_magic,self.__dict__.keys()) + \
  117. filter(inst_bound_magic,self.__class__.__dict__.keys())
  118. out = []
  119. for fn in set(magics):
  120. out.append(fn.replace('magic_','',1))
  121. out.sort()
  122. return out
  123. def extract_input_slices(self,slices,raw=False):
  124. """Return as a string a set of input history slices.
  125. Inputs:
  126. - slices: the set of slices is given as a list of strings (like
  127. ['1','4:8','9'], since this function is for use by magic functions
  128. which get their arguments as strings.
  129. Optional inputs:
  130. - raw(False): by default, the processed input is used. If this is
  131. true, the raw input history is used instead.
  132. Note that slices can be called with two notations:
  133. N:M -> standard python form, means including items N...(M-1).
  134. N-M -> include items N..M (closed endpoint)."""
  135. if raw:
  136. hist = self.shell.input_hist_raw
  137. else:
  138. hist = self.shell.input_hist
  139. cmds = []
  140. for chunk in slices:
  141. if ':' in chunk:
  142. ini,fin = map(int,chunk.split(':'))
  143. elif '-' in chunk:
  144. ini,fin = map(int,chunk.split('-'))
  145. fin += 1
  146. else:
  147. ini = int(chunk)
  148. fin = ini+1
  149. cmds.append(hist[ini:fin])
  150. return cmds
  151. def _ofind(self, oname, namespaces=None):
  152. """Find an object in the available namespaces.
  153. self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
  154. Has special code to detect magic functions.
  155. """
  156. oname = oname.strip()
  157. alias_ns = None
  158. if namespaces is None:
  159. # Namespaces to search in:
  160. # Put them in a list. The order is important so that we
  161. # find things in the same order that Python finds them.
  162. namespaces = [ ('Interactive', self.shell.user_ns),
  163. ('IPython internal', self.shell.internal_ns),
  164. ('Python builtin', __builtin__.__dict__),
  165. ('Alias', self.shell.alias_table),
  166. ]
  167. alias_ns = self.shell.alias_table
  168. # initialize results to 'null'
  169. found = 0; obj = None; ospace = None; ds = None;
  170. ismagic = 0; isalias = 0; parent = None
  171. # Look for the given name by splitting it in parts. If the head is
  172. # found, then we look for all the remaining parts as members, and only
  173. # declare success if we can find them all.
  174. oname_parts = oname.split('.')
  175. oname_head, oname_rest = oname_parts[0],oname_parts[1:]
  176. for nsname,ns in namespaces:
  177. try:
  178. obj = ns[oname_head]
  179. except KeyError:
  180. continue
  181. else:
  182. #print 'oname_rest:', oname_rest # dbg
  183. for part in oname_rest:
  184. try:
  185. parent = obj
  186. obj = getattr(obj,part)
  187. except:
  188. # Blanket except b/c some badly implemented objects
  189. # allow __getattr__ to raise exceptions other than
  190. # AttributeError, which then crashes IPython.
  191. break
  192. else:
  193. # If we finish the for loop (no break), we got all members
  194. found = 1
  195. ospace = nsname
  196. if ns == alias_ns:
  197. isalias = 1
  198. break # namespace loop
  199. # Try to see if it's magic
  200. if not found:
  201. if oname.startswith(self.shell.ESC_MAGIC):
  202. oname = oname[1:]
  203. obj = getattr(self,'magic_'+oname,None)
  204. if obj is not None:
  205. found = 1
  206. ospace = 'IPython internal'
  207. ismagic = 1
  208. # Last try: special-case some literals like '', [], {}, etc:
  209. if not found and oname_head in ["''",'""','[]','{}','()']:
  210. obj = eval(oname_head)
  211. found = 1
  212. ospace = 'Interactive'
  213. return {'found':found, 'obj':obj, 'namespace':ospace,
  214. 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
  215. def arg_err(self,func):
  216. """Print docstring if incorrect arguments were passed"""
  217. print 'Error in arguments:'
  218. print OInspect.getdoc(func)
  219. def format_latex(self,strng):
  220. """Format a string for latex inclusion."""
  221. # Characters that need to be escaped for latex:
  222. escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
  223. # Magic command names as headers:
  224. cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
  225. re.MULTILINE)
  226. # Magic commands
  227. cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
  228. re.MULTILINE)
  229. # Paragraph continue
  230. par_re = re.compile(r'\\$',re.MULTILINE)
  231. # The "\n" symbol
  232. newline_re = re.compile(r'\\n')
  233. # Now build the string for output:
  234. #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
  235. strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
  236. strng)
  237. strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
  238. strng = par_re.sub(r'\\\\',strng)
  239. strng = escape_re.sub(r'\\\1',strng)
  240. strng = newline_re.sub(r'\\textbackslash{}n',strng)
  241. return strng
  242. def format_screen(self,strng):
  243. """Format a string for screen printing.
  244. This removes some latex-type format codes."""
  245. # Paragraph continue
  246. par_re = re.compile(r'\\$',re.MULTILINE)
  247. strng = par_re.sub('',strng)
  248. return strng
  249. def parse_options(self,arg_str,opt_str,*long_opts,**kw):
  250. """Parse options passed to an argument string.
  251. The interface is similar to that of getopt(), but it returns back a
  252. Struct with the options as keys and the stripped argument string still
  253. as a string.
  254. arg_str is quoted as a true sys.argv vector by using shlex.split.
  255. This allows us to easily expand variables, glob files, quote
  256. arguments, etc.
  257. Options:
  258. -mode: default 'string'. If given as 'list', the argument string is
  259. returned as a list (split on whitespace) instead of a string.
  260. -list_all: put all option values in lists. Normally only options
  261. appearing more than once are put in a list.
  262. -posix (True): whether to split the input line in POSIX mode or not,
  263. as per the conventions outlined in the shlex module from the
  264. standard library."""
  265. # inject default options at the beginning of the input line
  266. caller = sys._getframe(1).f_code.co_name.replace('magic_','')
  267. arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
  268. mode = kw.get('mode','string')
  269. if mode not in ['string','list']:
  270. raise ValueError,'incorrect mode given: %s' % mode
  271. # Get options
  272. list_all = kw.get('list_all',0)
  273. posix = kw.get('posix',True)
  274. # Check if we have more than one argument to warrant extra processing:
  275. odict = {} # Dictionary with options
  276. args = arg_str.split()
  277. if len(args) >= 1:
  278. # If the list of inputs only has 0 or 1 thing in it, there's no
  279. # need to look for options
  280. argv = arg_split(arg_str,posix)
  281. # Do regular option processing
  282. try:
  283. opts,args = getopt(argv,opt_str,*long_opts)
  284. except GetoptError,e:
  285. raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
  286. " ".join(long_opts)))
  287. for o,a in opts:
  288. if o.startswith('--'):
  289. o = o[2:]
  290. else:
  291. o = o[1:]
  292. try:
  293. odict[o].append(a)
  294. except AttributeError:
  295. odict[o] = [odict[o],a]
  296. except KeyError:
  297. if list_all:
  298. odict[o] = [a]
  299. else:
  300. odict[o] = a
  301. # Prepare opts,args for return
  302. opts = Struct(odict)
  303. if mode == 'string':
  304. args = ' '.join(args)
  305. return opts,args
  306. #......................................................................
  307. # And now the actual magic functions
  308. # Functions for IPython shell work (vars,funcs, config, etc)
  309. def magic_lsmagic(self, parameter_s = ''):
  310. """List currently available magic functions."""
  311. mesc = self.shell.ESC_MAGIC
  312. print 'Available magic functions:\n'+mesc+\
  313. (' '+mesc).join(self.lsmagic())
  314. print '\n' + Magic.auto_status[self.shell.rc.automagic]
  315. return None
  316. def magic_magic(self, parameter_s = ''):
  317. """Print information about the magic function system.
  318. Supported formats: -latex, -brief, -rest
  319. """
  320. mode = ''
  321. try:
  322. if parameter_s.split()[0] == '-latex':
  323. mode = 'latex'
  324. if parameter_s.split()[0] == '-brief':
  325. mode = 'brief'
  326. if parameter_s.split()[0] == '-rest':
  327. mode = 'rest'
  328. rest_docs = []
  329. except:
  330. pass
  331. magic_docs = []
  332. for fname in self.lsmagic():
  333. mname = 'magic_' + fname
  334. for space in (Magic,self,self.__class__):
  335. try:
  336. fn = space.__dict__[mname]
  337. except KeyError:
  338. pass
  339. else:
  340. break
  341. if mode == 'brief':
  342. # only first line
  343. if fn.__doc__:
  344. fndoc = fn.__doc__.split('\n',1)[0]
  345. else:
  346. fndoc = 'No documentation'
  347. else:
  348. if fn.__doc__:
  349. fndoc = fn.__doc__.rstrip()
  350. else:
  351. fndoc = 'No documentation'
  352. if mode == 'rest':
  353. rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(self.shell.ESC_MAGIC,
  354. fname,fndoc))
  355. else:
  356. magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
  357. fname,fndoc))
  358. magic_docs = ''.join(magic_docs)
  359. if mode == 'rest':
  360. return "".join(rest_docs)
  361. if mode == 'latex':
  362. print self.format_latex(magic_docs)
  363. return
  364. else:
  365. magic_docs = self.format_screen(magic_docs)
  366. if mode == 'brief':
  367. return magic_docs
  368. outmsg = """
  369. IPython's 'magic' functions
  370. ===========================
  371. The magic function system provides a series of functions which allow you to
  372. control the behavior of IPython itself, plus a lot of system-type
  373. features. All these functions are prefixed with a % character, but parameters
  374. are given without parentheses or quotes.
  375. NOTE: If you have 'automagic' enabled (via the command line option or with the
  376. %automagic function), you don't need to type in the % explicitly. By default,
  377. IPython ships with automagic on, so you should only rarely need the % escape.
  378. Example: typing '%cd mydir' (without the quotes) changes you working directory
  379. to 'mydir', if it exists.
  380. You can define your own magic functions to extend the system. See the supplied
  381. ipythonrc and example-magic.py files for details (in your ipython
  382. configuration directory, typically $HOME/.ipython/).
  383. You can also define your own aliased names for magic functions. In your
  384. ipythonrc file, placing a line like:
  385. execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
  386. will define %pf as a new name for %profile.
  387. You can also call magics in code using the ipmagic() function, which IPython
  388. automatically adds to the builtin namespace. Type 'ipmagic?' for details.
  389. For a list of the available magic functions, use %lsmagic. For a description
  390. of any of them, type %magic_name?, e.g. '%cd?'.
  391. Currently the magic system has the following functions:\n"""
  392. mesc = self.shell.ESC_MAGIC
  393. outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
  394. "\n\n%s%s\n\n%s" % (outmsg,
  395. magic_docs,mesc,mesc,
  396. (' '+mesc).join(self.lsmagic()),
  397. Magic.auto_status[self.shell.rc.automagic] ) )
  398. page(outmsg,screen_lines=self.shell.rc.screen_length)
  399. def magic_autoindent(self, parameter_s = ''):
  400. """Toggle autoindent on/off (if available)."""
  401. self.shell.set_autoindent()
  402. print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
  403. def magic_automagic(self, parameter_s = ''):
  404. """Make magic functions callable without having to type the initial %.
  405. Without argumentsl toggles on/off (when off, you must call it as
  406. %automagic, of course). With arguments it sets the value, and you can
  407. use any of (case insensitive):
  408. - on,1,True: to activate
  409. - off,0,False: to deactivate.
  410. Note that magic functions have lowest priority, so if there's a
  411. variable whose name collides with that of a magic fn, automagic won't
  412. work for that function (you get the variable instead). However, if you
  413. delete the variable (del var), the previously shadowed magic function
  414. becomes visible to automagic again."""
  415. rc = self.shell.rc
  416. arg = parameter_s.lower()
  417. if parameter_s in ('on','1','true'):
  418. rc.automagic = True
  419. elif parameter_s in ('off','0','false'):
  420. rc.automagic = False
  421. else:
  422. rc.automagic = not rc.automagic
  423. print '\n' + Magic.auto_status[rc.automagic]
  424. @testdec.skip_doctest
  425. def magic_autocall(self, parameter_s = ''):
  426. """Make functions callable without having to type parentheses.
  427. Usage:
  428. %autocall [mode]
  429. The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
  430. value is toggled on and off (remembering the previous state).
  431. In more detail, these values mean:
  432. 0 -> fully disabled
  433. 1 -> active, but do not apply if there are no arguments on the line.
  434. In this mode, you get:
  435. In [1]: callable
  436. Out[1]: <built-in function callable>
  437. In [2]: callable 'hello'
  438. ------> callable('hello')
  439. Out[2]: False
  440. 2 -> Active always. Even if no arguments are present, the callable
  441. object is called:
  442. In [2]: float
  443. ------> float()
  444. Out[2]: 0.0
  445. Note that even with autocall off, you can still use '/' at the start of
  446. a line to treat the first argument on the command line as a function
  447. and add parentheses to it:
  448. In [8]: /str 43
  449. ------> str(43)
  450. Out[8]: '43'
  451. # all-random (note for auto-testing)
  452. """
  453. rc = self.shell.rc
  454. if parameter_s:
  455. arg = int(parameter_s)
  456. else:
  457. arg = 'toggle'
  458. if not arg in (0,1,2,'toggle'):
  459. error('Valid modes: (0->Off, 1->Smart, 2->Full')
  460. return
  461. if arg in (0,1,2):
  462. rc.autocall = arg
  463. else: # toggle
  464. if rc.autocall:
  465. self._magic_state.autocall_save = rc.autocall
  466. rc.autocall = 0
  467. else:
  468. try:
  469. rc.autocall = self._magic_state.autocall_save
  470. except AttributeError:
  471. rc.autocall = self._magic_state.autocall_save = 1
  472. print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
  473. def magic_system_verbose(self, parameter_s = ''):
  474. """Set verbose printing of system calls.
  475. If called without an argument, act as a toggle"""
  476. if parameter_s:
  477. val = bool(eval(parameter_s))
  478. else:
  479. val = None
  480. self.shell.rc_set_toggle('system_verbose',val)
  481. print "System verbose printing is:",\
  482. ['OFF','ON'][self.shell.rc.system_verbose]
  483. def magic_page(self, parameter_s=''):
  484. """Pretty print the object and display it through a pager.
  485. %page [options] OBJECT
  486. If no object is given, use _ (last output).
  487. Options:
  488. -r: page str(object), don't pretty-print it."""
  489. # After a function contributed by Olivier Aubert, slightly modified.
  490. # Process options/args
  491. opts,args = self.parse_options(parameter_s,'r')
  492. raw = 'r' in opts
  493. oname = args and args or '_'
  494. info = self._ofind(oname)
  495. if info['found']:
  496. txt = (raw and str or pformat)( info['obj'] )
  497. page(txt)
  498. else:
  499. print 'Object `%s` not found' % oname
  500. def magic_profile(self, parameter_s=''):
  501. """Print your currently active IPyhton profile."""
  502. if self.shell.rc.profile:
  503. printpl('Current IPython profile: $self.shell.rc.profile.')
  504. else:
  505. print 'No profile active.'
  506. def magic_pinfo(self, parameter_s='', namespaces=None):
  507. """Provide detailed information about an object.
  508. '%pinfo object' is just a synonym for object? or ?object."""
  509. #print 'pinfo par: <%s>' % parameter_s # dbg
  510. # detail_level: 0 -> obj? , 1 -> obj??
  511. detail_level = 0
  512. # We need to detect if we got called as 'pinfo pinfo foo', which can
  513. # happen if the user types 'pinfo foo?' at the cmd line.
  514. pinfo,qmark1,oname,qmark2 = \
  515. re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
  516. if pinfo or qmark1 or qmark2:
  517. detail_level = 1
  518. if "*" in oname:
  519. self.magic_psearch(oname)
  520. else:
  521. self._inspect('pinfo', oname, detail_level=detail_level,
  522. namespaces=namespaces)
  523. def magic_pdef(self, parameter_s='', namespaces=None):
  524. """Print the definition header for any callable object.
  525. If the object is a class, print the constructor information."""
  526. self._inspect('pdef',parameter_s, namespaces)
  527. def magic_pdoc(self, parameter_s='', namespaces=None):
  528. """Print the docstring for an object.
  529. If the given object is a class, it will print both the class and the
  530. constructor docstrings."""
  531. self._inspect('pdoc',parameter_s, namespaces)
  532. def magic_psource(self, parameter_s='', namespaces=None):
  533. """Print (or run through pager) the source code for an object."""
  534. self._inspect('psource',parameter_s, namespaces)
  535. def magic_pfile(self, parameter_s=''):
  536. """Print (or run through pager) the file where an object is defined.
  537. The file opens at the line where the object definition begins. IPython
  538. will honor the environment variable PAGER if set, and otherwise will
  539. do its best to print the file in a convenient form.
  540. If the given argument is not an object currently defined, IPython will
  541. try to interpret it as a filename (automatically adding a .py extension
  542. if needed). You can thus use %pfile as a syntax highlighting code
  543. viewer."""
  544. # first interpret argument as an object name
  545. out = self._inspect('pfile',parameter_s)
  546. # if not, try the input as a filename
  547. if out == 'not found':
  548. try:
  549. filename = get_py_filename(parameter_s)
  550. except IOError,msg:
  551. print msg
  552. return
  553. page(self.shell.inspector.format(file(filename).read()))
  554. def _inspect(self,meth,oname,namespaces=None,**kw):
  555. """Generic interface to the inspector system.
  556. This function is meant to be called by pdef, pdoc & friends."""
  557. #oname = oname.strip()
  558. #print '1- oname: <%r>' % oname # dbg
  559. try:
  560. oname = oname.strip().encode('ascii')
  561. #print '2- oname: <%r>' % oname # dbg
  562. except UnicodeEncodeError:
  563. print 'Python identifiers can only contain ascii characters.'
  564. return 'not found'
  565. info = Struct(self._ofind(oname, namespaces))
  566. if info.found:
  567. try:
  568. IPython.generics.inspect_object(info.obj)
  569. return
  570. except IPython.ipapi.TryNext:
  571. pass
  572. # Get the docstring of the class property if it exists.
  573. path = oname.split('.')
  574. root = '.'.join(path[:-1])
  575. if info.parent is not None:
  576. try:
  577. target = getattr(info.parent, '__class__')
  578. # The object belongs to a class instance.
  579. try:
  580. target = getattr(target, path[-1])
  581. # The class defines the object.
  582. if isinstance(target, property):
  583. oname = root + '.__class__.' + path[-1]
  584. info = Struct(self._ofind(oname))
  585. except AttributeError: pass
  586. except AttributeError: pass
  587. pmethod = getattr(self.shell.inspector,meth)
  588. formatter = info.ismagic and self.format_screen or None
  589. if meth == 'pdoc':
  590. pmethod(info.obj,oname,formatter)
  591. elif meth == 'pinfo':
  592. pmethod(info.obj,oname,formatter,info,**kw)
  593. else:
  594. pmethod(info.obj,oname)
  595. else:
  596. print 'Object `%s` not found.' % oname
  597. return 'not found' # so callers can take other action
  598. def magic_psearch(self, parameter_s=''):
  599. """Search for object in namespaces by wildcard.
  600. %psearch [options] PATTERN [OBJECT TYPE]
  601. Note: ? can be used as a synonym for %psearch, at the beginning or at
  602. the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
  603. rest of the command line must be unchanged (options come first), so
  604. for example the following forms are equivalent
  605. %psearch -i a* function
  606. -i a* function?
  607. ?-i a* function
  608. Arguments:
  609. PATTERN
  610. where PATTERN is a string containing * as a wildcard similar to its
  611. use in a shell. The pattern is matched in all namespaces on the
  612. search path. By default objects starting with a single _ are not
  613. matched, many IPython generated objects have a single
  614. underscore. The default is case insensitive matching. Matching is
  615. also done on the attributes of objects and not only on the objects
  616. in a module.
  617. [OBJECT TYPE]
  618. Is the name of a python type from the types module. The name is
  619. given in lowercase without the ending type, ex. StringType is
  620. written string. By adding a type here only objects matching the
  621. given type are matched. Using all here makes the pattern match all
  622. types (this is the default).
  623. Options:
  624. -a: makes the pattern match even objects whose names start with a
  625. single underscore. These names are normally ommitted from the
  626. search.
  627. -i/-c: make the pattern case insensitive/sensitive. If neither of
  628. these options is given, the default is read from your ipythonrc
  629. file. The option name which sets this value is
  630. 'wildcards_case_sensitive'. If this option is not specified in your
  631. ipythonrc file, IPython's internal default is to do a case sensitive
  632. search.
  633. -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
  634. specifiy can be searched in any of the following namespaces:
  635. 'builtin', 'user', 'user_global','internal', 'alias', where
  636. 'builtin' and 'user' are the search defaults. Note that you should
  637. not use quotes when specifying namespaces.
  638. 'Builtin' contains the python module builtin, 'user' contains all
  639. user data, 'alias' only contain the shell aliases and no python
  640. objects, 'internal' contains objects used by IPython. The
  641. 'user_global' namespace is only used by embedded IPython instances,
  642. and it contains module-level globals. You can add namespaces to the
  643. search with -s or exclude them with -e (these options can be given
  644. more than once).
  645. Examples:
  646. %psearch a* -> objects beginning with an a
  647. %psearch -e builtin a* -> objects NOT in the builtin space starting in a
  648. %psearch a* function -> all functions beginning with an a
  649. %psearch re.e* -> objects beginning with an e in module re
  650. %psearch r*.e* -> objects that start with e in modules starting in r
  651. %psearch r*.* string -> all strings in modules beginning with r
  652. Case sensitve search:
  653. %psearch -c a* list all object beginning with lower case a
  654. Show objects beginning with a single _:
  655. %psearch -a _* list objects beginning with a single underscore"""
  656. try:
  657. parameter_s = parameter_s.encode('ascii')
  658. except UnicodeEncodeError:
  659. print 'Python identifiers can only contain ascii characters.'
  660. return
  661. # default namespaces to be searched
  662. def_search = ['user','builtin']
  663. # Process options/args
  664. opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
  665. opt = opts.get
  666. shell = self.shell
  667. psearch = shell.inspector.psearch
  668. # select case options
  669. if opts.has_key('i'):
  670. ignore_case = True
  671. elif opts.has_key('c'):
  672. ignore_case = False
  673. else:
  674. ignore_case = not shell.rc.wildcards_case_sensitive
  675. # Build list of namespaces to search from user options
  676. def_search.extend(opt('s',[]))
  677. ns_exclude = ns_exclude=opt('e',[])
  678. ns_search = [nm for nm in def_search if nm not in ns_exclude]
  679. # Call the actual search
  680. try:
  681. psearch(args,shell.ns_table,ns_search,
  682. show_all=opt('a'),ignore_case=ignore_case)
  683. except:
  684. shell.showtraceback()
  685. def magic_who_ls(self, parameter_s=''):
  686. """Return a sorted list of all interactive variables.
  687. If arguments are given, only variables of types matching these
  688. arguments are returned."""
  689. user_ns = self.shell.user_ns
  690. internal_ns = self.shell.internal_ns
  691. user_config_ns = self.shell.user_config_ns
  692. out = []
  693. typelist = parameter_s.split()
  694. for i in user_ns:
  695. if not (i.startswith('_') or i.startswith('_i')) \
  696. and not (i in internal_ns or i in user_config_ns):
  697. if typelist:
  698. if type(user_ns[i]).__name__ in typelist:
  699. out.append(i)
  700. else:
  701. out.append(i)
  702. out.sort()
  703. return out
  704. def magic_who(self, parameter_s=''):
  705. """Print all interactive variables, with some minimal formatting.
  706. If any arguments are given, only variables whose type matches one of
  707. these are printed. For example:
  708. %who function str
  709. will only list functions and strings, excluding all other types of
  710. variables. To find the proper type names, simply use type(var) at a
  711. command line to see how python prints type names. For example:
  712. In [1]: type('hello')\\
  713. Out[1]: <type 'str'>
  714. indicates that the type name for strings is 'str'.
  715. %who always excludes executed names loaded through your configuration
  716. file and things which are internal to IPython.
  717. This is deliberate, as typically you may load many modules and the
  718. purpose of %who is to show you only what you've manually defined."""
  719. varlist = self.magic_who_ls(parameter_s)
  720. if not varlist:
  721. if parameter_s:
  722. print 'No variables match your requested type.'
  723. else:
  724. print 'Interactive namespace is empty.'
  725. return
  726. # if we have variables, move on...
  727. count = 0
  728. for i in varlist:
  729. print i+'\t',
  730. count += 1
  731. if count > 8:
  732. count = 0
  733. print
  734. print
  735. def magic_whos(self, parameter_s=''):
  736. """Like %who, but gives some extra information about each variable.
  737. The same type filtering of %who can be applied here.
  738. For all variables, the type is printed. Additionally it prints:
  739. - For {},[],(): their length.
  740. - For numpy and Numeric arrays, a summary with shape, number of
  741. elements, typecode and size in memory.
  742. - Everything else: a string representation, snipping their middle if
  743. too long."""
  744. varnames = self.magic_who_ls(parameter_s)
  745. if not varnames:
  746. if parameter_s:
  747. print 'No variables match your requested type.'
  748. else:
  749. print 'Interactive namespace is empty.'
  750. return
  751. # if we have variables, move on...
  752. # for these types, show len() instead of data:
  753. seq_types = [types.DictType,types.ListType,types.TupleType]
  754. # for numpy/Numeric arrays, display summary info
  755. try:
  756. import numpy
  757. except ImportError:
  758. ndarray_type = None
  759. else:
  760. ndarray_type = numpy.ndarray.__name__
  761. try:
  762. import Numeric
  763. except ImportError:
  764. array_type = None
  765. else:
  766. array_type = Numeric.ArrayType.__name__
  767. # Find all variable names and types so we can figure out column sizes
  768. def get_vars(i):
  769. return self.shell.user_ns[i]
  770. # some types are well known and can be shorter
  771. abbrevs = {'IPython.macro.Macro' : 'Macro'}
  772. def type_name(v):
  773. tn = type(v).__name__
  774. return abbrevs.get(tn,tn)
  775. varlist = map(get_vars,varnames)
  776. typelist = []
  777. for vv in varlist:
  778. tt = type_name(vv)
  779. if tt=='instance':
  780. typelist.append( abbrevs.get(str(vv.__class__),
  781. str(vv.__class__)))
  782. else:
  783. typelist.append(tt)
  784. # column labels and # of spaces as separator
  785. varlabel = 'Variable'
  786. typelabel = 'Type'
  787. datalabel = 'Data/Info'
  788. colsep = 3
  789. # variable format strings
  790. vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
  791. vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
  792. aformat = "%s: %s elems, type `%s`, %s bytes"
  793. # find the size of the columns to format the output nicely
  794. varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
  795. typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
  796. # table header
  797. print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
  798. ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
  799. # and the table itself
  800. kb = 1024
  801. Mb = 1048576 # kb**2
  802. for vname,var,vtype in zip(varnames,varlist,typelist):
  803. print itpl(vformat),
  804. if vtype in seq_types:
  805. print len(var)
  806. elif vtype in [array_type,ndarray_type]:
  807. vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
  808. if vtype==ndarray_type:
  809. # numpy
  810. vsize = var.size
  811. vbytes = vsize*var.itemsize
  812. vdtype = var.dtype
  813. else:
  814. # Numeric
  815. vsize = Numeric.size(var)
  816. vbytes = vsize*var.itemsize()
  817. vdtype = var.typecode()
  818. if vbytes < 100000:
  819. print aformat % (vshape,vsize,vdtype,vbytes)
  820. else:
  821. print aformat % (vshape,vsize,vdtype,vbytes),
  822. if vbytes < Mb:
  823. print '(%s kb)' % (vbytes/kb,)
  824. else:
  825. print '(%s Mb)' % (vbytes/Mb,)
  826. else:
  827. try:
  828. vstr = str(var)
  829. except UnicodeEncodeError:
  830. vstr = unicode(var).encode(sys.getdefaultencoding(),
  831. 'backslashreplace')
  832. vstr = vstr.replace('\n','\\n')
  833. if len(vstr) < 50:
  834. print vstr
  835. else:
  836. printpl(vfmt_short)
  837. def magic_reset(self, parameter_s=''):
  838. """Resets the namespace by removing all names defined by the user.
  839. Input/Output history are left around in case you need them.
  840. Parameters
  841. ----------
  842. -y : force reset without asking for confirmation.
  843. Examples
  844. --------
  845. In [6]: a = 1
  846. In [7]: a
  847. Out[7]: 1
  848. In [8]: 'a' in _ip.user_ns
  849. Out[8]: True
  850. In [9]: %reset -f
  851. In [10]: 'a' in _ip.user_ns
  852. Out[10]: False
  853. """
  854. if parameter_s == '-f':
  855. ans = True
  856. else:
  857. ans = self.shell.ask_yes_no(
  858. "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
  859. if not ans:
  860. print 'Nothing done.'
  861. return
  862. user_ns = self.shell.user_ns
  863. for i in self.magic_who_ls():
  864. del(user_ns[i])
  865. # Also flush the private list of module references kept for script
  866. # execution protection
  867. self.shell.clear_main_mod_cache()
  868. def magic_logstart(self,parameter_s=''):
  869. """Start logging anywhere in a session.
  870. %logstart [-o|-r|-t] [log_name [log_mode]]
  871. If no name is given, it defaults to a file named 'ipython_log.py' in your
  872. current directory, in 'rotate' mode (see below).
  873. '%logstart name' saves to file 'name' in 'backup' mode. It saves your
  874. history up to that point and then continues logging.
  875. %logstart takes a second optional parameter: logging mode. This can be one
  876. of (note that the modes are given unquoted):\\
  877. append: well, that says it.\\
  878. backup: rename (if exists) to name~ and start name.\\
  879. global: single logfile in your home dir, appended to.\\
  880. over : overwrite existing log.\\
  881. rotate: create rotating logs name.1~, name.2~, etc.
  882. Options:
  883. -o: log also IPython's output. In this mode, all commands which
  884. generate an Out[NN] prompt are recorded to the logfile, right after
  885. their corresponding input line. The output lines are always
  886. prepended with a '#[Out]# ' marker, so that the log remains valid
  887. Python code.
  888. Since this marker is always the same, filtering only the output from
  889. a log is very easy, using for example a simple awk call:
  890. awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
  891. -r: log 'raw' input. Normally, IPython's logs contain the processed
  892. input, so that user lines are logged in their final form, converted
  893. into valid Python. For example, %Exit is logged as
  894. '_ip.magic("Exit"). If the -r flag is given, all input is logged
  895. exactly as typed, with no transformations applied.
  896. -t: put timestamps before each input line logged (these are put in
  897. comments)."""
  898. opts,par = self.parse_options(parameter_s,'ort')
  899. log_output = 'o' in opts
  900. log_raw_input = 'r' in opts
  901. timestamp = 't' in opts
  902. rc = self.shell.rc
  903. logger = self.shell.logger
  904. # if no args are given, the defaults set in the logger constructor by
  905. # ipytohn remain valid
  906. if par:
  907. try:
  908. logfname,logmode = par.split()
  909. except:
  910. logfname = par
  911. logmode = 'backup'
  912. else:
  913. logfname = logger.logfname
  914. logmode = logger.logmode
  915. # put logfname into rc struct as if it had been called on the command
  916. # line, so it ends up saved in the log header Save it in case we need
  917. # to restore it...
  918. old_logfile = rc.opts.get('logfile','')
  919. if logfname:
  920. logfname = os.path.expanduser(logfname)
  921. rc.opts.logfile = logfname
  922. loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
  923. try:
  924. started = logger.logstart(logfname,loghead,logmode,
  925. log_output,timestamp,log_raw_input)
  926. except:
  927. rc.opts.logfile = old_logfile
  928. warn("Couldn't start log: %s" % sys.exc_info()[1])
  929. else:
  930. # log input history up to this point, optionally interleaving
  931. # output if requested
  932. if timestamp:
  933. # disable timestamping for the previous history, since we've
  934. # lost those already (no time machine here).
  935. logger.timestamp = False
  936. if log_raw_input:
  937. input_hist = self.shell.input_hist_raw
  938. else:
  939. input_hist = self.shell.input_hist
  940. if log_output:
  941. log_write = logger.log_write
  942. output_hist = self.shell.output_hist
  943. for n in range(1,len(input_hist)-1):
  944. log_write(input_hist[n].rstrip())
  945. if n in output_hist:
  946. log_write(repr(output_hist[n]),'output')
  947. else:
  948. logger.log_write(input_hist[1:])
  949. if timestamp:
  950. # re-enable timestamping
  951. logger.timestamp = True
  952. print ('Activating auto-logging. '
  953. 'Current session state plus future input saved.')
  954. logger.logstate()
  955. def magic_logstop(self,parameter_s=''):
  956. """Fully stop logging and close log file.
  957. In order to start logging again, a new %logstart call needs to be made,
  958. possibly (though not necessarily) with a new filename, mode and other
  959. options."""
  960. self.logger.logstop()
  961. def magic_logoff(self,parameter_s=''):
  962. """Temporarily stop logging.
  963. You must have previously started logging."""
  964. self.shell.logger.switch_log(0)
  965. def magic_logon(self,parameter_s=''):
  966. """Restart logging.
  967. This function is for restarting logging which you've temporarily
  968. stopped with %logoff. For starting logging for the first time, you
  969. must use the %logstart function, which allows you to specify an
  970. optional log filename."""
  971. self.shell.logger.switch_log(1)
  972. def magic_logstate(self,parameter_s=''):
  973. """Print the status of the logging system."""
  974. self.shell.logger.logstate()
  975. def magic_pdb(self, parameter_s=''):
  976. """Control the automatic calling of the pdb interactive debugger.
  977. Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
  978. argument it works as a toggle.
  979. When an exception is triggered, IPython can optionally call the
  980. interactive pdb debugger after the traceback printout. %pdb toggles
  981. this feature on and off.
  982. The initial state of this feature is set in your ipythonrc
  983. configuration file (the variable is called 'pdb').
  984. If you want to just activate the debugger AFTER an exception has fired,
  985. without having to type '%pdb on' and rerunning your code, you can use
  986. the %debug magic."""
  987. par = parameter_s.strip().lower()
  988. if par:
  989. try:
  990. new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
  991. except KeyError:
  992. print ('Incorrect argument. Use on/1, off/0, '
  993. 'or nothing for a toggle.')
  994. return
  995. else:
  996. # toggle
  997. new_pdb = not self.shell.call_pdb
  998. # set on the shell
  999. self.shell.call_pdb = new_pdb
  1000. print 'Automatic pdb calling has been turned',on_off(new_pdb)
  1001. def magic_debug(self, parameter_s=''):
  1002. """Activate the interactive debugger in post-mortem mode.
  1003. If an exception has just occurred, this lets you inspect its stack
  1004. frames interactively. Note that this will always work only on the last
  1005. traceback that occurred, so you must call this quickly after an
  1006. exception that you wish to inspect has fired, because if another one
  1007. occurs, it clobbers the previous one.
  1008. If you want IPython to automatically do this on every exception, see
  1009. the %pdb magic for more details.
  1010. """
  1011. self.shell.debugger(force=True)
  1012. @testdec.skip_doctest
  1013. def magic_prun(self, parameter_s ='',user_mode=1,
  1014. opts=None,arg_lst=None,prog_ns=None):
  1015. """Run a statement through the python code profiler.
  1016. Usage:
  1017. %prun [options] statement
  1018. The given statement (which doesn't require quote marks) is run via the
  1019. python profiler in a manner similar to the profile.run() function.
  1020. Namespaces are internally managed to work correctly; profile.run
  1021. cannot be used in IPython because it makes certain assumptions about
  1022. namespaces which do not hold under IPython.
  1023. Options:
  1024. -l <limit>: you can place restrictions on what or how much of the
  1025. profile gets printed. The limit value can be:
  1026. * A string: only information for function names containing this string
  1027. is printed.
  1028. * An integer: only these many lines are printed.
  1029. * A float (between 0 and 1): this fraction of the report is printed
  1030. (for example, use a limit of 0.4 to see the topmost 40% only).
  1031. You can combine several limits with repeated use of the option. For
  1032. example, '-l __init__ -l 5' will print only the topmost 5 lines of
  1033. information about class constructors.
  1034. -r: return the pstats.Stats object generated by the profiling. This
  1035. object has all the information about the profile in it, and you can
  1036. later use it for further analysis or in other functions.
  1037. -s <key>: sort profile by given key. You can provide more than one key
  1038. by using the option several times: '-s key1 -s key2 -s key3...'. The
  1039. default sorting key is 'time'.
  1040. The following is copied verbatim from the profile documentation
  1041. referenced below:
  1042. When more than one key is provided, additional keys are used as
  1043. secondary criteria when the there is equality in all keys selected
  1044. before them.
  1045. Abbreviations can be used for any key names, as long as the
  1046. abbreviation is unambiguous. The following are the keys currently
  1047. defined:
  1048. Valid Arg Meaning
  1049. "calls" call count
  1050. "cumulative" cumulative time
  1051. "file" file name
  1052. "module" file name
  1053. "pcalls" primitive call count
  1054. "line" line number
  1055. "name" function name
  1056. "nfl" name/file/line
  1057. "stdname" standard name
  1058. "time" internal time
  1059. Note that all sorts on statistics are in descending order (placing
  1060. most time consuming items first), where as name, file, and line number
  1061. searches are in ascending order (i.e., alphabetical). The subtle
  1062. distinction between "nfl" and "stdname" is that the standard name is a
  1063. sort of the name as printed, which means that the embedded line
  1064. numbers get compared in an odd way. For example, lines 3, 20, and 40
  1065. would (if the file names were the same) appear in the string order
  1066. "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
  1067. line numbers. In fact, sort_stats("nfl") is the same as
  1068. sort_stats("name", "file", "line").
  1069. -T <filename>: save profile results as shown on screen to a text
  1070. file. The profile is still shown on screen.
  1071. -D <filename>: save (via dump_stats) profile statistics to given
  1072. filename. This data is in a format understod by the pstats module, and
  1073. is generated by a call to the dump_stats() method of profile
  1074. objects. The profile is still shown on screen.
  1075. If you want to run complete programs under the profiler's control, use
  1076. '%run -p [prof_opts] filename.py [args to program]' where prof_opts
  1077. contains profiler specific options as described here.
  1078. You can read the complete documentation for the profile module with::
  1079. In [1]: import profile; profile.help()
  1080. """
  1081. opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
  1082. # protect user quote marks
  1083. parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
  1084. if user_mode: # regular user call
  1085. opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
  1086. list_all=1)
  1087. namespace = self.shell.user_ns
  1088. else: # called to run a program by %run -p
  1089. try:
  1090. filename = get_py_filename(arg_lst[0])
  1091. except IOError,msg:
  1092. error(msg)
  1093. return
  1094. arg_str = 'execfile(filename,prog_ns)'
  1095. namespace = locals()
  1096. opts.merge(opts_def)
  1097. prof = profile.Profile()
  1098. try:
  1099. prof = prof.runctx(arg_str,namespace,namespace)
  1100. sys_exit = ''
  1101. except SystemExit:
  1102. sys_exit = """*** SystemExit exception caught in code being profiled."""
  1103. stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
  1104. lims = opts.l
  1105. if lims:
  1106. lims = [] # rebuild lims with ints/floats/strings
  1107. for lim in opts.l:
  1108. try:
  1109. lims.append(int(lim))
  1110. except ValueError:
  1111. try:
  1112. lims.append(float(lim))
  1113. except ValueError:
  1114. lims.append(lim)
  1115. # Trap output.
  1116. stdout_trap = StringIO()
  1117. if hasattr(stats,'stream'):
  1118. # In newer versions of python, the stats object has a 'stream'
  1119. # attribute to write into.
  1120. stats.stream = stdout_trap
  1121. stats.print_stats(*lims)
  1122. else:
  1123. # For older versions, we manually redirect stdout during printing
  1124. sys_stdout = sys.stdout
  1125. try:
  1126. sys.stdout = stdout_trap
  1127. stats.print_stats(*lims)
  1128. finally:
  1129. sys.stdout = sys_stdout
  1130. output = stdout_trap.getvalue()
  1131. output = output.rstrip()
  1132. page(output,screen_lines=self.shell.rc.screen_length)
  1133. print sys_exit,
  1134. dump_file = opts.D[0]
  1135. text_file = opts.T[0]
  1136. if dump_file:
  1137. prof.dump_stats(dump_file)
  1138. print '\n*** Profile stats marshalled to file',\
  1139. `dump_file`+'.',sys_exit
  1140. if text_file:
  1141. pfile = file(text_file,'w')
  1142. pfile.write(output)
  1143. pfile.close()
  1144. print '\n*** Profile printout saved to text file',\
  1145. `text_file`+'.',sys_exit
  1146. if opts.has_key('r'):
  1147. return stats
  1148. else:
  1149. return None
  1150. @testdec.skip_doctest
  1151. def magic_run(self, parameter_s ='',runner=None,
  1152. file_finder=get_py_filename):
  1153. """Run the named file inside IPython as a program.
  1154. Usage:\\
  1155. %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
  1156. Parameters after the filename are passed as command-line arguments to
  1157. the program (put in sys.argv). Then, control returns to IPython's
  1158. prompt.
  1159. This is similar to running at a system prompt:\\
  1160. $ python file args\\
  1161. but with the advantage of giving you IPython's tracebacks, and of
  1162. loading all variables into your interactive namespace for further use
  1163. (unless -p is used, see below).
  1164. The file is executed in a namespace initially consisting only of
  1165. __name__=='__main__' and sys.argv constructed as indicated. It thus
  1166. sees its environment as if it were being run as a stand-alone program
  1167. (except for sharing global objects such as previously imported
  1168. modules). But after execution, the IPython interactive namespace gets
  1169. updated with all variables defined in the program (except for __name__
  1170. and sys.argv). This allows for very convenient loading of code for
  1171. interactive work, while giving each program a 'clean sheet' to run in.
  1172. Options:
  1173. -n: __name__ is NOT set to '__main__', but to the running file's name
  1174. without extension (as python does under import). This allows running
  1175. scripts and reloading the definitions in them without calling code
  1176. protected by an ' if __name__ == "__main__" ' clause.
  1177. -i: run the file in IPython's namespace instead of an empty one. This
  1178. is useful if you are experimenting with code written in a text editor
  1179. which depends on variables defined interactively.
  1180. -e: ignore sys.exit() calls or SystemExit exceptions in the script
  1181. being run. This is particularly useful if IPython is being used to
  1182. run unittests, which always exit with a sys.exit() call. In such
  1183. cases you are interested in the output of the test results, not in
  1184. seeing a traceback of the unittest module.
  1185. -t: print timing information at the end of the run. IPython will give
  1186. you an estimated CPU time consumption for your script, which under
  1187. Unix uses the resource module to avoid the wraparound problems of
  1188. time.clock(). Under Unix, an estimate of time spent on system tasks
  1189. is also given (for Windows platforms this is reported as 0.0).
  1190. If -t is given, an additional -N<N> option can be given, where <N>
  1191. must be an integer indicating how many times you want the script to
  1192. run. The final timing report will include total and per run results.
  1193. For example (testing the script uniq_stable.py):
  1194. In [1]: run -t uniq_stable
  1195. IPython CPU timings (estimated):\\
  1196. User : 0.19597 s.\\
  1197. System: 0.0 s.\\
  1198. In [2]: run -t -N5 uniq_stable
  1199. IPython CPU timings (estimated):\\
  1200. Total runs performed: 5\\
  1201. Times : Total Per run\\
  1202. User : 0.910862 s, 0.1821724 s.\\
  1203. System: 0.0 s, 0.0 s.
  1204. -d: run your program under the control of pdb, the Python debugger.
  1205. This allows you to execute your program step by step, watch variables,
  1206. etc. Internally, what IPython does is similar to calling:
  1207. pdb.run('execfile("YOURFILENAME")')
  1208. with a breakpoint set on line 1 of your file. You can change the line
  1209. number for this automatic breakpoint to be <N> by using the -bN option
  1210. (where N must be an integer). For example:
  1211. %run -d -b40 myscript
  1212. will set the first breakpoint at line 40 in myscript.py. Note that
  1213. the first breakpoint must be set on a line which actually does
  1214. something (not a comment or docstring) for it to stop execution.
  1215. When the pdb debugger starts, you will see a (Pdb) prompt. You must
  1216. first enter 'c' (without qoutes) to start execution up to the first
  1217. breakpoint.
  1218. Entering 'help' gives information about the use of the debugger. You
  1219. can easily see pdb's full documentation with "import pdb;pdb.help()"
  1220. at a prompt.
  1221. -p: run program under the control of the Python profiler module (which
  1222. prints a detailed report of execution times, function calls, etc).
  1223. You can pass other options after -p which affect the behavior of the
  1224. profiler itself. See the docs for %prun for details.
  1225. In this mode, the program's variables do NOT propagate back to the
  1226. IPython interactive namespace (because they remain in the namespace
  1227. where the profiler executes them).
  1228. Internally this triggers a call to %prun, see its documentation for
  1229. details on the options available specifically for profiling.
  1230. There is one special usage for which the text above doesn't apply:
  1231. if the filename ends with .ipy, the file is run as ipython script,
  1232. just as if the commands were written on IPython prompt.
  1233. """
  1234. # get arguments and set sys.argv for program to be run.
  1235. opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
  1236. mode='list',list_all=1)
  1237. try:
  1238. filename = file_finder(arg_lst[0])
  1239. except IndexError:
  1240. warn('you must provide at least a filename.')
  1241. print '\n%run:\n',OInspect.getdoc(self.magic_run)
  1242. return
  1243. except IOError,msg:
  1244. error(msg)
  1245. return
  1246. if filename.lower().endswith('.ipy'):
  1247. self.api.runlines(open(filename).read())
  1248. return
  1249. # Control the response to exit() calls made by the script being run
  1250. exit_ignore = opts.has_key('e')
  1251. # Make sure that the running script gets a proper sys.argv as if it
  1252. # were run from a system shell.
  1253. save_argv = sys.argv # save it for later restoring
  1254. sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
  1255. if opts.has_key('i'):
  1256. # Run in user's interactive namespace
  1257. prog_ns = self.shell.user_ns
  1258. __name__save = self.shell.user_ns['__name__']
  1259. prog_ns['__name__'] = '__main__'
  1260. main_mod = self.shell.new_main_mod(prog_ns)
  1261. else:
  1262. # Run in a fresh, empty namespace
  1263. if opts.has_key('n'):
  1264. name = os.path.splitext(os.path.basename(filename))[0]
  1265. else:
  1266. name = '__main__'
  1267. main_mod = self.shell.new_main_mod()
  1268. prog_ns = main_mod.__dict__
  1269. prog_ns['__name__'] = name
  1270. # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
  1271. # set the __file__ global in the script's namespace
  1272. prog_ns['__file__'] = filename
  1273. # pickle fix. See iplib for an explanation. But we need to make sure
  1274. # that, if we overwrite __main__, we replace it at the end
  1275. main_mod_name = prog_ns['__name__']
  1276. if main_mod_name == '__main__':
  1277. restore_main = sys.modules['__main__']
  1278. else:
  1279. restore_main = False
  1280. # This needs to be undone at the end to prevent holding references to
  1281. # every single object ever created.
  1282. sys.modules[main_mod_name] = main_mod
  1283. stats = None
  1284. try:
  1285. self.shell.savehist()
  1286. if opts.has_key('p'):
  1287. stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
  1288. else:
  1289. if opts.has_key('d'):
  1290. deb = Debugger.Pdb(self.shell.rc.colors)
  1291. # reset Breakpoint state, which is moronically kept
  1292. # in a class
  1293. bdb.Breakpoint.next = 1
  1294. bdb.Breakpoint.bplist = {}
  1295. bdb.Breakpoint.bpbynumber = [None]
  1296. # Set an initial breakpoint to stop execution
  1297. maxtries = 10
  1298. bp = int(opts.get('b',[1])[0])
  1299. checkline = deb.checkline(filename,bp)
  1300. if not checkline:
  1301. for bp in range(bp+1,bp+maxtries+1):
  1302. if deb.checkline(filename,bp):
  1303. break
  1304. else:
  1305. msg = ("\nI failed to find a valid line to set "
  1306. "a breakpoint\n"
  1307. "after trying up to line: %s.\n"
  1308. "Please set a valid breakpoint manually "
  1309. "with the -b option." % bp)
  1310. error(msg)
  1311. return
  1312. # if we find a good linenumber, set the breakpoint
  1313. deb.do_break('%s:%s' % (filename,bp))
  1314. # Start file run
  1315. print "NOTE: Enter 'c' at the",
  1316. print "%s prompt to start your script." % deb.prompt
  1317. try:
  1318. deb.run('execfile("%s")' % filename,prog_ns)
  1319. except:
  1320. etype, value, tb = sys.exc_info()
  1321. # Skip three frames in the traceback: the %run one,
  1322. # one inside bdb.py, and the command-line typed by the
  1323. # user (run by exec in pdb itself).
  1324. self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
  1325. else:
  1326. if runner is None:
  1327. runner = self.shell.safe_execfile
  1328. if opts.has_key('t'):
  1329. # timed execution
  1330. try:
  1331. nruns = int(opts['N'][0])
  1332. if nruns < 1:
  1333. error('Number of runs must be >=1')
  1334. return
  1335. except (KeyError):
  1336. nruns = 1
  1337. if nruns == 1:
  1338. t0 = clock2()
  1339. runner(filename,prog_ns,prog_ns,
  1340. exit_ignore=exit_ignore)
  1341. t1 = clock2()
  1342. t_usr = t1[0]-t0[0]
  1343. t_sys = t1[1]-t0[1]
  1344. print "\nIPython CPU timings (estimated):"
  1345. print " User : %10s s." % t_usr
  1346. print " System: %10s s." % t_sys
  1347. else:
  1348. runs = range(nruns)
  1349. t0 = clock2()
  1350. for nr in runs:
  1351. runner(filename,prog_ns,prog_ns,
  1352. exit_ignore=exit_ignore)
  1353. t1 = clock2()
  1354. t_usr = t1[0]-t0[0]
  1355. t_sys = t1[1]-t0[1]
  1356. print "\nIPython CPU timings (estimated):"
  1357. print "Total runs performed:",nruns
  1358. print " Times : %10s %10s" % ('Total','Per run')
  1359. print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
  1360. print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
  1361. else:
  1362. # regular execution
  1363. runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
  1364. if opts.has_key('i'):
  1365. self.shell.user_ns['__name__'] = __name__save
  1366. else:
  1367. # The shell MUST hold a reference to prog_ns so after %run
  1368. # exits, the python deletion mechanism doesn't zero it out
  1369. # (leaving dangling references).
  1370. self.shell.cache_main_mod(prog_ns,filename)
  1371. # update IPython interactive namespace
  1372. # Some forms of read errors on the file may mean the
  1373. # __name__ key was never set; using pop we don't have to
  1374. # worry about a possible KeyError.
  1375. prog_ns.pop('__name__', None)
  1376. self.shell.user_ns.update(prog_ns)
  1377. finally:
  1378. # It's a bit of a mystery why, but __builtins__ can change from
  1379. # being a module to becoming a dict missing some key data after
  1380. # %run. As best I can see, this is NOT something IPython is doing
  1381. # at all, and similar problems have been reported before:
  1382. # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
  1383. # Since this seems to be done by the interpreter itself, the best
  1384. # we can do is to at least restore __builtins__ for the user on
  1385. # exit.
  1386. self.shell.user_ns['__builtins__'] = __builtin__
  1387. # Ensure key global structures are restored
  1388. sys.argv = save_argv
  1389. if restore_main:
  1390. sys.modules['__main__'] = restore_main
  1391. else:
  1392. # Remove from sys.modules the reference to main_mod we'd
  1393. # added. Otherwise it will trap references to objects
  1394. # contained therein.
  1395. del sys.modules[main_mod_name]
  1396. self.shell.reloadhist()
  1397. return stats
  1398. def magic_runlog(self, parameter_s =''):
  1399. """Run files as logs.
  1400. Usage:\\
  1401. %runlog file1 file2 ...
  1402. Run the named files (treating them as log files) in sequence inside
  1403. the interpreter, and return to the prompt. This is much slower than
  1404. %run because each line is executed in a try/except block, but it
  1405. allows running files with syntax errors in them.
  1406. Normally IPython will guess when a file is one of its own logfiles, so
  1407. you can typically use %run even for logs. This shorthand allows you to
  1408. force any file to be treated as a log file."""
  1409. for f in parameter_s.split():
  1410. self.shell.safe_execfile(f,self.shell.user_ns,
  1411. self.shell.user_ns,islog=1)
  1412. @testdec.skip_doctest
  1413. def magic_timeit(self, parameter_s =''):
  1414. """Time execution of a Python statement or expression
  1415. Usage:\\
  1416. %timeit [-n<N> -r<R> [-t|-c]] statement
  1417. Time execution of a Python statement or expression using the timeit
  1418. module.
  1419. Options:
  1420. -n<N>: execute the given statement <N> times in a loop. If this value
  1421. is not given, a fitting value is chosen.
  1422. -r<R>: repeat the loop iteration <R> times and take the best result.
  1423. Default: 3
  1424. -t: use time.time to measure the time, which is the default on Unix.
  1425. This function measures wall time.
  1426. -c: use time.clock to measure the time, which is the default on
  1427. Windows and measures wall time. On Unix, resource.getrusage is used
  1428. instead and returns the CPU user time.
  1429. -p<P>: use a precision of <P> digits to display the timing result.
  1430. Default: 3
  1431. Examples:
  1432. In [1]: %timeit pass
  1433. 10000000 loops, best of 3: 53.3 ns per loop
  1434. In [2]: u = None
  1435. In [3]: %timeit u is None
  1436. 10000000 loops, best of 3: 184 ns per loop
  1437. In [4]: %timeit -r 4 u == None
  1438. 1000000 loops, best of 4: 242 ns per loop
  1439. In [5]: import time
  1440. In [6]: %timeit -n1 time.sleep(2)
  1441. 1 loops, best of 3: 2 s per loop
  1442. The times reported by %timeit will be slightly higher than those
  1443. reported by the timeit.py script when variables are accessed. This is
  1444. due to the fact that %timeit executes the statement in the namespace
  1445. of the shell, compared with timeit.py, which uses a single setup
  1446. statement to import function or create variables. Generally, the bias
  1447. does not matter as long as results from timeit.py are not mixed with
  1448. those from %timeit."""
  1449. import timeit
  1450. import math
  1451. # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
  1452. # certain terminals. Until we figure out a robust way of
  1453. # auto-detecting if the terminal can deal with it, use plain 'us' for
  1454. # microseconds. I am really NOT happy about disabling the proper
  1455. # 'micro' prefix, but crashing is worse... If anyone knows what the
  1456. # right solution for this is, I'm all ears...
  1457. #
  1458. # Note: using
  1459. #
  1460. # s = u'\xb5'
  1461. # s.encode(sys.getdefaultencoding())
  1462. #
  1463. # is not sufficient, as I've seen terminals where that fails but
  1464. # print s
  1465. #
  1466. # succeeds
  1467. #
  1468. # See bug: https://bugs.launchpad.net/ipython/+bug/348466
  1469. #units = [u"s", u"ms",u'\xb5',"ns"]
  1470. units = [u"s", u"ms",u'us',"ns"]
  1471. scaling = [1, 1e3, 1e6, 1e9]
  1472. opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
  1473. posix=False)
  1474. if stmt == "":
  1475. return
  1476. timefunc = timeit.default_timer
  1477. number = int(getattr(opts, "n", 0))
  1478. repeat = int(getattr(opts, "r", timeit.default_repeat))
  1479. precision = int(getattr(opts, "p", 3))
  1480. if hasattr(opts, "t"):
  1481. timefunc = time.time
  1482. if hasattr(opts, "c"):
  1483. timefunc = clock
  1484. timer = timeit.Timer(timer=timefunc)
  1485. # this code has tight coupling to the inner workings of timeit.Timer,
  1486. # but is there a better way to achieve that the code stmt has access
  1487. # to the shell namespace?
  1488. src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
  1489. 'setup': "pass"}
  1490. # Track compilation time so it can be reported if too long
  1491. # Minimum time above which compilation time will be reported
  1492. tc_min = 0.1
  1493. t0 = clock()
  1494. code = compile(src, "<magic-timeit>", "exec")
  1495. tc = clock()-t0
  1496. ns = {}
  1497. exec code in self.shell.user_ns, ns
  1498. timer.inner = ns["inner"]
  1499. if number == 0:
  1500. # determine number so that 0.2 <= total time < 2.0
  1501. number = 1
  1502. for i in range(1, 10):
  1503. if timer.timeit(number) >= 0.2:
  1504. break
  1505. number *= 10
  1506. best = min(timer.repeat(repeat, number)) / number
  1507. if best > 0.0:
  1508. order = min(-int(math.floor(math.log10(best)) // 3), 3)
  1509. else:
  1510. order = 3
  1511. print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
  1512. precision,
  1513. best * scaling[order],
  1514. units[order])
  1515. if tc > tc_min:
  1516. print "Compiler time: %.2f s" % tc
  1517. @testdec.skip_doctest
  1518. def magic_time(self,parameter_s = ''):
  1519. """Time execution of a Python statement or expression.
  1520. The CPU and wall clock times are printed, and the value of the
  1521. expression (if any) is returned. Note that under Win32, system time
  1522. is always reported as 0, since it can not be measured.
  1523. This function provides very basic timing functionality. In Python
  1524. 2.3, the timeit module offers more control and sophistication, so this
  1525. could be rewritten to use it (patches welcome).
  1526. Some examples:
  1527. In [1]: time 2**128
  1528. CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
  1529. Wall time: 0.00
  1530. Out[1]: 340282366920938463463374607431768211456L
  1531. In [2]: n = 1000000
  1532. In [3]: time sum(range(n))
  1533. CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
  1534. Wall time: 1.37
  1535. Out[3]: 499999500000L
  1536. In [4]: time print 'hello world'
  1537. hello world
  1538. CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
  1539. Wall time: 0.00
  1540. Note that the time needed by Python to compile the given expression
  1541. will be reported if it is more than 0.1s. In this example, the
  1542. actual exponentiation is done by Python at compilation time, so while
  1543. the expression can take a noticeable amount of time to compute, that
  1544. time is purely due to the compilation:
  1545. In [5]: time 3**9999;
  1546. CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
  1547. Wall time: 0.00 s
  1548. In [6]: time 3**999999;
  1549. CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
  1550. Wall time: 0.00 s
  1551. Compiler : 0.78 s
  1552. """
  1553. # fail immediately if the given expression can't be compiled
  1554. expr = self.shell.prefilter(parameter_s,False)
  1555. # Minimum time above which compilation time will be reported
  1556. tc_min = 0.1
  1557. try:
  1558. mode = 'eval'
  1559. t0 = clock()
  1560. code = compile(expr,'<timed eval>',mode)
  1561. tc = clock()-t0
  1562. except SyntaxError:
  1563. mode = 'exec'
  1564. t0 = clock()
  1565. code = compile(expr,'<timed exec>',mode)
  1566. tc = clock()-t0
  1567. # skew measurement as little as possible
  1568. glob = self.shell.user_ns
  1569. clk = clock2
  1570. wtime = time.time
  1571. # time execution
  1572. wall_st = wtime()
  1573. if mode=='eval':
  1574. st = clk()
  1575. out = eval(code,glob)
  1576. end = clk()
  1577. else:
  1578. st = clk()
  1579. exec code in glob
  1580. end = clk()
  1581. out = None
  1582. wall_end = wtime()
  1583. # Compute actual times and report
  1584. wall_time = wall_end-wall_st
  1585. cpu_user = end[0]-st[0]
  1586. cpu_sys = end[1]-st[1]
  1587. cpu_tot = cpu_user+cpu_sys
  1588. print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
  1589. (cpu_user,cpu_sys,cpu_tot)
  1590. print "Wall time: %.2f s" % wall_time
  1591. if tc > tc_min:
  1592. print "Compiler : %.2f s" % tc
  1593. return out
  1594. @testdec.skip_doctest
  1595. def magic_macro(self,parameter_s = ''):
  1596. """Define a set of input lines as a macro for future re-execution.
  1597. Usage:\\
  1598. %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
  1599. Options:
  1600. -r: use 'raw' input. By default, the 'processed' history is used,
  1601. so that magics are loaded in their transformed version to valid
  1602. Python. If this option is given, the raw input as typed as the
  1603. command line is used instead.
  1604. This will define a global variable called `name` which is a string
  1605. made of joining the slices and lines you specify (n1,n2,... numbers
  1606. above) from your input history into a single string. This variable
  1607. acts like an automatic function which re-executes those lines as if
  1608. you had typed them. You just type 'name' at the prompt and the code
  1609. executes.
  1610. The notation for indicating number ranges is: n1-n2 means 'use line
  1611. numbers n1,...n2' (the endpoint is included). That is, '5-7' means
  1612. using the lines numbered 5,6 and 7.
  1613. Note: as a 'hidden' feature, you can also use traditional python slice
  1614. notation, where N:M means numbers N through M-1.
  1615. For example, if your history contains (%hist prints it):
  1616. 44: x=1
  1617. 45: y=3
  1618. 46: z=x+y
  1619. 47: print x
  1620. 48: a=5
  1621. 49: print 'x',x,'y',y
  1622. you can create a macro with lines 44 through 47 (included) and line 49
  1623. called my_macro with:
  1624. In [55]: %macro my_macro 44-47 49
  1625. Now, typing `my_macro` (without quotes) will re-execute all this code
  1626. in one pass.
  1627. You don't need to give the line-numbers in order, and any given line
  1628. number can appear multiple times. You can assemble macros with any
  1629. lines from your input history in any order.
  1630. The macro is a simple object which holds its value in an attribute,
  1631. but IPython's display system checks for macros and executes them as
  1632. code instead of printing them when you type their name.
  1633. You can view a macro's contents by explicitly printing it with:
  1634. 'print macro_name'.
  1635. For one-off cases which DON'T contain magic function calls in them you
  1636. can obtain similar results by explicitly executing slices from your
  1637. input history with:
  1638. In [60]: exec In[44:48]+In[49]"""
  1639. opts,args = self.parse_options(parameter_s,'r',mode='list')
  1640. if not args:
  1641. macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
  1642. macs.sort()
  1643. return macs
  1644. if len(args) == 1:
  1645. raise UsageError(
  1646. "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
  1647. name,ranges = args[0], args[1:]
  1648. #print 'rng',ranges # dbg
  1649. lines = self.extract_input_slices(ranges,opts.has_key('r'))
  1650. macro = Macro(lines)
  1651. self.shell.user_ns.update({name:macro})
  1652. print 'Macro `%s` created. To execute, type its name (without quotes).' % name
  1653. print 'Macro contents:'
  1654. print macro,
  1655. def magic_save(self,parameter_s = ''):
  1656. """Save a set of lines to a given filename.
  1657. Usage:\\
  1658. %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
  1659. Options:
  1660. -r: use 'raw' input. By default, the 'processed' history is used,
  1661. so that magics are loaded in their transformed version to valid
  1662. Python. If this option is given, the raw input as typed as the
  1663. command line is used instead.
  1664. This function uses the same syntax as %macro for line extraction, but
  1665. instead of creating a macro it saves the resulting string to the
  1666. filename you specify.
  1667. It adds a '.py' extension to the file if you don't do so yourself, and
  1668. it asks for confirmation before overwriting existing files."""
  1669. opts,args = self.parse_options(parameter_s,'r',mode='list')
  1670. fname,ranges = args[0], args[1:]
  1671. if not fname.endswith('.py'):
  1672. fname += '.py'
  1673. if os.path.isfile(fname):
  1674. ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
  1675. if ans.lower() not in ['y','yes']:
  1676. print 'Operation cancelled.'
  1677. return
  1678. cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
  1679. f = file(fname,'w')
  1680. f.write(cmds)
  1681. f.close()
  1682. print 'The following commands were written to file `%s`:' % fname
  1683. print cmds
  1684. def _edit_macro(self,mname,macro):
  1685. """open an editor with the macro data in a file"""
  1686. filename = self.shell.mktempfile(macro.value)
  1687. self.shell.hooks.editor(filename)
  1688. # and make a new macro object, to replace the old one
  1689. mfile = open(filename)
  1690. mvalue = mfile.read()
  1691. mfile.close()
  1692. self.shell.user_ns[mname] = Macro(mvalue)
  1693. def magic_ed(self,parameter_s=''):
  1694. """Alias to %edit."""
  1695. return self.magic_edit(parameter_s)
  1696. @testdec.skip_doctest
  1697. def magic_edit(self,parameter_s='',last_call=['','']):
  1698. """Bring up an editor and execute the resulting code.
  1699. Usage:
  1700. %edit [options] [args]
  1701. %edit runs IPython's editor hook. The default version of this hook is
  1702. set to call the __IPYTHON__.rc.editor command. This is read from your
  1703. environment variable $EDITOR. If this isn't found, it will default to
  1704. vi under Linux/Unix and to notepad under Windows. See the end of this
  1705. docstring for how to change the editor hook.
  1706. You can also set the value of this editor via the command line option
  1707. '-editor' or in your ipythonrc file. This is useful if you wish to use
  1708. specifically for IPython an editor different from your typical default
  1709. (and for Windows users who typically don't set environment variables).
  1710. This command allows you to conveniently edit multi-line code right in
  1711. your IPython session.
  1712. If called without arguments, %edit opens up an empty editor with a
  1713. temporary file and will execute the contents of this file when you
  1714. close it (don't forget to save it!).
  1715. Options:
  1716. -n <number>: open the editor at a specified line number. By default,
  1717. the IPython editor hook uses the unix syntax 'editor +N filename', but
  1718. you can configure this by providing your own modified hook if your
  1719. favorite editor supports line-number specifications with a different
  1720. syntax.
  1721. -p: this will call the editor with the same data as the previous time
  1722. it was used, regardless of how long ago (in your current session) it
  1723. was.
  1724. -r: use 'raw' input. This option only applies to input taken from the
  1725. user's history. By default, the 'processed' history is used, so that
  1726. magics are loaded in their transformed version to valid Python. If
  1727. this option is given, the raw input as typed as the command line is
  1728. used instead. When you exit the editor, it will be executed by
  1729. IPython's own processor.
  1730. -x: do not execute the edited code immediately upon exit. This is
  1731. mainly useful if you are editing programs which need to be called with
  1732. command line arguments, which you can then do using %run.
  1733. Arguments:
  1734. If arguments are given, the following possibilites exist:
  1735. - The arguments are numbers or pairs of colon-separated numbers (like
  1736. 1 4:8 9). These are interpreted as lines of previous input to be
  1737. loaded into the editor. The syntax is the same of the %macro command.
  1738. - If the argument doesn't start with a number, it is evaluated as a
  1739. variable and its contents loaded into the editor. You can thus edit
  1740. any string which contains python code (including the result of
  1741. previous edits).
  1742. - If the argument is the name of an object (other than a string),
  1743. IPython will try to locate the file where it was defined and open the
  1744. editor at the point where it is defined. You can use `%edit function`
  1745. to load an editor exactly at the point where 'function' is defined,
  1746. edit it and have the file be executed automatically.
  1747. If the object is a macro (see %macro for details), this opens up your
  1748. specified editor with a temporary file containing the macro's data.
  1749. Upon exit, the macro is reloaded with the contents of the file.
  1750. Note: opening at an exact line is only supported under Unix, and some
  1751. editors (like kedit and gedit up to Gnome 2.8) do not understand the
  1752. '+NUMBER' parameter necessary for this feature. Good editors like
  1753. (X)Emacs, vi, jed, pico and joe all do.
  1754. - If the argument is not found as a variable, IPython will look for a
  1755. file with that name (adding .py if necessary) and load it into the
  1756. editor. It will execute its contents with execfile() when you exit,
  1757. loading any code in the file into your interactive namespace.
  1758. After executing your code, %edit will return as output the code you
  1759. typed in the editor (except when it was an existing file). This way
  1760. you can reload the code in further invocations of %edit as a variable,
  1761. via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
  1762. the output.
  1763. Note that %edit is also available through the alias %ed.
  1764. This is an example of creating a simple function inside the editor and
  1765. then modifying it. First, start up the editor:
  1766. In [1]: ed
  1767. Editing... done. Executing edited code...
  1768. Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
  1769. We can then call the function foo():
  1770. In [2]: foo()
  1771. foo() was defined in an editing session
  1772. Now we edit foo. IPython automatically loads the editor with the
  1773. (temporary) file where foo() was previously defined:
  1774. In [3]: ed foo
  1775. Editing... done. Executing edited code...
  1776. And if we call foo() again we get the modified version:
  1777. In [4]: foo()
  1778. foo() has now been changed!
  1779. Here is an example of how to edit a code snippet successive
  1780. times. First we call the editor:
  1781. In [5]: ed
  1782. Editing... done. Executing edited code...
  1783. hello
  1784. Out[5]: "print 'hello'n"
  1785. Now we call it again with the previous output (stored in _):
  1786. In [6]: ed _
  1787. Editing... done. Executing edited code...
  1788. hello world
  1789. Out[6]: "print 'hello world'n"
  1790. Now we call it with the output #8 (stored in _8, also as Out[8]):
  1791. In [7]: ed _8
  1792. Editing... done. Executing edited code...
  1793. hello again
  1794. Out[7]: "print 'hello again'n"
  1795. Changing the default editor hook:
  1796. If you wish to write your own editor hook, you can put it in a
  1797. configuration file which you load at startup time. The default hook
  1798. is defined in the IPython.hooks module, and you can use that as a
  1799. starting example for further modifications. That file also has
  1800. general instructions on how to set a new hook for use once you've
  1801. defined it."""
  1802. # FIXME: This function has become a convoluted mess. It needs a
  1803. # ground-up rewrite with clean, simple logic.
  1804. def make_filename(arg):
  1805. "Make a filename from the given args"
  1806. try:
  1807. filename = get_py_filename(arg)
  1808. except IOError:
  1809. if args.endswith('.py'):
  1810. filename = arg
  1811. else:
  1812. filename = None
  1813. return filename
  1814. # custom exceptions
  1815. class DataIsObject(Exception): pass
  1816. opts,args = self.parse_options(parameter_s,'prxn:')
  1817. # Set a few locals from the options for convenience:
  1818. opts_p = opts.has_key('p')
  1819. opts_r = opts.has_key('r')
  1820. # Default line number value
  1821. lineno = opts.get('n',None)
  1822. if opts_p:
  1823. args = '_%s' % last_call[0]
  1824. if not self.shell.user_ns.has_key(args):
  1825. args = last_call[1]
  1826. # use last_call to remember the state of the previous call, but don't
  1827. # let it be clobbered by successive '-p' calls.
  1828. try:
  1829. last_call[0] = self.shell.outputcache.prompt_count
  1830. if not opts_p:
  1831. last_call[1] = parameter_s
  1832. except:
  1833. pass
  1834. # by default this is done with temp files, except when the given
  1835. # arg is a filename
  1836. use_temp = 1
  1837. if re.match(r'\d',args):
  1838. # Mode where user specifies ranges of lines, like in %macro.
  1839. # This means that you can't edit files whose names begin with
  1840. # numbers this way. Tough.
  1841. ranges = args.split()
  1842. data = ''.join(self.extract_input_slices(ranges,opts_r))
  1843. elif args.endswith('.py'):
  1844. filename = make_filename(args)
  1845. data = ''
  1846. use_temp = 0
  1847. elif args:
  1848. try:
  1849. # Load the parameter given as a variable. If not a string,
  1850. # process it as an object instead (below)
  1851. #print '*** args',args,'type',type(args) # dbg
  1852. data = eval(args,self.shell.user_ns)
  1853. if not type(data) in StringTypes:
  1854. raise DataIsObject
  1855. except (NameError,SyntaxError):
  1856. # given argument is not a variable, try as a filename
  1857. filename = make_filename(args)
  1858. if filename is None:
  1859. warn("Argument given (%s) can't be found as a variable "
  1860. "or as a filename." % args)
  1861. return
  1862. data = ''
  1863. use_temp = 0
  1864. except DataIsObject:
  1865. # macros have a special edit function
  1866. if isinstance(data,Macro):
  1867. self._edit_macro(args,data)
  1868. return
  1869. # For objects, try to edit the file where they are defined
  1870. try:
  1871. filename = inspect.getabsfile(data)
  1872. if 'fakemodule' in filename.lower() and inspect.isclass(data):
  1873. # class created by %edit? Try to find source
  1874. # by looking for method definitions instead, the
  1875. # __module__ in those classes is FakeModule.
  1876. attrs = [getattr(data, aname) for aname in dir(data)]
  1877. for attr in attrs:
  1878. if not inspect.ismethod(attr):
  1879. continue
  1880. filename = inspect.getabsfile(attr)
  1881. if filename and 'fakemodule' not in filename.lower():
  1882. # change the attribute to be the edit target instead
  1883. data = attr
  1884. break
  1885. datafile = 1
  1886. except TypeError:
  1887. filename = make_filename(args)
  1888. datafile = 1
  1889. warn('Could not find file where `%s` is defined.\n'
  1890. 'Opening a file named `%s`' % (args,filename))
  1891. # Now, make sure we can actually read the source (if it was in
  1892. # a temp file it's gone by now).
  1893. if datafile:
  1894. try:
  1895. if lineno is None:
  1896. lineno = inspect.getsourcelines(data)[1]
  1897. except IOError:
  1898. filename = make_filename(args)
  1899. if filename is None:
  1900. warn('The file `%s` where `%s` was defined cannot '
  1901. 'be read.' % (filename,data))
  1902. return
  1903. use_temp = 0
  1904. else:
  1905. data = ''
  1906. if use_temp:
  1907. filename = self.shell.mktempfile(data)
  1908. print 'IPython will make a temporary file named:',filename
  1909. # do actual editing here
  1910. print 'Editing...',
  1911. sys.stdout.flush()
  1912. try:
  1913. self.shell.hooks.editor(filename,lineno)
  1914. except IPython.ipapi.TryNext:
  1915. warn('Could not open editor')
  1916. return
  1917. # XXX TODO: should this be generalized for all string vars?
  1918. # For now, this is special-cased to blocks created by cpaste
  1919. if args.strip() == 'pasted_block':
  1920. self.shell.user_ns['pasted_block'] = file_read(filename)
  1921. if opts.has_key('x'): # -x prevents actual execution
  1922. print
  1923. else:
  1924. print 'done. Executing edited code...'
  1925. if opts_r:
  1926. self.shell.runlines(file_read(filename))
  1927. else:
  1928. self.shell.safe_execfile(filename,self.shell.user_ns,
  1929. self.shell.user_ns)
  1930. if use_temp:
  1931. try:
  1932. return open(filename).read()
  1933. except IOError,msg:
  1934. if msg.filename == filename:
  1935. warn('File not found. Did you forget to save?')
  1936. return
  1937. else:
  1938. self.shell.showtraceback()
  1939. def magic_xmode(self,parameter_s = ''):
  1940. """Switch modes for the exception handlers.
  1941. Valid modes: Plain, Context and Verbose.
  1942. If called without arguments, acts as a toggle."""
  1943. def xmode_switch_err(name):
  1944. warn('Error changing %s exception modes.\n%s' %
  1945. (name,sys.exc_info()[1]))
  1946. shell = self.shell
  1947. new_mode = parameter_s.strip().capitalize()
  1948. try:
  1949. shell.InteractiveTB.set_mode(mode=new_mode)
  1950. print 'Exception reporting mode:',shell.InteractiveTB.mode
  1951. except:
  1952. xmode_switch_err('user')
  1953. # threaded shells use a special handler in sys.excepthook
  1954. if shell.isthreaded:
  1955. try:
  1956. shell.sys_excepthook.set_mode(mode=new_mode)
  1957. except:
  1958. xmode_switch_err('threaded')
  1959. def magic_colors(self,parameter_s = ''):
  1960. """Switch color scheme for prompts, info system and exception handlers.
  1961. Currently implemented schemes: NoColor, Linux, LightBG.
  1962. Color scheme names are not case-sensitive."""
  1963. def color_switch_err(name):
  1964. warn('Error changing %s color schemes.\n%s' %
  1965. (name,sys.exc_info()[1]))
  1966. new_scheme = parameter_s.strip()
  1967. if not new_scheme:
  1968. raise UsageError(
  1969. "%colors: you must specify a color scheme. See '%colors?'")
  1970. return
  1971. # local shortcut
  1972. shell = self.shell
  1973. import IPython.rlineimpl as readline
  1974. if not readline.have_readline and sys.platform == "win32":
  1975. msg = """\
  1976. Proper color support under MS Windows requires the pyreadline library.
  1977. You can find it at:
  1978. http://ipython.scipy.org/moin/PyReadline/Intro
  1979. Gary's readline needs the ctypes module, from:
  1980. http://starship.python.net/crew/theller/ctypes
  1981. (Note that ctypes is already part of Python versions 2.5 and newer).
  1982. Defaulting color scheme to 'NoColor'"""
  1983. new_scheme = 'NoColor'
  1984. warn(msg)
  1985. # readline option is 0
  1986. if not shell.has_readline:
  1987. new_scheme = 'NoColor'
  1988. # Set prompt colors
  1989. try:
  1990. shell.outputcache.set_colors(new_scheme)
  1991. except:
  1992. color_switch_err('prompt')
  1993. else:
  1994. shell.rc.colors = \
  1995. shell.outputcache.color_table.active_scheme_name
  1996. # Set exception colors
  1997. try:
  1998. shell.InteractiveTB.set_colors(scheme = new_scheme)
  1999. shell.SyntaxTB.set_colors(scheme = new_scheme)
  2000. except:
  2001. color_switch_err('exception')
  2002. # threaded shells use a verbose traceback in sys.excepthook
  2003. if shell.isthreaded:
  2004. try:
  2005. shell.sys_excepthook.set_colors(scheme=new_scheme)
  2006. except:
  2007. color_switch_err('system exception handler')
  2008. # Set info (for 'object?') colors
  2009. if shell.rc.color_info:
  2010. try:
  2011. shell.inspector.set_active_scheme(new_scheme)
  2012. except:
  2013. color_switch_err('object inspector')
  2014. else:
  2015. shell.inspector.set_active_scheme('NoColor')
  2016. def magic_color_info(self,parameter_s = ''):
  2017. """Toggle color_info.
  2018. The color_info configuration parameter controls whether colors are
  2019. used for displaying object details (by things like %psource, %pfile or
  2020. the '?' system). This function toggles this value with each call.
  2021. Note that unless you have a fairly recent pager (less works better
  2022. than more) in your system, using colored object information displays
  2023. will not work properly. Test it and see."""
  2024. self.shell.rc.color_info = 1 - self.shell.rc.color_info
  2025. self.magic_colors(self.shell.rc.colors)
  2026. print 'Object introspection functions have now coloring:',
  2027. print ['OFF','ON'][self.shell.rc.color_info]
  2028. def magic_Pprint(self, parameter_s=''):
  2029. """Toggle pretty printing on/off."""
  2030. self.shell.rc.pprint = 1 - self.shell.rc.pprint
  2031. print 'Pretty printing has been turned', \
  2032. ['OFF','ON'][self.shell.rc.pprint]
  2033. def magic_exit(self, parameter_s=''):
  2034. """Exit IPython, confirming if configured to do so.
  2035. You can configure whether IPython asks for confirmation upon exit by
  2036. setting the confirm_exit flag in the ipythonrc file."""
  2037. self.shell.exit()
  2038. def magic_quit(self, parameter_s=''):
  2039. """Exit IPython, confirming if configured to do so (like %exit)"""
  2040. self.shell.exit()
  2041. def magic_Exit(self, parameter_s=''):
  2042. """Exit IPython without confirmation."""
  2043. self.shell.ask_exit()
  2044. #......................................................................
  2045. # Functions to implement unix shell-type things
  2046. @testdec.skip_doctest
  2047. def magic_alias(self, parameter_s = ''):
  2048. """Define an alias for a system command.
  2049. '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
  2050. Then, typing 'alias_name params' will execute the system command 'cmd
  2051. params' (from your underlying operating system).
  2052. Aliases have lower precedence than magic functions and Python normal
  2053. variables, so if 'foo' is both a Python variable and an alias, the
  2054. alias can not be executed until 'del foo' removes the Python variable.
  2055. You can use the %l specifier in an alias definition to represent the
  2056. whole line when the alias is called. For example:
  2057. In [2]: alias all echo "Input in brackets: <%l>"
  2058. In [3]: all hello world
  2059. Input in brackets: <hello world>
  2060. You can also define aliases with parameters using %s specifiers (one
  2061. per parameter):
  2062. In [1]: alias parts echo first %s second %s
  2063. In [2]: %parts A B
  2064. first A second B
  2065. In [3]: %parts A
  2066. Incorrect number of arguments: 2 expected.
  2067. parts is an alias to: 'echo first %s second %s'
  2068. Note that %l and %s are mutually exclusive. You can only use one or
  2069. the other in your aliases.
  2070. Aliases expand Python variables just like system calls using ! or !!
  2071. do: all expressions prefixed with '$' get expanded. For details of
  2072. the semantic rules, see PEP-215:
  2073. http://www.python.org/peps/pep-0215.html. This is the library used by
  2074. IPython for variable expansion. If you want to access a true shell
  2075. variable, an extra $ is necessary to prevent its expansion by IPython:
  2076. In [6]: alias show echo
  2077. In [7]: PATH='A Python string'
  2078. In [8]: show $PATH
  2079. A Python string
  2080. In [9]: show $$PATH
  2081. /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
  2082. You can use the alias facility to acess all of $PATH. See the %rehash
  2083. and %rehashx functions, which automatically create aliases for the
  2084. contents of your $PATH.
  2085. If called with no parameters, %alias prints the current alias table."""
  2086. par = parameter_s.strip()
  2087. if not par:
  2088. stored = self.db.get('stored_aliases', {} )
  2089. atab = self.shell.alias_table
  2090. aliases = atab.keys()
  2091. aliases.sort()
  2092. res = []
  2093. showlast = []
  2094. for alias in aliases:
  2095. special = False
  2096. try:
  2097. tgt = atab[alias][1]
  2098. except (TypeError, AttributeError):
  2099. # unsubscriptable? probably a callable
  2100. tgt = atab[alias]
  2101. special = True
  2102. # 'interesting' aliases
  2103. if (alias in stored or
  2104. special or
  2105. alias.lower() != os.path.splitext(tgt)[0].lower() or
  2106. ' ' in tgt):
  2107. showlast.append((alias, tgt))
  2108. else:
  2109. res.append((alias, tgt ))
  2110. # show most interesting aliases last
  2111. res.extend(showlast)
  2112. print "Total number of aliases:",len(aliases)
  2113. return res
  2114. try:
  2115. alias,cmd = par.split(None,1)
  2116. except:
  2117. print OInspect.getdoc(self.magic_alias)
  2118. else:
  2119. nargs = cmd.count('%s')
  2120. if nargs>0 and cmd.find('%l')>=0:
  2121. error('The %s and %l specifiers are mutually exclusive '
  2122. 'in alias definitions.')
  2123. else: # all looks OK
  2124. self.shell.alias_table[alias] = (nargs,cmd)
  2125. self.shell.alias_table_validate(verbose=0)
  2126. # end magic_alias
  2127. def magic_unalias(self, parameter_s = ''):
  2128. """Remove an alias"""
  2129. aname = parameter_s.strip()
  2130. if aname in self.shell.alias_table:
  2131. del self.shell.alias_table[aname]
  2132. stored = self.db.get('stored_aliases', {} )
  2133. if aname in stored:
  2134. print "Removing %stored alias",aname
  2135. del stored[aname]
  2136. self.db['stored_aliases'] = stored
  2137. def magic_rehashx(self, parameter_s = ''):
  2138. """Update the alias table with all executable files in $PATH.
  2139. This version explicitly checks that every entry in $PATH is a file
  2140. with execute access (os.X_OK), so it is much slower than %rehash.
  2141. Under Windows, it checks executability as a match agains a
  2142. '|'-separated string of extensions, stored in the IPython config
  2143. variable win_exec_ext. This defaults to 'exe|com|bat'.
  2144. This function also resets the root module cache of module completer,
  2145. used on slow filesystems.
  2146. """
  2147. ip = self.api
  2148. # for the benefit of module completer in ipy_completers.py
  2149. del ip.db['rootmodules']
  2150. path = [os.path.abspath(os.path.expanduser(p)) for p in
  2151. os.environ.get('PATH','').split(os.pathsep)]
  2152. path = filter(os.path.isdir,path)
  2153. alias_table = self.shell.alias_table
  2154. syscmdlist = []
  2155. if os.name == 'posix':
  2156. isexec = lambda fname:os.path.isfile(fname) and \
  2157. os.access(fname,os.X_OK)
  2158. else:
  2159. try:
  2160. winext = os.environ['pathext'].replace(';','|').replace('.','')
  2161. except KeyError:
  2162. winext = 'exe|com|bat|py'
  2163. if 'py' not in winext:
  2164. winext += '|py'
  2165. execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
  2166. isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
  2167. savedir = os.getcwd()
  2168. try:
  2169. # write the whole loop for posix/Windows so we don't have an if in
  2170. # the innermost part
  2171. if os.name == 'posix':
  2172. for pdir in path:
  2173. os.chdir(pdir)
  2174. for ff in os.listdir(pdir):
  2175. if isexec(ff) and ff not in self.shell.no_alias:
  2176. # each entry in the alias table must be (N,name),
  2177. # where N is the number of positional arguments of the
  2178. # alias.
  2179. # Dots will be removed from alias names, since ipython
  2180. # assumes names with dots to be python code
  2181. alias_table[ff.replace('.','')] = (0,ff)
  2182. syscmdlist.append(ff)
  2183. else:
  2184. for pdir in path:
  2185. os.chdir(pdir)
  2186. for ff in os.listdir(pdir):
  2187. base, ext = os.path.splitext(ff)
  2188. if isexec(ff) and base.lower() not in self.shell.no_alias:
  2189. if ext.lower() == '.exe':
  2190. ff = base
  2191. alias_table[base.lower().replace('.','')] = (0,ff)
  2192. syscmdlist.append(ff)
  2193. # Make sure the alias table doesn't contain keywords or builtins
  2194. self.shell.alias_table_validate()
  2195. # Call again init_auto_alias() so we get 'rm -i' and other
  2196. # modified aliases since %rehashx will probably clobber them
  2197. # no, we don't want them. if %rehashx clobbers them, good,
  2198. # we'll probably get better versions
  2199. # self.shell.init_auto_alias()
  2200. db = ip.db
  2201. db['syscmdlist'] = syscmdlist
  2202. finally:
  2203. os.chdir(savedir)
  2204. def magic_pwd(self, parameter_s = ''):
  2205. """Return the current working directory path."""
  2206. return os.getcwd()
  2207. def magic_cd(self, parameter_s=''):
  2208. """Change the current working directory.
  2209. This command automatically maintains an internal list of directories
  2210. you visit during your IPython session, in the variable _dh. The
  2211. command %dhist shows this history nicely formatted. You can also
  2212. do 'cd -<tab>' to see directory history conveniently.
  2213. Usage:
  2214. cd 'dir': changes to directory 'dir'.
  2215. cd -: changes to the last visited directory.
  2216. cd -<n>: changes to the n-th directory in the directory history.
  2217. cd --foo: change to directory that matches 'foo' in history
  2218. cd -b <bookmark_name>: jump to a bookmark set by %bookmark
  2219. (note: cd <bookmark_name> is enough if there is no
  2220. directory <bookmark_name>, but a bookmark with the name exists.)
  2221. 'cd -b <tab>' allows you to tab-complete bookmark names.
  2222. Options:
  2223. -q: quiet. Do not print the working directory after the cd command is
  2224. executed. By default IPython's cd command does print this directory,
  2225. since the default prompts do not display path information.
  2226. Note that !cd doesn't work for this purpose because the shell where
  2227. !command runs is immediately discarded after executing 'command'."""
  2228. parameter_s = parameter_s.strip()
  2229. #bkms = self.shell.persist.get("bookmarks",{})
  2230. oldcwd = os.getcwd()
  2231. numcd = re.match(r'(-)(\d+)$',parameter_s)
  2232. # jump in directory history by number
  2233. if numcd:
  2234. nn = int(numcd.group(2))
  2235. try:
  2236. ps = self.shell.user_ns['_dh'][nn]
  2237. except IndexError:
  2238. print 'The requested directory does not exist in history.'
  2239. return
  2240. else:
  2241. opts = {}
  2242. elif parameter_s.startswith('--'):
  2243. ps = None
  2244. fallback = None
  2245. pat = parameter_s[2:]
  2246. dh = self.shell.user_ns['_dh']
  2247. # first search only by basename (last component)
  2248. for ent in reversed(dh):
  2249. if pat in os.path.basename(ent) and os.path.isdir(ent):
  2250. ps = ent
  2251. break
  2252. if fallback is None and pat in ent and os.path.isdir(ent):
  2253. fallback = ent
  2254. # if we have no last part match, pick the first full path match
  2255. if ps is None:
  2256. ps = fallback
  2257. if ps is None:
  2258. print "No matching entry in directory history"
  2259. return
  2260. else:
  2261. opts = {}
  2262. else:
  2263. #turn all non-space-escaping backslashes to slashes,
  2264. # for c:\windows\directory\names\
  2265. parameter_s = re.sub(r'\\(?! )','/', parameter_s)
  2266. opts,ps = self.parse_options(parameter_s,'qb',mode='string')
  2267. # jump to previous
  2268. if ps == '-':
  2269. try:
  2270. ps = self.shell.user_ns['_dh'][-2]
  2271. except IndexError:
  2272. raise UsageError('%cd -: No previous directory to change to.')
  2273. # jump to bookmark if needed
  2274. else:
  2275. if not os.path.isdir(ps) or opts.has_key('b'):
  2276. bkms = self.db.get('bookmarks', {})
  2277. if bkms.has_key(ps):
  2278. target = bkms[ps]
  2279. print '(bookmark:%s) -> %s' % (ps,target)
  2280. ps = target
  2281. else:
  2282. if opts.has_key('b'):
  2283. raise UsageError("Bookmark '%s' not found. "
  2284. "Use '%%bookmark -l' to see your bookmarks." % ps)
  2285. # at this point ps should point to the target dir
  2286. if ps:
  2287. try:
  2288. os.chdir(os.path.expanduser(ps))
  2289. if self.shell.rc.term_title:
  2290. #print 'set term title:',self.shell.rc.term_title # dbg
  2291. platutils.set_term_title('IPy ' + abbrev_cwd())
  2292. except OSError:
  2293. print sys.exc_info()[1]
  2294. else:
  2295. cwd = os.getcwd()
  2296. dhist = self.shell.user_ns['_dh']
  2297. if oldcwd != cwd:
  2298. dhist.append(cwd)
  2299. self.db['dhist'] = compress_dhist(dhist)[-100:]
  2300. else:
  2301. os.chdir(self.shell.home_dir)
  2302. if self.shell.rc.term_title:
  2303. platutils.set_term_title("IPy ~")
  2304. cwd = os.getcwd()
  2305. dhist = self.shell.user_ns['_dh']
  2306. if oldcwd != cwd:
  2307. dhist.append(cwd)
  2308. self.db['dhist'] = compress_dhist(dhist)[-100:]
  2309. if not 'q' in opts and self.shell.user_ns['_dh']:
  2310. print self.shell.user_ns['_dh'][-1]
  2311. def magic_env(self, parameter_s=''):
  2312. """List environment variables."""
  2313. return os.environ.data
  2314. def magic_pushd(self, parameter_s=''):
  2315. """Place the current dir on stack and change directory.
  2316. Usage:\\
  2317. %pushd ['dirname']
  2318. """
  2319. dir_s = self.shell.dir_stack
  2320. tgt = os.path.expanduser(parameter_s)
  2321. cwd = os.getcwd().replace(self.home_dir,'~')
  2322. if tgt:
  2323. self.magic_cd(parameter_s)
  2324. dir_s.insert(0,cwd)
  2325. return self.magic_dirs()
  2326. def magic_popd(self, parameter_s=''):
  2327. """Change to directory popped off the top of the stack.
  2328. """
  2329. if not self.shell.dir_stack:
  2330. raise UsageError("%popd on empty stack")
  2331. top = self.shell.dir_stack.pop(0)
  2332. self.magic_cd(top)
  2333. print "popd ->",top
  2334. def magic_dirs(self, parameter_s=''):
  2335. """Return the current directory stack."""
  2336. return self.shell.dir_stack
  2337. def magic_dhist(self, parameter_s=''):
  2338. """Print your history of visited directories.
  2339. %dhist -> print full history\\
  2340. %dhist n -> print last n entries only\\
  2341. %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
  2342. This history is automatically maintained by the %cd command, and
  2343. always available as the global list variable _dh. You can use %cd -<n>
  2344. to go to directory number <n>.
  2345. Note that most of time, you should view directory history by entering
  2346. cd -<TAB>.
  2347. """
  2348. dh = self.shell.user_ns['_dh']
  2349. if parameter_s:
  2350. try:
  2351. args = map(int,parameter_s.split())
  2352. except:
  2353. self.arg_err(Magic.magic_dhist)
  2354. return
  2355. if len(args) == 1:
  2356. ini,fin = max(len(dh)-(args[0]),0),len(dh)
  2357. elif len(args) == 2:
  2358. ini,fin = args
  2359. else:
  2360. self.arg_err(Magic.magic_dhist)
  2361. return
  2362. else:
  2363. ini,fin = 0,len(dh)
  2364. nlprint(dh,
  2365. header = 'Directory history (kept in _dh)',
  2366. start=ini,stop=fin)
  2367. @testdec.skip_doctest
  2368. def magic_sc(self, parameter_s=''):
  2369. """Shell capture - execute a shell command and capture its output.
  2370. DEPRECATED. Suboptimal, retained for backwards compatibility.
  2371. You should use the form 'var = !command' instead. Example:
  2372. "%sc -l myfiles = ls ~" should now be written as
  2373. "myfiles = !ls ~"
  2374. myfiles.s, myfiles.l and myfiles.n still apply as documented
  2375. below.
  2376. --
  2377. %sc [options] varname=command
  2378. IPython will run the given command using commands.getoutput(), and
  2379. will then update the user's interactive namespace with a variable
  2380. called varname, containing the value of the call. Your command can
  2381. contain shell wildcards, pipes, etc.
  2382. The '=' sign in the syntax is mandatory, and the variable name you
  2383. supply must follow Python's standard conventions for valid names.
  2384. (A special format without variable name exists for internal use)
  2385. Options:
  2386. -l: list output. Split the output on newlines into a list before
  2387. assigning it to the given variable. By default the output is stored
  2388. as a single string.
  2389. -v: verbose. Print the contents of the variable.
  2390. In most cases you should not need to split as a list, because the
  2391. returned value is a special type of string which can automatically
  2392. provide its contents either as a list (split on newlines) or as a
  2393. space-separated string. These are convenient, respectively, either
  2394. for sequential processing or to be passed to a shell command.
  2395. For example:
  2396. # all-random
  2397. # Capture into variable a
  2398. In [1]: sc a=ls *py
  2399. # a is a string with embedded newlines
  2400. In [2]: a
  2401. Out[2]: 'setup.py\\nwin32_manual_post_install.py'
  2402. # which can be seen as a list:
  2403. In [3]: a.l
  2404. Out[3]: ['setup.py', 'win32_manual_post_install.py']
  2405. # or as a whitespace-separated string:
  2406. In [4]: a.s
  2407. Out[4]: 'setup.py win32_manual_post_install.py'
  2408. # a.s is useful to pass as a single command line:
  2409. In [5]: !wc -l $a.s
  2410. 146 setup.py
  2411. 130 win32_manual_post_install.py
  2412. 276 total
  2413. # while the list form is useful to loop over:
  2414. In [6]: for f in a.l:
  2415. ...: !wc -l $f
  2416. ...:
  2417. 146 setup.py
  2418. 130 win32_manual_post_install.py
  2419. Similiarly, the lists returned by the -l option are also special, in
  2420. the sense that you can equally invoke the .s attribute on them to
  2421. automatically get a whitespace-separated string from their contents:
  2422. In [7]: sc -l b=ls *py
  2423. In [8]: b
  2424. Out[8]: ['setup.py', 'win32_manual_post_install.py']
  2425. In [9]: b.s
  2426. Out[9]: 'setup.py win32_manual_post_install.py'
  2427. In summary, both the lists and strings used for ouptut capture have
  2428. the following special attributes:
  2429. .l (or .list) : value as list.
  2430. .n (or .nlstr): value as newline-separated string.
  2431. .s (or .spstr): value as space-separated string.
  2432. """
  2433. opts,args = self.parse_options(parameter_s,'lv')
  2434. # Try to get a variable name and command to run
  2435. try:
  2436. # the variable name must be obtained from the parse_options
  2437. # output, which uses shlex.split to strip options out.
  2438. var,_ = args.split('=',1)
  2439. var = var.strip()
  2440. # But the the command has to be extracted from the original input
  2441. # parameter_s, not on what parse_options returns, to avoid the
  2442. # quote stripping which shlex.split performs on it.
  2443. _,cmd = parameter_s.split('=',1)
  2444. except ValueError:
  2445. var,cmd = '',''
  2446. # If all looks ok, proceed
  2447. out,err = self.shell.getoutputerror(cmd)
  2448. if err:
  2449. print >> Term.cerr,err
  2450. if opts.has_key('l'):
  2451. out = SList(out.split('\n'))
  2452. else:
  2453. out = LSString(out)
  2454. if opts.has_key('v'):
  2455. print '%s ==\n%s' % (var,pformat(out))
  2456. if var:
  2457. self.shell.user_ns.update({var:out})
  2458. else:
  2459. return out
  2460. def magic_sx(self, parameter_s=''):
  2461. """Shell execute - run a shell command and capture its output.
  2462. %sx command
  2463. IPython will run the given command using commands.getoutput(), and
  2464. return the result formatted as a list (split on '\\n'). Since the
  2465. output is _returned_, it will be stored in ipython's regular output
  2466. cache Out[N] and in the '_N' automatic variables.
  2467. Notes:
  2468. 1) If an input line begins with '!!', then %sx is automatically
  2469. invoked. That is, while:
  2470. !ls
  2471. causes ipython to simply issue system('ls'), typing
  2472. !!ls
  2473. is a shorthand equivalent to:
  2474. %sx ls
  2475. 2) %sx differs from %sc in that %sx automatically splits into a list,
  2476. like '%sc -l'. The reason for this is to make it as easy as possible
  2477. to process line-oriented shell output via further python commands.
  2478. %sc is meant to provide much finer control, but requires more
  2479. typing.
  2480. 3) Just like %sc -l, this is a list with special attributes:
  2481. .l (or .list) : value as list.
  2482. .n (or .nlstr): value as newline-separated string.
  2483. .s (or .spstr): value as whitespace-separated string.
  2484. This is very useful when trying to use such lists as arguments to
  2485. system commands."""
  2486. if parameter_s:
  2487. out,err = self.shell.getoutputerror(parameter_s)
  2488. if err:
  2489. print >> Term.cerr,err
  2490. return SList(out.split('\n'))
  2491. def magic_bg(self, parameter_s=''):
  2492. """Run a job in the background, in a separate thread.
  2493. For example,
  2494. %bg myfunc(x,y,z=1)
  2495. will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
  2496. execution starts, a message will be printed indicating the job
  2497. number. If your job number is 5, you can use
  2498. myvar = jobs.result(5) or myvar = jobs[5].result
  2499. to assign this result to variable 'myvar'.
  2500. IPython has a job manager, accessible via the 'jobs' object. You can
  2501. type jobs? to get more information about it, and use jobs.<TAB> to see
  2502. its attributes. All attributes not starting with an underscore are
  2503. meant for public use.
  2504. In particular, look at the jobs.new() method, which is used to create
  2505. new jobs. This magic %bg function is just a convenience wrapper
  2506. around jobs.new(), for expression-based jobs. If you want to create a
  2507. new job with an explicit function object and arguments, you must call
  2508. jobs.new() directly.
  2509. The jobs.new docstring also describes in detail several important
  2510. caveats associated with a thread-based model for background job
  2511. execution. Type jobs.new? for details.
  2512. You can check the status of all jobs with jobs.status().
  2513. The jobs variable is set by IPython into the Python builtin namespace.
  2514. If you ever declare a variable named 'jobs', you will shadow this
  2515. name. You can either delete your global jobs variable to regain
  2516. access to the job manager, or make a new name and assign it manually
  2517. to the manager (stored in IPython's namespace). For example, to
  2518. assign the job manager to the Jobs name, use:
  2519. Jobs = __builtins__.jobs"""
  2520. self.shell.jobs.new(parameter_s,self.shell.user_ns)
  2521. def magic_r(self, parameter_s=''):
  2522. """Repeat previous input.
  2523. Note: Consider using the more powerfull %rep instead!
  2524. If given an argument, repeats the previous command which starts with
  2525. the same string, otherwise it just repeats the previous input.
  2526. Shell escaped commands (with ! as first character) are not recognized
  2527. by this system, only pure python code and magic commands.
  2528. """
  2529. start = parameter_s.strip()
  2530. esc_magic = self.shell.ESC_MAGIC
  2531. # Identify magic commands even if automagic is on (which means
  2532. # the in-memory version is different from that typed by the user).
  2533. if self.shell.rc.automagic:
  2534. start_magic = esc_magic+start
  2535. else:
  2536. start_magic = start
  2537. # Look through the input history in reverse
  2538. for n in range(len(self.shell.input_hist)-2,0,-1):
  2539. input = self.shell.input_hist[n]
  2540. # skip plain 'r' lines so we don't recurse to infinity
  2541. if input != '_ip.magic("r")\n' and \
  2542. (input.startswith(start) or input.startswith(start_magic)):
  2543. #print 'match',`input` # dbg
  2544. print 'Executing:',input,
  2545. self.shell.runlines(input)
  2546. return
  2547. print 'No previous input matching `%s` found.' % start
  2548. def magic_bookmark(self, parameter_s=''):
  2549. """Manage IPython's bookmark system.
  2550. %bookmark <name> - set bookmark to current dir
  2551. %bookmark <name> <dir> - set bookmark to <dir>
  2552. %bookmark -l - list all bookmarks
  2553. %bookmark -d <name> - remove bookmark
  2554. %bookmark -r - remove all bookmarks
  2555. You can later on access a bookmarked folder with:
  2556. %cd -b <name>
  2557. or simply '%cd <name>' if there is no directory called <name> AND
  2558. there is such a bookmark defined.
  2559. Your bookmarks persist through IPython sessions, but they are
  2560. associated with each profile."""
  2561. opts,args = self.parse_options(parameter_s,'drl',mode='list')
  2562. if len(args) > 2:
  2563. raise UsageError("%bookmark: too many arguments")
  2564. bkms = self.db.get('bookmarks',{})
  2565. if opts.has_key('d'):
  2566. try:
  2567. todel = args[0]
  2568. except IndexError:
  2569. raise UsageError(
  2570. "%bookmark -d: must provide a bookmark to delete")
  2571. else:
  2572. try:
  2573. del bkms[todel]
  2574. except KeyError:
  2575. raise UsageError(
  2576. "%%bookmark -d: Can't delete bookmark '%s'" % todel)
  2577. elif opts.has_key('r'):
  2578. bkms = {}
  2579. elif opts.has_key('l'):
  2580. bks = bkms.keys()
  2581. bks.sort()
  2582. if bks:
  2583. size = max(map(len,bks))
  2584. else:
  2585. size = 0
  2586. fmt = '%-'+str(size)+'s -> %s'
  2587. print 'Current bookmarks:'
  2588. for bk in bks:
  2589. print fmt % (bk,bkms[bk])
  2590. else:
  2591. if not args:
  2592. raise UsageError("%bookmark: You must specify the bookmark name")
  2593. elif len(args)==1:
  2594. bkms[args[0]] = os.getcwd()
  2595. elif len(args)==2:
  2596. bkms[args[0]] = args[1]
  2597. self.db['bookmarks'] = bkms
  2598. def magic_pycat(self, parameter_s=''):
  2599. """Show a syntax-highlighted file through a pager.
  2600. This magic is similar to the cat utility, but it will assume the file
  2601. to be Python source and will show it with syntax highlighting. """
  2602. try:
  2603. filename = get_py_filename(parameter_s)
  2604. cont = file_read(filename)
  2605. except IOError:
  2606. try:
  2607. cont = eval(parameter_s,self.user_ns)
  2608. except NameError:
  2609. cont = None
  2610. if cont is None:
  2611. print "Error: no such file or variable"
  2612. return
  2613. page(self.shell.pycolorize(cont),
  2614. screen_lines=self.shell.rc.screen_length)
  2615. def _rerun_pasted(self):
  2616. """ Rerun a previously pasted command.
  2617. """
  2618. b = self.user_ns.get('pasted_block', None)
  2619. if b is None:
  2620. raise UsageError('No previous pasted block available')
  2621. print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
  2622. exec b in self.user_ns
  2623. def _get_pasted_lines(self, sentinel):
  2624. """ Yield pasted lines until the user enters the given sentinel value.
  2625. """
  2626. from IPython import iplib
  2627. print "Pasting code; enter '%s' alone on the line to stop." % sentinel
  2628. while True:
  2629. l = iplib.raw_input_original(':')
  2630. if l == sentinel:
  2631. return
  2632. else:
  2633. yield l
  2634. def _strip_pasted_lines_for_code(self, raw_lines):
  2635. """ Strip non-code parts of a sequence of lines to return a block of
  2636. code.
  2637. """
  2638. # Regular expressions that declare text we strip from the input:
  2639. strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
  2640. r'^\s*(\s?>)+', # Python input prompt
  2641. r'^\s*\.{3,}', # Continuation prompts
  2642. r'^\++',
  2643. ]
  2644. strip_from_start = map(re.compile,strip_re)
  2645. lines = []
  2646. for l in raw_lines:
  2647. for pat in strip_from_start:
  2648. l = pat.sub('',l)
  2649. lines.append(l)
  2650. block = "\n".join(lines) + '\n'
  2651. #print "block:\n",block
  2652. return block
  2653. def _execute_block(self, block, par):
  2654. """ Execute a block, or store it in a variable, per the user's request.
  2655. """
  2656. if not par:
  2657. b = textwrap.dedent(block)
  2658. self.user_ns['pasted_block'] = b
  2659. exec b in self.user_ns
  2660. else:
  2661. self.user_ns[par] = SList(block.splitlines())
  2662. print "Block assigned to '%s'" % par
  2663. def magic_cpaste(self, parameter_s=''):
  2664. """Allows you to paste & execute a pre-formatted code block from clipboard.
  2665. You must terminate the block with '--' (two minus-signs) alone on the
  2666. line. You can also provide your own sentinel with '%paste -s %%' ('%%'
  2667. is the new sentinel for this operation)
  2668. The block is dedented prior to execution to enable execution of method
  2669. definitions. '>' and '+' characters at the beginning of a line are
  2670. ignored, to allow pasting directly from e-mails, diff files and
  2671. doctests (the '...' continuation prompt is also stripped). The
  2672. executed block is also assigned to variable named 'pasted_block' for
  2673. later editing with '%edit pasted_block'.
  2674. You can also pass a variable name as an argument, e.g. '%cpaste foo'.
  2675. This assigns the pasted block to variable 'foo' as string, without
  2676. dedenting or executing it (preceding >>> and + is still stripped)
  2677. '%cpaste -r' re-executes the block previously entered by cpaste.
  2678. Do not be alarmed by garbled output on Windows (it's a readline bug).
  2679. Just press enter and type -- (and press enter again) and the block
  2680. will be what was just pasted.
  2681. IPython statements (magics, shell escapes) are not supported (yet).
  2682. See also
  2683. --------
  2684. paste: automatically pull code from clipboard.
  2685. """
  2686. opts,args = self.parse_options(parameter_s,'rs:',mode='string')
  2687. par = args.strip()
  2688. if opts.has_key('r'):
  2689. self._rerun_pasted()
  2690. return
  2691. sentinel = opts.get('s','--')
  2692. block = self._strip_pasted_lines_for_code(
  2693. self._get_pasted_lines(sentinel))
  2694. self._execute_block(block, par)
  2695. def magic_paste(self, parameter_s=''):
  2696. """Allows you to paste & execute a pre-formatted code block from clipboard.
  2697. The text is pulled directly from the clipboard without user
  2698. intervention.
  2699. The block is dedented prior to execution to enable execution of method
  2700. definitions. '>' and '+' characters at the beginning of a line are
  2701. ignored, to allow pasting directly from e-mails, diff files and
  2702. doctests (the '...' continuation prompt is also stripped). The
  2703. executed block is also assigned to variable named 'pasted_block' for
  2704. later editing with '%edit pasted_block'.
  2705. You can also pass a variable name as an argument, e.g. '%paste foo'.
  2706. This assigns the pasted block to variable 'foo' as string, without
  2707. dedenting or executing it (preceding >>> and + is still stripped)
  2708. '%paste -r' re-executes the block previously entered by cpaste.
  2709. IPython statements (magics, shell escapes) are not supported (yet).
  2710. See also
  2711. --------
  2712. cpaste: manually paste code into terminal until you mark its end.
  2713. """
  2714. opts,args = self.parse_options(parameter_s,'r:',mode='string')
  2715. par = args.strip()
  2716. if opts.has_key('r'):
  2717. self._rerun_pasted()
  2718. return
  2719. text = self.shell.hooks.clipboard_get()
  2720. block = self._strip_pasted_lines_for_code(text.splitlines())
  2721. self._execute_block(block, par)
  2722. def magic_quickref(self,arg):
  2723. """ Show a quick reference sheet """
  2724. import IPython.usage
  2725. qr = IPython.usage.quick_reference + self.magic_magic('-brief')
  2726. page(qr)
  2727. def magic_upgrade(self,arg):
  2728. """ Upgrade your IPython installation
  2729. This will copy the config files that don't yet exist in your
  2730. ipython dir from the system config dir. Use this after upgrading
  2731. IPython if you don't wish to delete your .ipython dir.
  2732. Call with -nolegacy to get rid of ipythonrc* files (recommended for
  2733. new users)
  2734. """
  2735. ip = self.getapi()
  2736. ipinstallation = path(IPython.__file__).dirname()
  2737. upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py')
  2738. src_config = ipinstallation / 'UserConfig'
  2739. userdir = path(ip.options.ipythondir)
  2740. cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
  2741. print ">",cmd
  2742. shell(cmd)
  2743. if arg == '-nolegacy':
  2744. legacy = userdir.files('ipythonrc*')
  2745. print "Nuking legacy files:",legacy
  2746. [p.remove() for p in legacy]
  2747. suffix = (sys.platform == 'win32' and '.ini' or '')
  2748. (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
  2749. def magic_doctest_mode(self,parameter_s=''):
  2750. """Toggle doctest mode on and off.
  2751. This mode allows you to toggle the prompt behavior between normal
  2752. IPython prompts and ones that are as similar to the default IPython
  2753. interpreter as possible.
  2754. It also supports the pasting of code snippets that have leading '>>>'
  2755. and '...' prompts in them. This means that you can paste doctests from
  2756. files or docstrings (even if they have leading whitespace), and the
  2757. code will execute correctly. You can then use '%history -tn' to see
  2758. the translated history without line numbers; this will give you the
  2759. input after removal of all the leading prompts and whitespace, which
  2760. can be pasted back into an editor.
  2761. With these features, you can switch into this mode easily whenever you
  2762. need to do testing and changes to doctests, without having to leave
  2763. your existing IPython session.
  2764. """
  2765. # XXX - Fix this to have cleaner activate/deactivate calls.
  2766. from IPython.Extensions import InterpreterPasteInput as ipaste
  2767. from IPython.ipstruct import Struct
  2768. # Shorthands
  2769. shell = self.shell
  2770. oc = shell.outputcache
  2771. rc = shell.rc
  2772. meta = shell.meta
  2773. # dstore is a data store kept in the instance metadata bag to track any
  2774. # changes we make, so we can undo them later.
  2775. dstore = meta.setdefault('doctest_mode',Struct())
  2776. save_dstore = dstore.setdefault
  2777. # save a few values we'll need to recover later
  2778. mode = save_dstore('mode',False)
  2779. save_dstore('rc_pprint',rc.pprint)
  2780. save_dstore('xmode',shell.InteractiveTB.mode)
  2781. save_dstore('rc_separate_out',rc.separate_out)
  2782. save_dstore('rc_separate_out2',rc.separate_out2)
  2783. save_dstore('rc_prompts_pad_left',rc.prompts_pad_left)
  2784. save_dstore('rc_separate_in',rc.separate_in)
  2785. if mode == False:
  2786. # turn on
  2787. ipaste.activate_prefilter()
  2788. oc.prompt1.p_template = '>>> '
  2789. oc.prompt2.p_template = '... '
  2790. oc.prompt_out.p_template = ''
  2791. # Prompt separators like plain python
  2792. oc.input_sep = oc.prompt1.sep = ''
  2793. oc.output_sep = ''
  2794. oc.output_sep2 = ''
  2795. oc.prompt1.pad_left = oc.prompt2.pad_left = \
  2796. oc.prompt_out.pad_left = False
  2797. rc.pprint = False
  2798. shell.magic_xmode('Plain')
  2799. else:
  2800. # turn off
  2801. ipaste.deactivate_prefilter()
  2802. oc.prompt1.p_template = rc.prompt_in1
  2803. oc.prompt2.p_template = rc.prompt_in2
  2804. oc.prompt_out.p_template = rc.prompt_out
  2805. oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
  2806. oc.output_sep = dstore.rc_separate_out
  2807. oc.output_sep2 = dstore.rc_separate_out2
  2808. oc.prompt1.pad_left = oc.prompt2.pad_left = \
  2809. oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
  2810. rc.pprint = dstore.rc_pprint
  2811. shell.magic_xmode(dstore.xmode)
  2812. # Store new mode and inform
  2813. dstore.mode = bool(1-int(mode))
  2814. print 'Doctest mode is:',
  2815. print ['OFF','ON'][dstore.mode]
  2816. # end Magic