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