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