##// END OF EJS Templates
Terminal IPython working with newapp
MinRK -
Show More
@@ -1,802 +1,799
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 datetime
18 18 import os
19 19 import re
20 20 import sqlite3
21 21 import threading
22 22
23 23 # Our own packages
24 24 from IPython.config.configurable import Configurable
25 25
26 26 from IPython.testing.skipdoctest import skip_doctest
27 27 from IPython.utils import io
28 28 from IPython.utils.traitlets import Bool, Dict, Instance, Int, List, Unicode
29 29 from IPython.utils.warn import warn
30 30
31 31 #-----------------------------------------------------------------------------
32 32 # Classes and functions
33 33 #-----------------------------------------------------------------------------
34 34
35 35 class HistoryManager(Configurable):
36 36 """A class to organize all history-related functionality in one place.
37 37 """
38 38 # Public interface
39 39
40 40 # An instance of the IPython shell we are attached to
41 41 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
42 42 # Lists to hold processed and raw history. These start with a blank entry
43 43 # so that we can index them starting from 1
44 44 input_hist_parsed = List([""])
45 45 input_hist_raw = List([""])
46 46 # A list of directories visited during session
47 47 dir_hist = List()
48 48 def _dir_hist_default(self):
49 49 try:
50 50 return [os.getcwd()]
51 51 except OSError:
52 52 return []
53 53
54 54 # A dict of output history, keyed with ints from the shell's
55 55 # execution count.
56 56 output_hist = Dict()
57 57 # The text/plain repr of outputs.
58 58 output_hist_reprs = Dict()
59 59
60 60 # String holding the path to the history file
61 61 hist_file = Unicode(config=True)
62 62
63 63 # The SQLite database
64 64 db = Instance(sqlite3.Connection)
65 65 # The number of the current session in the history database
66 66 session_number = Int()
67 67 # Should we log output to the database? (default no)
68 68 db_log_output = Bool(False, config=True)
69 69 # Write to database every x commands (higher values save disk access & power)
70 70 # Values of 1 or less effectively disable caching.
71 71 db_cache_size = Int(0, config=True)
72 72 # The input and output caches
73 73 db_input_cache = List()
74 74 db_output_cache = List()
75 75
76 76 # History saving in separate thread
77 77 save_thread = Instance('IPython.core.history.HistorySavingThread')
78 78 # N.B. Event is a function returning an instance of _Event.
79 79 save_flag = Instance(threading._Event)
80 80
81 81 # Private interface
82 82 # Variables used to store the three last inputs from the user. On each new
83 83 # history update, we populate the user's namespace with these, shifted as
84 84 # necessary.
85 85 _i00 = Unicode(u'')
86 86 _i = Unicode(u'')
87 87 _ii = Unicode(u'')
88 88 _iii = Unicode(u'')
89 89
90 90 # A regex matching all forms of the exit command, so that we don't store
91 91 # them in the history (it's annoying to rewind the first entry and land on
92 92 # an exit call).
93 93 _exit_re = re.compile(r"(exit|quit)(\s*\(.*\))?$")
94 94
95 95 def __init__(self, shell, config=None, **traits):
96 96 """Create a new history manager associated with a shell instance.
97 97 """
98 98 # We need a pointer back to the shell for various tasks.
99 99 super(HistoryManager, self).__init__(shell=shell, config=config,
100 100 **traits)
101 101
102 102 if self.hist_file == u'':
103 103 # No one has set the hist_file, yet.
104 if shell.profile:
105 histfname = 'history-%s' % shell.profile
106 else:
107 histfname = 'history'
108 self.hist_file = os.path.join(shell.ipython_dir, histfname + '.sqlite')
104 histfname = 'history'
105 self.hist_file = os.path.join(shell.profile_dir.location, histfname + '.sqlite')
109 106
110 107 try:
111 108 self.init_db()
112 109 except sqlite3.DatabaseError:
113 110 if os.path.isfile(self.hist_file):
114 111 # Try to move the file out of the way.
115 newpath = os.path.join(self.shell.ipython_dir, "hist-corrupt.sqlite")
112 newpath = os.path.join(self.shell.profile_dir.location, "hist-corrupt.sqlite")
116 113 os.rename(self.hist_file, newpath)
117 114 print("ERROR! History file wasn't a valid SQLite database.",
118 115 "It was moved to %s" % newpath, "and a new file created.")
119 116 self.init_db()
120 117 else:
121 118 # The hist_file is probably :memory: or something else.
122 119 raise
123 120
124 121 self.save_flag = threading.Event()
125 122 self.db_input_cache_lock = threading.Lock()
126 123 self.db_output_cache_lock = threading.Lock()
127 124 self.save_thread = HistorySavingThread(self)
128 125 self.save_thread.start()
129 126
130 127 self.new_session()
131 128
132 129
133 130 def init_db(self):
134 131 """Connect to the database, and create tables if necessary."""
135 132 self.db = sqlite3.connect(self.hist_file)
136 133 self.db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer
137 134 primary key autoincrement, start timestamp,
138 135 end timestamp, num_cmds integer, remark text)""")
139 136 self.db.execute("""CREATE TABLE IF NOT EXISTS history
140 137 (session integer, line integer, source text, source_raw text,
141 138 PRIMARY KEY (session, line))""")
142 139 # Output history is optional, but ensure the table's there so it can be
143 140 # enabled later.
144 141 self.db.execute("""CREATE TABLE IF NOT EXISTS output_history
145 142 (session integer, line integer, output text,
146 143 PRIMARY KEY (session, line))""")
147 144 self.db.commit()
148 145
149 146 def new_session(self, conn=None):
150 147 """Get a new session number."""
151 148 if conn is None:
152 149 conn = self.db
153 150
154 151 with conn:
155 152 cur = conn.execute("""INSERT INTO sessions VALUES (NULL, ?, NULL,
156 153 NULL, "") """, (datetime.datetime.now(),))
157 154 self.session_number = cur.lastrowid
158 155
159 156 def end_session(self):
160 157 """Close the database session, filling in the end time and line count."""
161 158 self.writeout_cache()
162 159 with self.db:
163 160 self.db.execute("""UPDATE sessions SET end=?, num_cmds=? WHERE
164 161 session==?""", (datetime.datetime.now(),
165 162 len(self.input_hist_parsed)-1, self.session_number))
166 163 self.session_number = 0
167 164
168 165 def name_session(self, name):
169 166 """Give the current session a name in the history database."""
170 167 with self.db:
171 168 self.db.execute("UPDATE sessions SET remark=? WHERE session==?",
172 169 (name, self.session_number))
173 170
174 171 def reset(self, new_session=True):
175 172 """Clear the session history, releasing all object references, and
176 173 optionally open a new session."""
177 174 self.output_hist.clear()
178 175 # The directory history can't be completely empty
179 176 self.dir_hist[:] = [os.getcwd()]
180 177
181 178 if new_session:
182 179 if self.session_number:
183 180 self.end_session()
184 181 self.input_hist_parsed[:] = [""]
185 182 self.input_hist_raw[:] = [""]
186 183 self.new_session()
187 184
188 185 ## -------------------------------
189 186 ## Methods for retrieving history:
190 187 ## -------------------------------
191 188 def _run_sql(self, sql, params, raw=True, output=False):
192 189 """Prepares and runs an SQL query for the history database.
193 190
194 191 Parameters
195 192 ----------
196 193 sql : str
197 194 Any filtering expressions to go after SELECT ... FROM ...
198 195 params : tuple
199 196 Parameters passed to the SQL query (to replace "?")
200 197 raw, output : bool
201 198 See :meth:`get_range`
202 199
203 200 Returns
204 201 -------
205 202 Tuples as :meth:`get_range`
206 203 """
207 204 toget = 'source_raw' if raw else 'source'
208 205 sqlfrom = "history"
209 206 if output:
210 207 sqlfrom = "history LEFT JOIN output_history USING (session, line)"
211 208 toget = "history.%s, output_history.output" % toget
212 209 cur = self.db.execute("SELECT session, line, %s FROM %s " %\
213 210 (toget, sqlfrom) + sql, params)
214 211 if output: # Regroup into 3-tuples, and parse JSON
215 212 return ((ses, lin, (inp, out)) for ses, lin, inp, out in cur)
216 213 return cur
217 214
218 215
219 216 def get_tail(self, n=10, raw=True, output=False, include_latest=False):
220 217 """Get the last n lines from the history database.
221 218
222 219 Parameters
223 220 ----------
224 221 n : int
225 222 The number of lines to get
226 223 raw, output : bool
227 224 See :meth:`get_range`
228 225 include_latest : bool
229 226 If False (default), n+1 lines are fetched, and the latest one
230 227 is discarded. This is intended to be used where the function
231 228 is called by a user command, which it should not return.
232 229
233 230 Returns
234 231 -------
235 232 Tuples as :meth:`get_range`
236 233 """
237 234 self.writeout_cache()
238 235 if not include_latest:
239 236 n += 1
240 237 cur = self._run_sql("ORDER BY session DESC, line DESC LIMIT ?",
241 238 (n,), raw=raw, output=output)
242 239 if not include_latest:
243 240 return reversed(list(cur)[1:])
244 241 return reversed(list(cur))
245 242
246 243 def search(self, pattern="*", raw=True, search_raw=True,
247 244 output=False):
248 245 """Search the database using unix glob-style matching (wildcards
249 246 * and ?).
250 247
251 248 Parameters
252 249 ----------
253 250 pattern : str
254 251 The wildcarded pattern to match when searching
255 252 search_raw : bool
256 253 If True, search the raw input, otherwise, the parsed input
257 254 raw, output : bool
258 255 See :meth:`get_range`
259 256
260 257 Returns
261 258 -------
262 259 Tuples as :meth:`get_range`
263 260 """
264 261 tosearch = "source_raw" if search_raw else "source"
265 262 if output:
266 263 tosearch = "history." + tosearch
267 264 self.writeout_cache()
268 265 return self._run_sql("WHERE %s GLOB ?" % tosearch, (pattern,),
269 266 raw=raw, output=output)
270 267
271 268 def _get_range_session(self, start=1, stop=None, raw=True, output=False):
272 269 """Get input and output history from the current session. Called by
273 270 get_range, and takes similar parameters."""
274 271 input_hist = self.input_hist_raw if raw else self.input_hist_parsed
275 272
276 273 n = len(input_hist)
277 274 if start < 0:
278 275 start += n
279 276 if not stop:
280 277 stop = n
281 278 elif stop < 0:
282 279 stop += n
283 280
284 281 for i in range(start, stop):
285 282 if output:
286 283 line = (input_hist[i], self.output_hist_reprs.get(i))
287 284 else:
288 285 line = input_hist[i]
289 286 yield (0, i, line)
290 287
291 288 def get_range(self, session=0, start=1, stop=None, raw=True,output=False):
292 289 """Retrieve input by session.
293 290
294 291 Parameters
295 292 ----------
296 293 session : int
297 294 Session number to retrieve. The current session is 0, and negative
298 295 numbers count back from current session, so -1 is previous session.
299 296 start : int
300 297 First line to retrieve.
301 298 stop : int
302 299 End of line range (excluded from output itself). If None, retrieve
303 300 to the end of the session.
304 301 raw : bool
305 302 If True, return untranslated input
306 303 output : bool
307 304 If True, attempt to include output. This will be 'real' Python
308 305 objects for the current session, or text reprs from previous
309 306 sessions if db_log_output was enabled at the time. Where no output
310 307 is found, None is used.
311 308
312 309 Returns
313 310 -------
314 311 An iterator over the desired lines. Each line is a 3-tuple, either
315 312 (session, line, input) if output is False, or
316 313 (session, line, (input, output)) if output is True.
317 314 """
318 315 if session == 0 or session==self.session_number: # Current session
319 316 return self._get_range_session(start, stop, raw, output)
320 317 if session < 0:
321 318 session += self.session_number
322 319
323 320 if stop:
324 321 lineclause = "line >= ? AND line < ?"
325 322 params = (session, start, stop)
326 323 else:
327 324 lineclause = "line>=?"
328 325 params = (session, start)
329 326
330 327 return self._run_sql("WHERE session==? AND %s""" % lineclause,
331 328 params, raw=raw, output=output)
332 329
333 330 def get_range_by_str(self, rangestr, raw=True, output=False):
334 331 """Get lines of history from a string of ranges, as used by magic
335 332 commands %hist, %save, %macro, etc.
336 333
337 334 Parameters
338 335 ----------
339 336 rangestr : str
340 337 A string specifying ranges, e.g. "5 ~2/1-4". See
341 338 :func:`magic_history` for full details.
342 339 raw, output : bool
343 340 As :meth:`get_range`
344 341
345 342 Returns
346 343 -------
347 344 Tuples as :meth:`get_range`
348 345 """
349 346 for sess, s, e in extract_hist_ranges(rangestr):
350 347 for line in self.get_range(sess, s, e, raw=raw, output=output):
351 348 yield line
352 349
353 350 ## ----------------------------
354 351 ## Methods for storing history:
355 352 ## ----------------------------
356 353 def store_inputs(self, line_num, source, source_raw=None):
357 354 """Store source and raw input in history and create input cache
358 355 variables _i*.
359 356
360 357 Parameters
361 358 ----------
362 359 line_num : int
363 360 The prompt number of this input.
364 361
365 362 source : str
366 363 Python input.
367 364
368 365 source_raw : str, optional
369 366 If given, this is the raw input without any IPython transformations
370 367 applied to it. If not given, ``source`` is used.
371 368 """
372 369 if source_raw is None:
373 370 source_raw = source
374 371 source = source.rstrip('\n')
375 372 source_raw = source_raw.rstrip('\n')
376 373
377 374 # do not store exit/quit commands
378 375 if self._exit_re.match(source_raw.strip()):
379 376 return
380 377
381 378 self.input_hist_parsed.append(source)
382 379 self.input_hist_raw.append(source_raw)
383 380
384 381 with self.db_input_cache_lock:
385 382 self.db_input_cache.append((line_num, source, source_raw))
386 383 # Trigger to flush cache and write to DB.
387 384 if len(self.db_input_cache) >= self.db_cache_size:
388 385 self.save_flag.set()
389 386
390 387 # update the auto _i variables
391 388 self._iii = self._ii
392 389 self._ii = self._i
393 390 self._i = self._i00
394 391 self._i00 = source_raw
395 392
396 393 # hackish access to user namespace to create _i1,_i2... dynamically
397 394 new_i = '_i%s' % line_num
398 395 to_main = {'_i': self._i,
399 396 '_ii': self._ii,
400 397 '_iii': self._iii,
401 398 new_i : self._i00 }
402 399 self.shell.user_ns.update(to_main)
403 400
404 401 def store_output(self, line_num):
405 402 """If database output logging is enabled, this saves all the
406 403 outputs from the indicated prompt number to the database. It's
407 404 called by run_cell after code has been executed.
408 405
409 406 Parameters
410 407 ----------
411 408 line_num : int
412 409 The line number from which to save outputs
413 410 """
414 411 if (not self.db_log_output) or (line_num not in self.output_hist_reprs):
415 412 return
416 413 output = self.output_hist_reprs[line_num]
417 414
418 415 with self.db_output_cache_lock:
419 416 self.db_output_cache.append((line_num, output))
420 417 if self.db_cache_size <= 1:
421 418 self.save_flag.set()
422 419
423 420 def _writeout_input_cache(self, conn):
424 421 with conn:
425 422 for line in self.db_input_cache:
426 423 conn.execute("INSERT INTO history VALUES (?, ?, ?, ?)",
427 424 (self.session_number,)+line)
428 425
429 426 def _writeout_output_cache(self, conn):
430 427 with conn:
431 428 for line in self.db_output_cache:
432 429 conn.execute("INSERT INTO output_history VALUES (?, ?, ?)",
433 430 (self.session_number,)+line)
434 431
435 432 def writeout_cache(self, conn=None):
436 433 """Write any entries in the cache to the database."""
437 434 if conn is None:
438 435 conn = self.db
439 436
440 437 with self.db_input_cache_lock:
441 438 try:
442 439 self._writeout_input_cache(conn)
443 440 except sqlite3.IntegrityError:
444 441 self.new_session(conn)
445 442 print("ERROR! Session/line number was not unique in",
446 443 "database. History logging moved to new session",
447 444 self.session_number)
448 445 try: # Try writing to the new session. If this fails, don't recurse
449 446 self._writeout_input_cache(conn)
450 447 except sqlite3.IntegrityError:
451 448 pass
452 449 finally:
453 450 self.db_input_cache = []
454 451
455 452 with self.db_output_cache_lock:
456 453 try:
457 454 self._writeout_output_cache(conn)
458 455 except sqlite3.IntegrityError:
459 456 print("!! Session/line number for output was not unique",
460 457 "in database. Output will not be stored.")
461 458 finally:
462 459 self.db_output_cache = []
463 460
464 461
465 462 class HistorySavingThread(threading.Thread):
466 463 """This thread takes care of writing history to the database, so that
467 464 the UI isn't held up while that happens.
468 465
469 466 It waits for the HistoryManager's save_flag to be set, then writes out
470 467 the history cache. The main thread is responsible for setting the flag when
471 468 the cache size reaches a defined threshold."""
472 469 daemon = True
473 470 stop_now = False
474 471 def __init__(self, history_manager):
475 472 super(HistorySavingThread, self).__init__()
476 473 self.history_manager = history_manager
477 474 atexit.register(self.stop)
478 475
479 476 def run(self):
480 477 # We need a separate db connection per thread:
481 478 try:
482 479 self.db = sqlite3.connect(self.history_manager.hist_file)
483 480 while True:
484 481 self.history_manager.save_flag.wait()
485 482 if self.stop_now:
486 483 return
487 484 self.history_manager.save_flag.clear()
488 485 self.history_manager.writeout_cache(self.db)
489 486 except Exception as e:
490 487 print(("The history saving thread hit an unexpected error (%s)."
491 488 "History will not be written to the database.") % repr(e))
492 489
493 490 def stop(self):
494 491 """This can be called from the main thread to safely stop this thread.
495 492
496 493 Note that it does not attempt to write out remaining history before
497 494 exiting. That should be done by calling the HistoryManager's
498 495 end_session method."""
499 496 self.stop_now = True
500 497 self.history_manager.save_flag.set()
501 498 self.join()
502 499
503 500
504 501 # To match, e.g. ~5/8-~2/3
505 502 range_re = re.compile(r"""
506 503 ((?P<startsess>~?\d+)/)?
507 504 (?P<start>\d+) # Only the start line num is compulsory
508 505 ((?P<sep>[\-:])
509 506 ((?P<endsess>~?\d+)/)?
510 507 (?P<end>\d+))?
511 508 $""", re.VERBOSE)
512 509
513 510 def extract_hist_ranges(ranges_str):
514 511 """Turn a string of history ranges into 3-tuples of (session, start, stop).
515 512
516 513 Examples
517 514 --------
518 515 list(extract_input_ranges("~8/5-~7/4 2"))
519 516 [(-8, 5, None), (-7, 1, 4), (0, 2, 3)]
520 517 """
521 518 for range_str in ranges_str.split():
522 519 rmatch = range_re.match(range_str)
523 520 if not rmatch:
524 521 continue
525 522 start = int(rmatch.group("start"))
526 523 end = rmatch.group("end")
527 524 end = int(end) if end else start+1 # If no end specified, get (a, a+1)
528 525 if rmatch.group("sep") == "-": # 1-3 == 1:4 --> [1, 2, 3]
529 526 end += 1
530 527 startsess = rmatch.group("startsess") or "0"
531 528 endsess = rmatch.group("endsess") or startsess
532 529 startsess = int(startsess.replace("~","-"))
533 530 endsess = int(endsess.replace("~","-"))
534 531 assert endsess >= startsess
535 532
536 533 if endsess == startsess:
537 534 yield (startsess, start, end)
538 535 continue
539 536 # Multiple sessions in one range:
540 537 yield (startsess, start, None)
541 538 for sess in range(startsess+1, endsess):
542 539 yield (sess, 1, None)
543 540 yield (endsess, 1, end)
544 541
545 542 def _format_lineno(session, line):
546 543 """Helper function to format line numbers properly."""
547 544 if session == 0:
548 545 return str(line)
549 546 return "%s#%s" % (session, line)
550 547
551 548 @skip_doctest
552 549 def magic_history(self, parameter_s = ''):
553 550 """Print input history (_i<n> variables), with most recent last.
554 551
555 552 %history -> print at most 40 inputs (some may be multi-line)\\
556 553 %history n -> print at most n inputs\\
557 554 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
558 555
559 556 By default, input history is printed without line numbers so it can be
560 557 directly pasted into an editor. Use -n to show them.
561 558
562 559 Ranges of history can be indicated using the syntax:
563 560 4 : Line 4, current session
564 561 4-6 : Lines 4-6, current session
565 562 243/1-5: Lines 1-5, session 243
566 563 ~2/7 : Line 7, session 2 before current
567 564 ~8/1-~6/5 : From the first line of 8 sessions ago, to the fifth line
568 565 of 6 sessions ago.
569 566 Multiple ranges can be entered, separated by spaces
570 567
571 568 The same syntax is used by %macro, %save, %edit, %rerun
572 569
573 570 Options:
574 571
575 572 -n: print line numbers for each input.
576 573 This feature is only available if numbered prompts are in use.
577 574
578 575 -o: also print outputs for each input.
579 576
580 577 -p: print classic '>>>' python prompts before each input. This is useful
581 578 for making documentation, and in conjunction with -o, for producing
582 579 doctest-ready output.
583 580
584 581 -r: (default) print the 'raw' history, i.e. the actual commands you typed.
585 582
586 583 -t: print the 'translated' history, as IPython understands it. IPython
587 584 filters your input and converts it all into valid Python source before
588 585 executing it (things like magics or aliases are turned into function
589 586 calls, for example). With this option, you'll see the native history
590 587 instead of the user-entered version: '%cd /' will be seen as
591 588 'get_ipython().magic("%cd /")' instead of '%cd /'.
592 589
593 590 -g: treat the arg as a pattern to grep for in (full) history.
594 591 This includes the saved history (almost all commands ever written).
595 592 Use '%hist -g' to show full saved history (may be very long).
596 593
597 594 -l: get the last n lines from all sessions. Specify n as a single arg, or
598 595 the default is the last 10 lines.
599 596
600 597 -f FILENAME: instead of printing the output to the screen, redirect it to
601 598 the given file. The file is always overwritten, though IPython asks for
602 599 confirmation first if it already exists.
603 600
604 601 Examples
605 602 --------
606 603 ::
607 604
608 605 In [6]: %hist -n 4 6
609 606 4:a = 12
610 607 5:print a**2
611 608
612 609 """
613 610
614 611 if not self.shell.displayhook.do_full_cache:
615 612 print('This feature is only available if numbered prompts are in use.')
616 613 return
617 614 opts,args = self.parse_options(parameter_s,'noprtglf:',mode='string')
618 615
619 616 # For brevity
620 617 history_manager = self.shell.history_manager
621 618
622 619 def _format_lineno(session, line):
623 620 """Helper function to format line numbers properly."""
624 621 if session in (0, history_manager.session_number):
625 622 return str(line)
626 623 return "%s/%s" % (session, line)
627 624
628 625 # Check if output to specific file was requested.
629 626 try:
630 627 outfname = opts['f']
631 628 except KeyError:
632 629 outfile = io.stdout # default
633 630 # We don't want to close stdout at the end!
634 631 close_at_end = False
635 632 else:
636 633 if os.path.exists(outfname):
637 634 if not io.ask_yes_no("File %r exists. Overwrite?" % outfname):
638 635 print('Aborting.')
639 636 return
640 637
641 638 outfile = open(outfname,'w')
642 639 close_at_end = True
643 640
644 641 print_nums = 'n' in opts
645 642 get_output = 'o' in opts
646 643 pyprompts = 'p' in opts
647 644 # Raw history is the default
648 645 raw = not('t' in opts)
649 646
650 647 default_length = 40
651 648 pattern = None
652 649
653 650 if 'g' in opts: # Glob search
654 651 pattern = "*" + args + "*" if args else "*"
655 652 hist = history_manager.search(pattern, raw=raw, output=get_output)
656 653 elif 'l' in opts: # Get 'tail'
657 654 try:
658 655 n = int(args)
659 656 except ValueError, IndexError:
660 657 n = 10
661 658 hist = history_manager.get_tail(n, raw=raw, output=get_output)
662 659 else:
663 660 if args: # Get history by ranges
664 661 hist = history_manager.get_range_by_str(args, raw, get_output)
665 662 else: # Just get history for the current session
666 663 hist = history_manager.get_range(raw=raw, output=get_output)
667 664
668 665 # We could be displaying the entire history, so let's not try to pull it
669 666 # into a list in memory. Anything that needs more space will just misalign.
670 667 width = 4
671 668
672 669 for session, lineno, inline in hist:
673 670 # Print user history with tabs expanded to 4 spaces. The GUI clients
674 671 # use hard tabs for easier usability in auto-indented code, but we want
675 672 # to produce PEP-8 compliant history for safe pasting into an editor.
676 673 if get_output:
677 674 inline, output = inline
678 675 inline = inline.expandtabs(4).rstrip()
679 676
680 677 multiline = "\n" in inline
681 678 line_sep = '\n' if multiline else ' '
682 679 if print_nums:
683 680 print('%s:%s' % (_format_lineno(session, lineno).rjust(width),
684 681 line_sep), file=outfile, end='')
685 682 if pyprompts:
686 683 print(">>> ", end="", file=outfile)
687 684 if multiline:
688 685 inline = "\n... ".join(inline.splitlines()) + "\n..."
689 686 print(inline, file=outfile)
690 687 if get_output and output:
691 688 print(output, file=outfile)
692 689
693 690 if close_at_end:
694 691 outfile.close()
695 692
696 693
697 694 def magic_rep(self, arg):
698 695 r""" Repeat a command, or get command to input line for editing
699 696
700 697 - %rep (no arguments):
701 698
702 699 Place a string version of last computation result (stored in the special '_'
703 700 variable) to the next input prompt. Allows you to create elaborate command
704 701 lines without using copy-paste::
705 702
706 703 In[1]: l = ["hei", "vaan"]
707 704 In[2]: "".join(l)
708 705 Out[2]: heivaan
709 706 In[3]: %rep
710 707 In[4]: heivaan_ <== cursor blinking
711 708
712 709 %rep 45
713 710
714 711 Place history line 45 on the next input prompt. Use %hist to find
715 712 out the number.
716 713
717 714 %rep 1-4
718 715
719 716 Combine the specified lines into one cell, and place it on the next
720 717 input prompt. See %history for the slice syntax.
721 718
722 719 %rep foo+bar
723 720
724 721 If foo+bar can be evaluated in the user namespace, the result is
725 722 placed at the next input prompt. Otherwise, the history is searched
726 723 for lines which contain that substring, and the most recent one is
727 724 placed at the next input prompt.
728 725 """
729 726 if not arg: # Last output
730 727 self.set_next_input(str(self.shell.user_ns["_"]))
731 728 return
732 729 # Get history range
733 730 histlines = self.history_manager.get_range_by_str(arg)
734 731 cmd = "\n".join(x[2] for x in histlines)
735 732 if cmd:
736 733 self.set_next_input(cmd.rstrip())
737 734 return
738 735
739 736 try: # Variable in user namespace
740 737 cmd = str(eval(arg, self.shell.user_ns))
741 738 except Exception: # Search for term in history
742 739 histlines = self.history_manager.search("*"+arg+"*")
743 740 for h in reversed([x[2] for x in histlines]):
744 741 if 'rep' in h:
745 742 continue
746 743 self.set_next_input(h.rstrip())
747 744 return
748 745 else:
749 746 self.set_next_input(cmd.rstrip())
750 747 print("Couldn't evaluate or find in history:", arg)
751 748
752 749 def magic_rerun(self, parameter_s=''):
753 750 """Re-run previous input
754 751
755 752 By default, you can specify ranges of input history to be repeated
756 753 (as with %history). With no arguments, it will repeat the last line.
757 754
758 755 Options:
759 756
760 757 -l <n> : Repeat the last n lines of input, not including the
761 758 current command.
762 759
763 760 -g foo : Repeat the most recent line which contains foo
764 761 """
765 762 opts, args = self.parse_options(parameter_s, 'l:g:', mode='string')
766 763 if "l" in opts: # Last n lines
767 764 n = int(opts['l'])
768 765 hist = self.history_manager.get_tail(n)
769 766 elif "g" in opts: # Search
770 767 p = "*"+opts['g']+"*"
771 768 hist = list(self.history_manager.search(p))
772 769 for l in reversed(hist):
773 770 if "rerun" not in l[2]:
774 771 hist = [l] # The last match which isn't a %rerun
775 772 break
776 773 else:
777 774 hist = [] # No matches except %rerun
778 775 elif args: # Specify history ranges
779 776 hist = self.history_manager.get_range_by_str(args)
780 777 else: # Last line
781 778 hist = self.history_manager.get_tail(1)
782 779 hist = [x[2] for x in hist]
783 780 if not hist:
784 781 print("No lines in history match specification")
785 782 return
786 783 histlines = "\n".join(hist)
787 784 print("=== Executing: ===")
788 785 print(histlines)
789 786 print("=== Output: ===")
790 787 self.run_cell("\n".join(hist), store_history=False)
791 788
792 789
793 790 def init_ipython(ip):
794 791 ip.define_magic("rep", magic_rep)
795 792 ip.define_magic("recall", magic_rep)
796 793 ip.define_magic("rerun", magic_rerun)
797 794 ip.define_magic("hist",magic_history) # Alternative name
798 795 ip.define_magic("history",magic_history)
799 796
800 797 # XXX - ipy_completers are in quarantine, need to be updated to new apis
801 798 #import ipy_completers
802 799 #ipy_completers.quick_completer('%hist' ,'-g -t -r -n')
@@ -1,2542 +1,2553
1 1 # -*- coding: utf-8 -*-
2 2 """Main IPython class."""
3 3
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 7 # Copyright (C) 2008-2011 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 from __future__ import with_statement
18 18 from __future__ import absolute_import
19 19
20 20 import __builtin__
21 21 import __future__
22 22 import abc
23 23 import ast
24 24 import atexit
25 25 import codeop
26 26 import inspect
27 27 import os
28 28 import re
29 29 import sys
30 30 import tempfile
31 31 import types
32 32 from contextlib import nested
33 33
34 34 from IPython.config.configurable import SingletonConfigurable
35 35 from IPython.core import debugger, oinspect
36 36 from IPython.core import history as ipcorehist
37 37 from IPython.core import page
38 38 from IPython.core import prefilter
39 39 from IPython.core import shadowns
40 40 from IPython.core import ultratb
41 41 from IPython.core.alias import AliasManager, AliasError
42 42 from IPython.core.autocall import ExitAutocall
43 43 from IPython.core.builtin_trap import BuiltinTrap
44 44 from IPython.core.compilerop import CachingCompiler
45 45 from IPython.core.display_trap import DisplayTrap
46 46 from IPython.core.displayhook import DisplayHook
47 47 from IPython.core.displaypub import DisplayPublisher
48 48 from IPython.core.error import TryNext, UsageError
49 49 from IPython.core.extensions import ExtensionManager
50 50 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
51 51 from IPython.core.formatters import DisplayFormatter
52 52 from IPython.core.history import HistoryManager
53 53 from IPython.core.inputsplitter import IPythonInputSplitter
54 54 from IPython.core.logger import Logger
55 55 from IPython.core.macro import Macro
56 56 from IPython.core.magic import Magic
57 from IPython.core.newapplication import ProfileDir
57 58 from IPython.core.payload import PayloadManager
58 59 from IPython.core.plugin import PluginManager
59 60 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
60 61 from IPython.external.Itpl import ItplNS
61 62 from IPython.utils import PyColorize
62 63 from IPython.utils import io
63 64 from IPython.utils.doctestreload import doctest_reload
64 65 from IPython.utils.io import ask_yes_no, rprint
65 66 from IPython.utils.ipstruct import Struct
66 67 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
67 68 from IPython.utils.pickleshare import PickleShareDB
68 69 from IPython.utils.process import system, getoutput
69 70 from IPython.utils.strdispatch import StrDispatch
70 71 from IPython.utils.syspathcontext import prepended_to_syspath
71 72 from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList
72 73 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
73 74 List, Unicode, Instance, Type)
74 75 from IPython.utils.warn import warn, error, fatal
75 76 import IPython.core.hooks
76 77
77 78 #-----------------------------------------------------------------------------
78 79 # Globals
79 80 #-----------------------------------------------------------------------------
80 81
81 82 # compiled regexps for autoindent management
82 83 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
83 84
84 85 #-----------------------------------------------------------------------------
85 86 # Utilities
86 87 #-----------------------------------------------------------------------------
87 88
88 89 # store the builtin raw_input globally, and use this always, in case user code
89 90 # overwrites it (like wx.py.PyShell does)
90 91 raw_input_original = raw_input
91 92
92 93 def softspace(file, newvalue):
93 94 """Copied from code.py, to remove the dependency"""
94 95
95 96 oldvalue = 0
96 97 try:
97 98 oldvalue = file.softspace
98 99 except AttributeError:
99 100 pass
100 101 try:
101 102 file.softspace = newvalue
102 103 except (AttributeError, TypeError):
103 104 # "attribute-less object" or "read-only attributes"
104 105 pass
105 106 return oldvalue
106 107
107 108
108 109 def no_op(*a, **kw): pass
109 110
110 111 class SpaceInInput(Exception): pass
111 112
112 113 class Bunch: pass
113 114
114 115
115 116 def get_default_colors():
116 117 if sys.platform=='darwin':
117 118 return "LightBG"
118 119 elif os.name=='nt':
119 120 return 'Linux'
120 121 else:
121 122 return 'Linux'
122 123
123 124
124 125 class SeparateStr(Str):
125 126 """A Str subclass to validate separate_in, separate_out, etc.
126 127
127 128 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
128 129 """
129 130
130 131 def validate(self, obj, value):
131 132 if value == '0': value = ''
132 133 value = value.replace('\\n','\n')
133 134 return super(SeparateStr, self).validate(obj, value)
134 135
135 136
136 137 class ReadlineNoRecord(object):
137 138 """Context manager to execute some code, then reload readline history
138 139 so that interactive input to the code doesn't appear when pressing up."""
139 140 def __init__(self, shell):
140 141 self.shell = shell
141 142 self._nested_level = 0
142 143
143 144 def __enter__(self):
144 145 if self._nested_level == 0:
145 146 try:
146 147 self.orig_length = self.current_length()
147 148 self.readline_tail = self.get_readline_tail()
148 149 except (AttributeError, IndexError): # Can fail with pyreadline
149 150 self.orig_length, self.readline_tail = 999999, []
150 151 self._nested_level += 1
151 152
152 153 def __exit__(self, type, value, traceback):
153 154 self._nested_level -= 1
154 155 if self._nested_level == 0:
155 156 # Try clipping the end if it's got longer
156 157 try:
157 158 e = self.current_length() - self.orig_length
158 159 if e > 0:
159 160 for _ in range(e):
160 161 self.shell.readline.remove_history_item(self.orig_length)
161 162
162 163 # If it still doesn't match, just reload readline history.
163 164 if self.current_length() != self.orig_length \
164 165 or self.get_readline_tail() != self.readline_tail:
165 166 self.shell.refill_readline_hist()
166 167 except (AttributeError, IndexError):
167 168 pass
168 169 # Returning False will cause exceptions to propagate
169 170 return False
170 171
171 172 def current_length(self):
172 173 return self.shell.readline.get_current_history_length()
173 174
174 175 def get_readline_tail(self, n=10):
175 176 """Get the last n items in readline history."""
176 177 end = self.shell.readline.get_current_history_length() + 1
177 178 start = max(end-n, 1)
178 179 ghi = self.shell.readline.get_history_item
179 180 return [ghi(x) for x in range(start, end)]
180 181
181 182
182 183 _autocall_help = """
183 184 Make IPython automatically call any callable object even if
184 185 you didn't type explicit parentheses. For example, 'str 43' becomes 'str(43)'
185 186 automatically. The value can be '0' to disable the feature, '1' for 'smart'
186 187 autocall, where it is not applied if there are no more arguments on the line,
187 188 and '2' for 'full' autocall, where all callable objects are automatically
188 189 called (even if no arguments are present). The default is '1'.
189 190 """
190 191
191 192 #-----------------------------------------------------------------------------
192 193 # Main IPython class
193 194 #-----------------------------------------------------------------------------
194 195
195 196 class InteractiveShell(SingletonConfigurable, Magic):
196 197 """An enhanced, interactive shell for Python."""
197 198
198 199 _instance = None
199 200
200 201 autocall = Enum((0,1,2), default_value=1, config=True, help=
201 202 """
202 203 Make IPython automatically call any callable object even if you didn't
203 204 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
204 205 automatically. The value can be '0' to disable the feature, '1' for
205 206 'smart' autocall, where it is not applied if there are no more
206 207 arguments on the line, and '2' for 'full' autocall, where all callable
207 208 objects are automatically called (even if no arguments are present).
208 209 The default is '1'.
209 210 """
210 211 )
211 212 # TODO: remove all autoindent logic and put into frontends.
212 213 # We can't do this yet because even runlines uses the autoindent.
213 214 autoindent = CBool(True, config=True, help=
214 215 """
215 216 Autoindent IPython code entered interactively.
216 217 """
217 218 )
218 219 automagic = CBool(True, config=True, help=
219 220 """
220 221 Enable magic commands to be called without the leading %.
221 222 """
222 223 )
223 224 cache_size = Int(1000, config=True, help=
224 225 """
225 226 Set the size of the output cache. The default is 1000, you can
226 227 change it permanently in your config file. Setting it to 0 completely
227 228 disables the caching system, and the minimum value accepted is 20 (if
228 229 you provide a value less than 20, it is reset to 0 and a warning is
229 230 issued). This limit is defined because otherwise you'll spend more
230 231 time re-flushing a too small cache than working
231 232 """
232 233 )
233 234 color_info = CBool(True, config=True, help=
234 235 """
235 236 Use colors for displaying information about objects. Because this
236 237 information is passed through a pager (like 'less'), and some pagers
237 238 get confused with color codes, this capability can be turned off.
238 239 """
239 240 )
240 241 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
241 default_value=get_default_colors(), config=True)
242 default_value=get_default_colors(), config=True,
243 help="Set the color scheme (NoColor, Linux, and LightBG)."
244 )
242 245 debug = CBool(False, config=True)
243 246 deep_reload = CBool(False, config=True, help=
244 247 """
245 248 Enable deep (recursive) reloading by default. IPython can use the
246 249 deep_reload module which reloads changes in modules recursively (it
247 250 replaces the reload() function, so you don't need to change anything to
248 251 use it). deep_reload() forces a full reload of modules whose code may
249 252 have changed, which the default reload() function does not. When
250 253 deep_reload is off, IPython will use the normal reload(), but
251 254 deep_reload will still be available as dreload().
252 255 """
253 256 )
254 257 display_formatter = Instance(DisplayFormatter)
255 258 displayhook_class = Type(DisplayHook)
256 259 display_pub_class = Type(DisplayPublisher)
257 260
258 261 exit_now = CBool(False)
259 262 exiter = Instance(ExitAutocall)
260 263 def _exiter_default(self):
261 264 return ExitAutocall(self)
262 265 # Monotonically increasing execution counter
263 266 execution_count = Int(1)
264 267 filename = Unicode("<ipython console>")
265 268 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
266 269
267 270 # Input splitter, to split entire cells of input into either individual
268 271 # interactive statements or whole blocks.
269 272 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
270 273 (), {})
271 274 logstart = CBool(False, config=True, help=
272 275 """
273 276 Start logging to the default log file.
274 277 """
275 278 )
276 279 logfile = Unicode('', config=True, help=
277 280 """
278 281 The name of the logfile to use.
279 282 """
280 283 )
281 284 logappend = Unicode('', config=True, help=
282 285 """
283 286 Start logging to the given file in append mode.
284 287 """
285 288 )
286 289 object_info_string_level = Enum((0,1,2), default_value=0,
287 290 config=True)
288 291 pdb = CBool(False, config=True, help=
289 292 """
290 293 Automatically call the pdb debugger after every exception.
291 294 """
292 295 )
293 296
294 profile = Unicode('', config=True)
295 297 prompt_in1 = Str('In [\\#]: ', config=True)
296 298 prompt_in2 = Str(' .\\D.: ', config=True)
297 299 prompt_out = Str('Out[\\#]: ', config=True)
298 300 prompts_pad_left = CBool(True, config=True)
299 301 quiet = CBool(False, config=True)
300 302
301 303 history_length = Int(10000, config=True)
302 304
303 305 # The readline stuff will eventually be moved to the terminal subclass
304 306 # but for now, we can't do that as readline is welded in everywhere.
305 307 readline_use = CBool(True, config=True)
306 308 readline_merge_completions = CBool(True, config=True)
307 309 readline_omit__names = Enum((0,1,2), default_value=2, config=True)
308 310 readline_remove_delims = Str('-/~', config=True)
309 311 # don't use \M- bindings by default, because they
310 312 # conflict with 8-bit encodings. See gh-58,gh-88
311 313 readline_parse_and_bind = List([
312 314 'tab: complete',
313 315 '"\C-l": clear-screen',
314 316 'set show-all-if-ambiguous on',
315 317 '"\C-o": tab-insert',
316 318 '"\C-r": reverse-search-history',
317 319 '"\C-s": forward-search-history',
318 320 '"\C-p": history-search-backward',
319 321 '"\C-n": history-search-forward',
320 322 '"\e[A": history-search-backward',
321 323 '"\e[B": history-search-forward',
322 324 '"\C-k": kill-line',
323 325 '"\C-u": unix-line-discard',
324 326 ], allow_none=False, config=True)
325 327
326 328 # TODO: this part of prompt management should be moved to the frontends.
327 329 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
328 330 separate_in = SeparateStr('\n', config=True)
329 331 separate_out = SeparateStr('', config=True)
330 332 separate_out2 = SeparateStr('', config=True)
331 333 wildcards_case_sensitive = CBool(True, config=True)
332 334 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
333 335 default_value='Context', config=True)
334 336
335 337 # Subcomponents of InteractiveShell
336 338 alias_manager = Instance('IPython.core.alias.AliasManager')
337 339 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
338 340 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
339 341 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
340 342 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
341 343 plugin_manager = Instance('IPython.core.plugin.PluginManager')
342 344 payload_manager = Instance('IPython.core.payload.PayloadManager')
343 345 history_manager = Instance('IPython.core.history.HistoryManager')
344 346
347 profile_dir = Instance('IPython.core.newapplication.ProfileDir')
348 @property
349 def profile(self):
350 if self.profile_dir is not None:
351 name = os.path.basename(self.profile_dir.location)
352 return name.replace('profile_','')
353
354
345 355 # Private interface
346 356 _post_execute = Instance(dict)
347 357
348 def __init__(self, config=None, ipython_dir=None,
358 def __init__(self, config=None, ipython_dir=None, profile_dir=None,
349 359 user_ns=None, user_global_ns=None,
350 360 custom_exceptions=((), None)):
351 361
352 362 # This is where traits with a config_key argument are updated
353 363 # from the values on config.
354 364 super(InteractiveShell, self).__init__(config=config)
355 365
356 366 # These are relatively independent and stateless
357 367 self.init_ipython_dir(ipython_dir)
368 self.init_profile_dir(profile_dir)
358 369 self.init_instance_attrs()
359 370 self.init_environment()
360 371
361 372 # Create namespaces (user_ns, user_global_ns, etc.)
362 373 self.init_create_namespaces(user_ns, user_global_ns)
363 374 # This has to be done after init_create_namespaces because it uses
364 375 # something in self.user_ns, but before init_sys_modules, which
365 376 # is the first thing to modify sys.
366 377 # TODO: When we override sys.stdout and sys.stderr before this class
367 378 # is created, we are saving the overridden ones here. Not sure if this
368 379 # is what we want to do.
369 380 self.save_sys_module_state()
370 381 self.init_sys_modules()
371 382
372 383 # While we're trying to have each part of the code directly access what
373 384 # it needs without keeping redundant references to objects, we have too
374 385 # much legacy code that expects ip.db to exist.
375 self.db = PickleShareDB(os.path.join(self.ipython_dir, 'db'))
386 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
376 387
377 388 self.init_history()
378 389 self.init_encoding()
379 390 self.init_prefilter()
380 391
381 392 Magic.__init__(self, self)
382 393
383 394 self.init_syntax_highlighting()
384 395 self.init_hooks()
385 396 self.init_pushd_popd_magic()
386 397 # self.init_traceback_handlers use to be here, but we moved it below
387 398 # because it and init_io have to come after init_readline.
388 399 self.init_user_ns()
389 400 self.init_logger()
390 401 self.init_alias()
391 402 self.init_builtins()
392 403
393 404 # pre_config_initialization
394 405
395 406 # The next section should contain everything that was in ipmaker.
396 407 self.init_logstart()
397 408
398 409 # The following was in post_config_initialization
399 410 self.init_inspector()
400 411 # init_readline() must come before init_io(), because init_io uses
401 412 # readline related things.
402 413 self.init_readline()
403 414 # init_completer must come after init_readline, because it needs to
404 415 # know whether readline is present or not system-wide to configure the
405 416 # completers, since the completion machinery can now operate
406 417 # independently of readline (e.g. over the network)
407 418 self.init_completer()
408 419 # TODO: init_io() needs to happen before init_traceback handlers
409 420 # because the traceback handlers hardcode the stdout/stderr streams.
410 421 # This logic in in debugger.Pdb and should eventually be changed.
411 422 self.init_io()
412 423 self.init_traceback_handlers(custom_exceptions)
413 424 self.init_prompts()
414 425 self.init_display_formatter()
415 426 self.init_display_pub()
416 427 self.init_displayhook()
417 428 self.init_reload_doctest()
418 429 self.init_magics()
419 430 self.init_pdb()
420 431 self.init_extension_manager()
421 432 self.init_plugin_manager()
422 433 self.init_payload()
423 434 self.hooks.late_startup_hook()
424 435 atexit.register(self.atexit_operations)
425 436
426 437 def get_ipython(self):
427 438 """Return the currently running IPython instance."""
428 439 return self
429 440
430 441 #-------------------------------------------------------------------------
431 442 # Trait changed handlers
432 443 #-------------------------------------------------------------------------
433 444
434 445 def _ipython_dir_changed(self, name, new):
435 446 if not os.path.isdir(new):
436 447 os.makedirs(new, mode = 0777)
437 448
438 449 def set_autoindent(self,value=None):
439 450 """Set the autoindent flag, checking for readline support.
440 451
441 452 If called with no arguments, it acts as a toggle."""
442 453
443 454 if not self.has_readline:
444 455 if os.name == 'posix':
445 456 warn("The auto-indent feature requires the readline library")
446 457 self.autoindent = 0
447 458 return
448 459 if value is None:
449 460 self.autoindent = not self.autoindent
450 461 else:
451 462 self.autoindent = value
452 463
453 464 #-------------------------------------------------------------------------
454 465 # init_* methods called by __init__
455 466 #-------------------------------------------------------------------------
456 467
457 468 def init_ipython_dir(self, ipython_dir):
458 469 if ipython_dir is not None:
459 470 self.ipython_dir = ipython_dir
460 self.config.Global.ipython_dir = self.ipython_dir
461 471 return
462 472
463 if hasattr(self.config.Global, 'ipython_dir'):
464 self.ipython_dir = self.config.Global.ipython_dir
465 else:
466 self.ipython_dir = get_ipython_dir()
473 self.ipython_dir = get_ipython_dir()
467 474
468 # All children can just read this
469 self.config.Global.ipython_dir = self.ipython_dir
475 def init_profile_dir(self, profile_dir):
476 if profile_dir is not None:
477 self.profile_dir = profile_dir
478 return
479 self.profile_dir =\
480 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
470 481
471 482 def init_instance_attrs(self):
472 483 self.more = False
473 484
474 485 # command compiler
475 486 self.compile = CachingCompiler()
476 487
477 488 # Make an empty namespace, which extension writers can rely on both
478 489 # existing and NEVER being used by ipython itself. This gives them a
479 490 # convenient location for storing additional information and state
480 491 # their extensions may require, without fear of collisions with other
481 492 # ipython names that may develop later.
482 493 self.meta = Struct()
483 494
484 495 # Temporary files used for various purposes. Deleted at exit.
485 496 self.tempfiles = []
486 497
487 498 # Keep track of readline usage (later set by init_readline)
488 499 self.has_readline = False
489 500
490 501 # keep track of where we started running (mainly for crash post-mortem)
491 502 # This is not being used anywhere currently.
492 503 self.starting_dir = os.getcwd()
493 504
494 505 # Indentation management
495 506 self.indent_current_nsp = 0
496 507
497 508 # Dict to track post-execution functions that have been registered
498 509 self._post_execute = {}
499 510
500 511 def init_environment(self):
501 512 """Any changes we need to make to the user's environment."""
502 513 pass
503 514
504 515 def init_encoding(self):
505 516 # Get system encoding at startup time. Certain terminals (like Emacs
506 517 # under Win32 have it set to None, and we need to have a known valid
507 518 # encoding to use in the raw_input() method
508 519 try:
509 520 self.stdin_encoding = sys.stdin.encoding or 'ascii'
510 521 except AttributeError:
511 522 self.stdin_encoding = 'ascii'
512 523
513 524 def init_syntax_highlighting(self):
514 525 # Python source parser/formatter for syntax highlighting
515 526 pyformat = PyColorize.Parser().format
516 527 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
517 528
518 529 def init_pushd_popd_magic(self):
519 530 # for pushd/popd management
520 531 try:
521 532 self.home_dir = get_home_dir()
522 533 except HomeDirError, msg:
523 534 fatal(msg)
524 535
525 536 self.dir_stack = []
526 537
527 538 def init_logger(self):
528 539 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
529 540 logmode='rotate')
530 541
531 542 def init_logstart(self):
532 543 """Initialize logging in case it was requested at the command line.
533 544 """
534 545 if self.logappend:
535 546 self.magic_logstart(self.logappend + ' append')
536 547 elif self.logfile:
537 548 self.magic_logstart(self.logfile)
538 549 elif self.logstart:
539 550 self.magic_logstart()
540 551
541 552 def init_builtins(self):
542 553 self.builtin_trap = BuiltinTrap(shell=self)
543 554
544 555 def init_inspector(self):
545 556 # Object inspector
546 557 self.inspector = oinspect.Inspector(oinspect.InspectColors,
547 558 PyColorize.ANSICodeColors,
548 559 'NoColor',
549 560 self.object_info_string_level)
550 561
551 562 def init_io(self):
552 563 # This will just use sys.stdout and sys.stderr. If you want to
553 564 # override sys.stdout and sys.stderr themselves, you need to do that
554 565 # *before* instantiating this class, because io holds onto
555 566 # references to the underlying streams.
556 567 if sys.platform == 'win32' and self.has_readline:
557 568 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
558 569 else:
559 570 io.stdout = io.IOStream(sys.stdout)
560 571 io.stderr = io.IOStream(sys.stderr)
561 572
562 573 def init_prompts(self):
563 574 # TODO: This is a pass for now because the prompts are managed inside
564 575 # the DisplayHook. Once there is a separate prompt manager, this
565 576 # will initialize that object and all prompt related information.
566 577 pass
567 578
568 579 def init_display_formatter(self):
569 580 self.display_formatter = DisplayFormatter(config=self.config)
570 581
571 582 def init_display_pub(self):
572 583 self.display_pub = self.display_pub_class(config=self.config)
573 584
574 585 def init_displayhook(self):
575 586 # Initialize displayhook, set in/out prompts and printing system
576 587 self.displayhook = self.displayhook_class(
577 588 config=self.config,
578 589 shell=self,
579 590 cache_size=self.cache_size,
580 591 input_sep = self.separate_in,
581 592 output_sep = self.separate_out,
582 593 output_sep2 = self.separate_out2,
583 594 ps1 = self.prompt_in1,
584 595 ps2 = self.prompt_in2,
585 596 ps_out = self.prompt_out,
586 597 pad_left = self.prompts_pad_left
587 598 )
588 599 # This is a context manager that installs/revmoes the displayhook at
589 600 # the appropriate time.
590 601 self.display_trap = DisplayTrap(hook=self.displayhook)
591 602
592 603 def init_reload_doctest(self):
593 604 # Do a proper resetting of doctest, including the necessary displayhook
594 605 # monkeypatching
595 606 try:
596 607 doctest_reload()
597 608 except ImportError:
598 609 warn("doctest module does not exist.")
599 610
600 611 #-------------------------------------------------------------------------
601 612 # Things related to injections into the sys module
602 613 #-------------------------------------------------------------------------
603 614
604 615 def save_sys_module_state(self):
605 616 """Save the state of hooks in the sys module.
606 617
607 618 This has to be called after self.user_ns is created.
608 619 """
609 620 self._orig_sys_module_state = {}
610 621 self._orig_sys_module_state['stdin'] = sys.stdin
611 622 self._orig_sys_module_state['stdout'] = sys.stdout
612 623 self._orig_sys_module_state['stderr'] = sys.stderr
613 624 self._orig_sys_module_state['excepthook'] = sys.excepthook
614 625 try:
615 626 self._orig_sys_modules_main_name = self.user_ns['__name__']
616 627 except KeyError:
617 628 pass
618 629
619 630 def restore_sys_module_state(self):
620 631 """Restore the state of the sys module."""
621 632 try:
622 633 for k, v in self._orig_sys_module_state.iteritems():
623 634 setattr(sys, k, v)
624 635 except AttributeError:
625 636 pass
626 637 # Reset what what done in self.init_sys_modules
627 638 try:
628 639 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
629 640 except (AttributeError, KeyError):
630 641 pass
631 642
632 643 #-------------------------------------------------------------------------
633 644 # Things related to hooks
634 645 #-------------------------------------------------------------------------
635 646
636 647 def init_hooks(self):
637 648 # hooks holds pointers used for user-side customizations
638 649 self.hooks = Struct()
639 650
640 651 self.strdispatchers = {}
641 652
642 653 # Set all default hooks, defined in the IPython.hooks module.
643 654 hooks = IPython.core.hooks
644 655 for hook_name in hooks.__all__:
645 656 # default hooks have priority 100, i.e. low; user hooks should have
646 657 # 0-100 priority
647 658 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
648 659
649 660 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
650 661 """set_hook(name,hook) -> sets an internal IPython hook.
651 662
652 663 IPython exposes some of its internal API as user-modifiable hooks. By
653 664 adding your function to one of these hooks, you can modify IPython's
654 665 behavior to call at runtime your own routines."""
655 666
656 667 # At some point in the future, this should validate the hook before it
657 668 # accepts it. Probably at least check that the hook takes the number
658 669 # of args it's supposed to.
659 670
660 671 f = types.MethodType(hook,self)
661 672
662 673 # check if the hook is for strdispatcher first
663 674 if str_key is not None:
664 675 sdp = self.strdispatchers.get(name, StrDispatch())
665 676 sdp.add_s(str_key, f, priority )
666 677 self.strdispatchers[name] = sdp
667 678 return
668 679 if re_key is not None:
669 680 sdp = self.strdispatchers.get(name, StrDispatch())
670 681 sdp.add_re(re.compile(re_key), f, priority )
671 682 self.strdispatchers[name] = sdp
672 683 return
673 684
674 685 dp = getattr(self.hooks, name, None)
675 686 if name not in IPython.core.hooks.__all__:
676 687 print "Warning! Hook '%s' is not one of %s" % \
677 688 (name, IPython.core.hooks.__all__ )
678 689 if not dp:
679 690 dp = IPython.core.hooks.CommandChainDispatcher()
680 691
681 692 try:
682 693 dp.add(f,priority)
683 694 except AttributeError:
684 695 # it was not commandchain, plain old func - replace
685 696 dp = f
686 697
687 698 setattr(self.hooks,name, dp)
688 699
689 700 def register_post_execute(self, func):
690 701 """Register a function for calling after code execution.
691 702 """
692 703 if not callable(func):
693 704 raise ValueError('argument %s must be callable' % func)
694 705 self._post_execute[func] = True
695 706
696 707 #-------------------------------------------------------------------------
697 708 # Things related to the "main" module
698 709 #-------------------------------------------------------------------------
699 710
700 711 def new_main_mod(self,ns=None):
701 712 """Return a new 'main' module object for user code execution.
702 713 """
703 714 main_mod = self._user_main_module
704 715 init_fakemod_dict(main_mod,ns)
705 716 return main_mod
706 717
707 718 def cache_main_mod(self,ns,fname):
708 719 """Cache a main module's namespace.
709 720
710 721 When scripts are executed via %run, we must keep a reference to the
711 722 namespace of their __main__ module (a FakeModule instance) around so
712 723 that Python doesn't clear it, rendering objects defined therein
713 724 useless.
714 725
715 726 This method keeps said reference in a private dict, keyed by the
716 727 absolute path of the module object (which corresponds to the script
717 728 path). This way, for multiple executions of the same script we only
718 729 keep one copy of the namespace (the last one), thus preventing memory
719 730 leaks from old references while allowing the objects from the last
720 731 execution to be accessible.
721 732
722 733 Note: we can not allow the actual FakeModule instances to be deleted,
723 734 because of how Python tears down modules (it hard-sets all their
724 735 references to None without regard for reference counts). This method
725 736 must therefore make a *copy* of the given namespace, to allow the
726 737 original module's __dict__ to be cleared and reused.
727 738
728 739
729 740 Parameters
730 741 ----------
731 742 ns : a namespace (a dict, typically)
732 743
733 744 fname : str
734 745 Filename associated with the namespace.
735 746
736 747 Examples
737 748 --------
738 749
739 750 In [10]: import IPython
740 751
741 752 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
742 753
743 754 In [12]: IPython.__file__ in _ip._main_ns_cache
744 755 Out[12]: True
745 756 """
746 757 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
747 758
748 759 def clear_main_mod_cache(self):
749 760 """Clear the cache of main modules.
750 761
751 762 Mainly for use by utilities like %reset.
752 763
753 764 Examples
754 765 --------
755 766
756 767 In [15]: import IPython
757 768
758 769 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
759 770
760 771 In [17]: len(_ip._main_ns_cache) > 0
761 772 Out[17]: True
762 773
763 774 In [18]: _ip.clear_main_mod_cache()
764 775
765 776 In [19]: len(_ip._main_ns_cache) == 0
766 777 Out[19]: True
767 778 """
768 779 self._main_ns_cache.clear()
769 780
770 781 #-------------------------------------------------------------------------
771 782 # Things related to debugging
772 783 #-------------------------------------------------------------------------
773 784
774 785 def init_pdb(self):
775 786 # Set calling of pdb on exceptions
776 787 # self.call_pdb is a property
777 788 self.call_pdb = self.pdb
778 789
779 790 def _get_call_pdb(self):
780 791 return self._call_pdb
781 792
782 793 def _set_call_pdb(self,val):
783 794
784 795 if val not in (0,1,False,True):
785 796 raise ValueError,'new call_pdb value must be boolean'
786 797
787 798 # store value in instance
788 799 self._call_pdb = val
789 800
790 801 # notify the actual exception handlers
791 802 self.InteractiveTB.call_pdb = val
792 803
793 804 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
794 805 'Control auto-activation of pdb at exceptions')
795 806
796 807 def debugger(self,force=False):
797 808 """Call the pydb/pdb debugger.
798 809
799 810 Keywords:
800 811
801 812 - force(False): by default, this routine checks the instance call_pdb
802 813 flag and does not actually invoke the debugger if the flag is false.
803 814 The 'force' option forces the debugger to activate even if the flag
804 815 is false.
805 816 """
806 817
807 818 if not (force or self.call_pdb):
808 819 return
809 820
810 821 if not hasattr(sys,'last_traceback'):
811 822 error('No traceback has been produced, nothing to debug.')
812 823 return
813 824
814 825 # use pydb if available
815 826 if debugger.has_pydb:
816 827 from pydb import pm
817 828 else:
818 829 # fallback to our internal debugger
819 830 pm = lambda : self.InteractiveTB.debugger(force=True)
820 831
821 832 with self.readline_no_record:
822 833 pm()
823 834
824 835 #-------------------------------------------------------------------------
825 836 # Things related to IPython's various namespaces
826 837 #-------------------------------------------------------------------------
827 838
828 839 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
829 840 # Create the namespace where the user will operate. user_ns is
830 841 # normally the only one used, and it is passed to the exec calls as
831 842 # the locals argument. But we do carry a user_global_ns namespace
832 843 # given as the exec 'globals' argument, This is useful in embedding
833 844 # situations where the ipython shell opens in a context where the
834 845 # distinction between locals and globals is meaningful. For
835 846 # non-embedded contexts, it is just the same object as the user_ns dict.
836 847
837 848 # FIXME. For some strange reason, __builtins__ is showing up at user
838 849 # level as a dict instead of a module. This is a manual fix, but I
839 850 # should really track down where the problem is coming from. Alex
840 851 # Schmolck reported this problem first.
841 852
842 853 # A useful post by Alex Martelli on this topic:
843 854 # Re: inconsistent value from __builtins__
844 855 # Von: Alex Martelli <aleaxit@yahoo.com>
845 856 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
846 857 # Gruppen: comp.lang.python
847 858
848 859 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
849 860 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
850 861 # > <type 'dict'>
851 862 # > >>> print type(__builtins__)
852 863 # > <type 'module'>
853 864 # > Is this difference in return value intentional?
854 865
855 866 # Well, it's documented that '__builtins__' can be either a dictionary
856 867 # or a module, and it's been that way for a long time. Whether it's
857 868 # intentional (or sensible), I don't know. In any case, the idea is
858 869 # that if you need to access the built-in namespace directly, you
859 870 # should start with "import __builtin__" (note, no 's') which will
860 871 # definitely give you a module. Yeah, it's somewhat confusing:-(.
861 872
862 873 # These routines return properly built dicts as needed by the rest of
863 874 # the code, and can also be used by extension writers to generate
864 875 # properly initialized namespaces.
865 876 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
866 877 user_global_ns)
867 878
868 879 # Assign namespaces
869 880 # This is the namespace where all normal user variables live
870 881 self.user_ns = user_ns
871 882 self.user_global_ns = user_global_ns
872 883
873 884 # An auxiliary namespace that checks what parts of the user_ns were
874 885 # loaded at startup, so we can list later only variables defined in
875 886 # actual interactive use. Since it is always a subset of user_ns, it
876 887 # doesn't need to be separately tracked in the ns_table.
877 888 self.user_ns_hidden = {}
878 889
879 890 # A namespace to keep track of internal data structures to prevent
880 891 # them from cluttering user-visible stuff. Will be updated later
881 892 self.internal_ns = {}
882 893
883 894 # Now that FakeModule produces a real module, we've run into a nasty
884 895 # problem: after script execution (via %run), the module where the user
885 896 # code ran is deleted. Now that this object is a true module (needed
886 897 # so docetst and other tools work correctly), the Python module
887 898 # teardown mechanism runs over it, and sets to None every variable
888 899 # present in that module. Top-level references to objects from the
889 900 # script survive, because the user_ns is updated with them. However,
890 901 # calling functions defined in the script that use other things from
891 902 # the script will fail, because the function's closure had references
892 903 # to the original objects, which are now all None. So we must protect
893 904 # these modules from deletion by keeping a cache.
894 905 #
895 906 # To avoid keeping stale modules around (we only need the one from the
896 907 # last run), we use a dict keyed with the full path to the script, so
897 908 # only the last version of the module is held in the cache. Note,
898 909 # however, that we must cache the module *namespace contents* (their
899 910 # __dict__). Because if we try to cache the actual modules, old ones
900 911 # (uncached) could be destroyed while still holding references (such as
901 912 # those held by GUI objects that tend to be long-lived)>
902 913 #
903 914 # The %reset command will flush this cache. See the cache_main_mod()
904 915 # and clear_main_mod_cache() methods for details on use.
905 916
906 917 # This is the cache used for 'main' namespaces
907 918 self._main_ns_cache = {}
908 919 # And this is the single instance of FakeModule whose __dict__ we keep
909 920 # copying and clearing for reuse on each %run
910 921 self._user_main_module = FakeModule()
911 922
912 923 # A table holding all the namespaces IPython deals with, so that
913 924 # introspection facilities can search easily.
914 925 self.ns_table = {'user':user_ns,
915 926 'user_global':user_global_ns,
916 927 'internal':self.internal_ns,
917 928 'builtin':__builtin__.__dict__
918 929 }
919 930
920 931 # Similarly, track all namespaces where references can be held and that
921 932 # we can safely clear (so it can NOT include builtin). This one can be
922 933 # a simple list. Note that the main execution namespaces, user_ns and
923 934 # user_global_ns, can NOT be listed here, as clearing them blindly
924 935 # causes errors in object __del__ methods. Instead, the reset() method
925 936 # clears them manually and carefully.
926 937 self.ns_refs_table = [ self.user_ns_hidden,
927 938 self.internal_ns, self._main_ns_cache ]
928 939
929 940 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
930 941 """Return a valid local and global user interactive namespaces.
931 942
932 943 This builds a dict with the minimal information needed to operate as a
933 944 valid IPython user namespace, which you can pass to the various
934 945 embedding classes in ipython. The default implementation returns the
935 946 same dict for both the locals and the globals to allow functions to
936 947 refer to variables in the namespace. Customized implementations can
937 948 return different dicts. The locals dictionary can actually be anything
938 949 following the basic mapping protocol of a dict, but the globals dict
939 950 must be a true dict, not even a subclass. It is recommended that any
940 951 custom object for the locals namespace synchronize with the globals
941 952 dict somehow.
942 953
943 954 Raises TypeError if the provided globals namespace is not a true dict.
944 955
945 956 Parameters
946 957 ----------
947 958 user_ns : dict-like, optional
948 959 The current user namespace. The items in this namespace should
949 960 be included in the output. If None, an appropriate blank
950 961 namespace should be created.
951 962 user_global_ns : dict, optional
952 963 The current user global namespace. The items in this namespace
953 964 should be included in the output. If None, an appropriate
954 965 blank namespace should be created.
955 966
956 967 Returns
957 968 -------
958 969 A pair of dictionary-like object to be used as the local namespace
959 970 of the interpreter and a dict to be used as the global namespace.
960 971 """
961 972
962 973
963 974 # We must ensure that __builtin__ (without the final 's') is always
964 975 # available and pointing to the __builtin__ *module*. For more details:
965 976 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
966 977
967 978 if user_ns is None:
968 979 # Set __name__ to __main__ to better match the behavior of the
969 980 # normal interpreter.
970 981 user_ns = {'__name__' :'__main__',
971 982 '__builtin__' : __builtin__,
972 983 '__builtins__' : __builtin__,
973 984 }
974 985 else:
975 986 user_ns.setdefault('__name__','__main__')
976 987 user_ns.setdefault('__builtin__',__builtin__)
977 988 user_ns.setdefault('__builtins__',__builtin__)
978 989
979 990 if user_global_ns is None:
980 991 user_global_ns = user_ns
981 992 if type(user_global_ns) is not dict:
982 993 raise TypeError("user_global_ns must be a true dict; got %r"
983 994 % type(user_global_ns))
984 995
985 996 return user_ns, user_global_ns
986 997
987 998 def init_sys_modules(self):
988 999 # We need to insert into sys.modules something that looks like a
989 1000 # module but which accesses the IPython namespace, for shelve and
990 1001 # pickle to work interactively. Normally they rely on getting
991 1002 # everything out of __main__, but for embedding purposes each IPython
992 1003 # instance has its own private namespace, so we can't go shoving
993 1004 # everything into __main__.
994 1005
995 1006 # note, however, that we should only do this for non-embedded
996 1007 # ipythons, which really mimic the __main__.__dict__ with their own
997 1008 # namespace. Embedded instances, on the other hand, should not do
998 1009 # this because they need to manage the user local/global namespaces
999 1010 # only, but they live within a 'normal' __main__ (meaning, they
1000 1011 # shouldn't overtake the execution environment of the script they're
1001 1012 # embedded in).
1002 1013
1003 1014 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1004 1015
1005 1016 try:
1006 1017 main_name = self.user_ns['__name__']
1007 1018 except KeyError:
1008 1019 raise KeyError('user_ns dictionary MUST have a "__name__" key')
1009 1020 else:
1010 1021 sys.modules[main_name] = FakeModule(self.user_ns)
1011 1022
1012 1023 def init_user_ns(self):
1013 1024 """Initialize all user-visible namespaces to their minimum defaults.
1014 1025
1015 1026 Certain history lists are also initialized here, as they effectively
1016 1027 act as user namespaces.
1017 1028
1018 1029 Notes
1019 1030 -----
1020 1031 All data structures here are only filled in, they are NOT reset by this
1021 1032 method. If they were not empty before, data will simply be added to
1022 1033 therm.
1023 1034 """
1024 1035 # This function works in two parts: first we put a few things in
1025 1036 # user_ns, and we sync that contents into user_ns_hidden so that these
1026 1037 # initial variables aren't shown by %who. After the sync, we add the
1027 1038 # rest of what we *do* want the user to see with %who even on a new
1028 1039 # session (probably nothing, so theye really only see their own stuff)
1029 1040
1030 1041 # The user dict must *always* have a __builtin__ reference to the
1031 1042 # Python standard __builtin__ namespace, which must be imported.
1032 1043 # This is so that certain operations in prompt evaluation can be
1033 1044 # reliably executed with builtins. Note that we can NOT use
1034 1045 # __builtins__ (note the 's'), because that can either be a dict or a
1035 1046 # module, and can even mutate at runtime, depending on the context
1036 1047 # (Python makes no guarantees on it). In contrast, __builtin__ is
1037 1048 # always a module object, though it must be explicitly imported.
1038 1049
1039 1050 # For more details:
1040 1051 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1041 1052 ns = dict(__builtin__ = __builtin__)
1042 1053
1043 1054 # Put 'help' in the user namespace
1044 1055 try:
1045 1056 from site import _Helper
1046 1057 ns['help'] = _Helper()
1047 1058 except ImportError:
1048 1059 warn('help() not available - check site.py')
1049 1060
1050 1061 # make global variables for user access to the histories
1051 1062 ns['_ih'] = self.history_manager.input_hist_parsed
1052 1063 ns['_oh'] = self.history_manager.output_hist
1053 1064 ns['_dh'] = self.history_manager.dir_hist
1054 1065
1055 1066 ns['_sh'] = shadowns
1056 1067
1057 1068 # user aliases to input and output histories. These shouldn't show up
1058 1069 # in %who, as they can have very large reprs.
1059 1070 ns['In'] = self.history_manager.input_hist_parsed
1060 1071 ns['Out'] = self.history_manager.output_hist
1061 1072
1062 1073 # Store myself as the public api!!!
1063 1074 ns['get_ipython'] = self.get_ipython
1064 1075
1065 1076 ns['exit'] = self.exiter
1066 1077 ns['quit'] = self.exiter
1067 1078
1068 1079 # Sync what we've added so far to user_ns_hidden so these aren't seen
1069 1080 # by %who
1070 1081 self.user_ns_hidden.update(ns)
1071 1082
1072 1083 # Anything put into ns now would show up in %who. Think twice before
1073 1084 # putting anything here, as we really want %who to show the user their
1074 1085 # stuff, not our variables.
1075 1086
1076 1087 # Finally, update the real user's namespace
1077 1088 self.user_ns.update(ns)
1078 1089
1079 1090 def reset(self, new_session=True):
1080 1091 """Clear all internal namespaces, and attempt to release references to
1081 1092 user objects.
1082 1093
1083 1094 If new_session is True, a new history session will be opened.
1084 1095 """
1085 1096 # Clear histories
1086 1097 self.history_manager.reset(new_session)
1087 1098 # Reset counter used to index all histories
1088 1099 if new_session:
1089 1100 self.execution_count = 1
1090 1101
1091 1102 # Flush cached output items
1092 1103 if self.displayhook.do_full_cache:
1093 1104 self.displayhook.flush()
1094 1105
1095 1106 # Restore the user namespaces to minimal usability
1096 1107 for ns in self.ns_refs_table:
1097 1108 ns.clear()
1098 1109
1099 1110 # The main execution namespaces must be cleared very carefully,
1100 1111 # skipping the deletion of the builtin-related keys, because doing so
1101 1112 # would cause errors in many object's __del__ methods.
1102 1113 for ns in [self.user_ns, self.user_global_ns]:
1103 1114 drop_keys = set(ns.keys())
1104 1115 drop_keys.discard('__builtin__')
1105 1116 drop_keys.discard('__builtins__')
1106 1117 for k in drop_keys:
1107 1118 del ns[k]
1108 1119
1109 1120 # Restore the user namespaces to minimal usability
1110 1121 self.init_user_ns()
1111 1122
1112 1123 # Restore the default and user aliases
1113 1124 self.alias_manager.clear_aliases()
1114 1125 self.alias_manager.init_aliases()
1115 1126
1116 1127 # Flush the private list of module references kept for script
1117 1128 # execution protection
1118 1129 self.clear_main_mod_cache()
1119 1130
1120 1131 # Clear out the namespace from the last %run
1121 1132 self.new_main_mod()
1122 1133
1123 1134 def del_var(self, varname, by_name=False):
1124 1135 """Delete a variable from the various namespaces, so that, as
1125 1136 far as possible, we're not keeping any hidden references to it.
1126 1137
1127 1138 Parameters
1128 1139 ----------
1129 1140 varname : str
1130 1141 The name of the variable to delete.
1131 1142 by_name : bool
1132 1143 If True, delete variables with the given name in each
1133 1144 namespace. If False (default), find the variable in the user
1134 1145 namespace, and delete references to it.
1135 1146 """
1136 1147 if varname in ('__builtin__', '__builtins__'):
1137 1148 raise ValueError("Refusing to delete %s" % varname)
1138 1149 ns_refs = self.ns_refs_table + [self.user_ns,
1139 1150 self.user_global_ns, self._user_main_module.__dict__] +\
1140 1151 self._main_ns_cache.values()
1141 1152
1142 1153 if by_name: # Delete by name
1143 1154 for ns in ns_refs:
1144 1155 try:
1145 1156 del ns[varname]
1146 1157 except KeyError:
1147 1158 pass
1148 1159 else: # Delete by object
1149 1160 try:
1150 1161 obj = self.user_ns[varname]
1151 1162 except KeyError:
1152 1163 raise NameError("name '%s' is not defined" % varname)
1153 1164 # Also check in output history
1154 1165 ns_refs.append(self.history_manager.output_hist)
1155 1166 for ns in ns_refs:
1156 1167 to_delete = [n for n, o in ns.iteritems() if o is obj]
1157 1168 for name in to_delete:
1158 1169 del ns[name]
1159 1170
1160 1171 # displayhook keeps extra references, but not in a dictionary
1161 1172 for name in ('_', '__', '___'):
1162 1173 if getattr(self.displayhook, name) is obj:
1163 1174 setattr(self.displayhook, name, None)
1164 1175
1165 1176 def reset_selective(self, regex=None):
1166 1177 """Clear selective variables from internal namespaces based on a
1167 1178 specified regular expression.
1168 1179
1169 1180 Parameters
1170 1181 ----------
1171 1182 regex : string or compiled pattern, optional
1172 1183 A regular expression pattern that will be used in searching
1173 1184 variable names in the users namespaces.
1174 1185 """
1175 1186 if regex is not None:
1176 1187 try:
1177 1188 m = re.compile(regex)
1178 1189 except TypeError:
1179 1190 raise TypeError('regex must be a string or compiled pattern')
1180 1191 # Search for keys in each namespace that match the given regex
1181 1192 # If a match is found, delete the key/value pair.
1182 1193 for ns in self.ns_refs_table:
1183 1194 for var in ns:
1184 1195 if m.search(var):
1185 1196 del ns[var]
1186 1197
1187 1198 def push(self, variables, interactive=True):
1188 1199 """Inject a group of variables into the IPython user namespace.
1189 1200
1190 1201 Parameters
1191 1202 ----------
1192 1203 variables : dict, str or list/tuple of str
1193 1204 The variables to inject into the user's namespace. If a dict, a
1194 1205 simple update is done. If a str, the string is assumed to have
1195 1206 variable names separated by spaces. A list/tuple of str can also
1196 1207 be used to give the variable names. If just the variable names are
1197 1208 give (list/tuple/str) then the variable values looked up in the
1198 1209 callers frame.
1199 1210 interactive : bool
1200 1211 If True (default), the variables will be listed with the ``who``
1201 1212 magic.
1202 1213 """
1203 1214 vdict = None
1204 1215
1205 1216 # We need a dict of name/value pairs to do namespace updates.
1206 1217 if isinstance(variables, dict):
1207 1218 vdict = variables
1208 1219 elif isinstance(variables, (basestring, list, tuple)):
1209 1220 if isinstance(variables, basestring):
1210 1221 vlist = variables.split()
1211 1222 else:
1212 1223 vlist = variables
1213 1224 vdict = {}
1214 1225 cf = sys._getframe(1)
1215 1226 for name in vlist:
1216 1227 try:
1217 1228 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1218 1229 except:
1219 1230 print ('Could not get variable %s from %s' %
1220 1231 (name,cf.f_code.co_name))
1221 1232 else:
1222 1233 raise ValueError('variables must be a dict/str/list/tuple')
1223 1234
1224 1235 # Propagate variables to user namespace
1225 1236 self.user_ns.update(vdict)
1226 1237
1227 1238 # And configure interactive visibility
1228 1239 config_ns = self.user_ns_hidden
1229 1240 if interactive:
1230 1241 for name, val in vdict.iteritems():
1231 1242 config_ns.pop(name, None)
1232 1243 else:
1233 1244 for name,val in vdict.iteritems():
1234 1245 config_ns[name] = val
1235 1246
1236 1247 #-------------------------------------------------------------------------
1237 1248 # Things related to object introspection
1238 1249 #-------------------------------------------------------------------------
1239 1250
1240 1251 def _ofind(self, oname, namespaces=None):
1241 1252 """Find an object in the available namespaces.
1242 1253
1243 1254 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1244 1255
1245 1256 Has special code to detect magic functions.
1246 1257 """
1247 1258 #oname = oname.strip()
1248 1259 #print '1- oname: <%r>' % oname # dbg
1249 1260 try:
1250 1261 oname = oname.strip().encode('ascii')
1251 1262 #print '2- oname: <%r>' % oname # dbg
1252 1263 except UnicodeEncodeError:
1253 1264 print 'Python identifiers can only contain ascii characters.'
1254 1265 return dict(found=False)
1255 1266
1256 1267 alias_ns = None
1257 1268 if namespaces is None:
1258 1269 # Namespaces to search in:
1259 1270 # Put them in a list. The order is important so that we
1260 1271 # find things in the same order that Python finds them.
1261 1272 namespaces = [ ('Interactive', self.user_ns),
1262 1273 ('IPython internal', self.internal_ns),
1263 1274 ('Python builtin', __builtin__.__dict__),
1264 1275 ('Alias', self.alias_manager.alias_table),
1265 1276 ]
1266 1277 alias_ns = self.alias_manager.alias_table
1267 1278
1268 1279 # initialize results to 'null'
1269 1280 found = False; obj = None; ospace = None; ds = None;
1270 1281 ismagic = False; isalias = False; parent = None
1271 1282
1272 1283 # We need to special-case 'print', which as of python2.6 registers as a
1273 1284 # function but should only be treated as one if print_function was
1274 1285 # loaded with a future import. In this case, just bail.
1275 1286 if (oname == 'print' and not (self.compile.compiler_flags &
1276 1287 __future__.CO_FUTURE_PRINT_FUNCTION)):
1277 1288 return {'found':found, 'obj':obj, 'namespace':ospace,
1278 1289 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1279 1290
1280 1291 # Look for the given name by splitting it in parts. If the head is
1281 1292 # found, then we look for all the remaining parts as members, and only
1282 1293 # declare success if we can find them all.
1283 1294 oname_parts = oname.split('.')
1284 1295 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1285 1296 for nsname,ns in namespaces:
1286 1297 try:
1287 1298 obj = ns[oname_head]
1288 1299 except KeyError:
1289 1300 continue
1290 1301 else:
1291 1302 #print 'oname_rest:', oname_rest # dbg
1292 1303 for part in oname_rest:
1293 1304 try:
1294 1305 parent = obj
1295 1306 obj = getattr(obj,part)
1296 1307 except:
1297 1308 # Blanket except b/c some badly implemented objects
1298 1309 # allow __getattr__ to raise exceptions other than
1299 1310 # AttributeError, which then crashes IPython.
1300 1311 break
1301 1312 else:
1302 1313 # If we finish the for loop (no break), we got all members
1303 1314 found = True
1304 1315 ospace = nsname
1305 1316 if ns == alias_ns:
1306 1317 isalias = True
1307 1318 break # namespace loop
1308 1319
1309 1320 # Try to see if it's magic
1310 1321 if not found:
1311 1322 if oname.startswith(ESC_MAGIC):
1312 1323 oname = oname[1:]
1313 1324 obj = getattr(self,'magic_'+oname,None)
1314 1325 if obj is not None:
1315 1326 found = True
1316 1327 ospace = 'IPython internal'
1317 1328 ismagic = True
1318 1329
1319 1330 # Last try: special-case some literals like '', [], {}, etc:
1320 1331 if not found and oname_head in ["''",'""','[]','{}','()']:
1321 1332 obj = eval(oname_head)
1322 1333 found = True
1323 1334 ospace = 'Interactive'
1324 1335
1325 1336 return {'found':found, 'obj':obj, 'namespace':ospace,
1326 1337 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1327 1338
1328 1339 def _ofind_property(self, oname, info):
1329 1340 """Second part of object finding, to look for property details."""
1330 1341 if info.found:
1331 1342 # Get the docstring of the class property if it exists.
1332 1343 path = oname.split('.')
1333 1344 root = '.'.join(path[:-1])
1334 1345 if info.parent is not None:
1335 1346 try:
1336 1347 target = getattr(info.parent, '__class__')
1337 1348 # The object belongs to a class instance.
1338 1349 try:
1339 1350 target = getattr(target, path[-1])
1340 1351 # The class defines the object.
1341 1352 if isinstance(target, property):
1342 1353 oname = root + '.__class__.' + path[-1]
1343 1354 info = Struct(self._ofind(oname))
1344 1355 except AttributeError: pass
1345 1356 except AttributeError: pass
1346 1357
1347 1358 # We return either the new info or the unmodified input if the object
1348 1359 # hadn't been found
1349 1360 return info
1350 1361
1351 1362 def _object_find(self, oname, namespaces=None):
1352 1363 """Find an object and return a struct with info about it."""
1353 1364 inf = Struct(self._ofind(oname, namespaces))
1354 1365 return Struct(self._ofind_property(oname, inf))
1355 1366
1356 1367 def _inspect(self, meth, oname, namespaces=None, **kw):
1357 1368 """Generic interface to the inspector system.
1358 1369
1359 1370 This function is meant to be called by pdef, pdoc & friends."""
1360 1371 info = self._object_find(oname)
1361 1372 if info.found:
1362 1373 pmethod = getattr(self.inspector, meth)
1363 1374 formatter = format_screen if info.ismagic else None
1364 1375 if meth == 'pdoc':
1365 1376 pmethod(info.obj, oname, formatter)
1366 1377 elif meth == 'pinfo':
1367 1378 pmethod(info.obj, oname, formatter, info, **kw)
1368 1379 else:
1369 1380 pmethod(info.obj, oname)
1370 1381 else:
1371 1382 print 'Object `%s` not found.' % oname
1372 1383 return 'not found' # so callers can take other action
1373 1384
1374 1385 def object_inspect(self, oname):
1375 1386 with self.builtin_trap:
1376 1387 info = self._object_find(oname)
1377 1388 if info.found:
1378 1389 return self.inspector.info(info.obj, oname, info=info)
1379 1390 else:
1380 1391 return oinspect.object_info(name=oname, found=False)
1381 1392
1382 1393 #-------------------------------------------------------------------------
1383 1394 # Things related to history management
1384 1395 #-------------------------------------------------------------------------
1385 1396
1386 1397 def init_history(self):
1387 1398 """Sets up the command history, and starts regular autosaves."""
1388 1399 self.history_manager = HistoryManager(shell=self, config=self.config)
1389 1400
1390 1401 #-------------------------------------------------------------------------
1391 1402 # Things related to exception handling and tracebacks (not debugging)
1392 1403 #-------------------------------------------------------------------------
1393 1404
1394 1405 def init_traceback_handlers(self, custom_exceptions):
1395 1406 # Syntax error handler.
1396 1407 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1397 1408
1398 1409 # The interactive one is initialized with an offset, meaning we always
1399 1410 # want to remove the topmost item in the traceback, which is our own
1400 1411 # internal code. Valid modes: ['Plain','Context','Verbose']
1401 1412 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1402 1413 color_scheme='NoColor',
1403 1414 tb_offset = 1,
1404 1415 check_cache=self.compile.check_cache)
1405 1416
1406 1417 # The instance will store a pointer to the system-wide exception hook,
1407 1418 # so that runtime code (such as magics) can access it. This is because
1408 1419 # during the read-eval loop, it may get temporarily overwritten.
1409 1420 self.sys_excepthook = sys.excepthook
1410 1421
1411 1422 # and add any custom exception handlers the user may have specified
1412 1423 self.set_custom_exc(*custom_exceptions)
1413 1424
1414 1425 # Set the exception mode
1415 1426 self.InteractiveTB.set_mode(mode=self.xmode)
1416 1427
1417 1428 def set_custom_exc(self, exc_tuple, handler):
1418 1429 """set_custom_exc(exc_tuple,handler)
1419 1430
1420 1431 Set a custom exception handler, which will be called if any of the
1421 1432 exceptions in exc_tuple occur in the mainloop (specifically, in the
1422 1433 run_code() method.
1423 1434
1424 1435 Inputs:
1425 1436
1426 1437 - exc_tuple: a *tuple* of valid exceptions to call the defined
1427 1438 handler for. It is very important that you use a tuple, and NOT A
1428 1439 LIST here, because of the way Python's except statement works. If
1429 1440 you only want to trap a single exception, use a singleton tuple:
1430 1441
1431 1442 exc_tuple == (MyCustomException,)
1432 1443
1433 1444 - handler: this must be defined as a function with the following
1434 1445 basic interface::
1435 1446
1436 1447 def my_handler(self, etype, value, tb, tb_offset=None)
1437 1448 ...
1438 1449 # The return value must be
1439 1450 return structured_traceback
1440 1451
1441 1452 This will be made into an instance method (via types.MethodType)
1442 1453 of IPython itself, and it will be called if any of the exceptions
1443 1454 listed in the exc_tuple are caught. If the handler is None, an
1444 1455 internal basic one is used, which just prints basic info.
1445 1456
1446 1457 WARNING: by putting in your own exception handler into IPython's main
1447 1458 execution loop, you run a very good chance of nasty crashes. This
1448 1459 facility should only be used if you really know what you are doing."""
1449 1460
1450 1461 assert type(exc_tuple)==type(()) , \
1451 1462 "The custom exceptions must be given AS A TUPLE."
1452 1463
1453 1464 def dummy_handler(self,etype,value,tb):
1454 1465 print '*** Simple custom exception handler ***'
1455 1466 print 'Exception type :',etype
1456 1467 print 'Exception value:',value
1457 1468 print 'Traceback :',tb
1458 1469 #print 'Source code :','\n'.join(self.buffer)
1459 1470
1460 1471 if handler is None: handler = dummy_handler
1461 1472
1462 1473 self.CustomTB = types.MethodType(handler,self)
1463 1474 self.custom_exceptions = exc_tuple
1464 1475
1465 1476 def excepthook(self, etype, value, tb):
1466 1477 """One more defense for GUI apps that call sys.excepthook.
1467 1478
1468 1479 GUI frameworks like wxPython trap exceptions and call
1469 1480 sys.excepthook themselves. I guess this is a feature that
1470 1481 enables them to keep running after exceptions that would
1471 1482 otherwise kill their mainloop. This is a bother for IPython
1472 1483 which excepts to catch all of the program exceptions with a try:
1473 1484 except: statement.
1474 1485
1475 1486 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1476 1487 any app directly invokes sys.excepthook, it will look to the user like
1477 1488 IPython crashed. In order to work around this, we can disable the
1478 1489 CrashHandler and replace it with this excepthook instead, which prints a
1479 1490 regular traceback using our InteractiveTB. In this fashion, apps which
1480 1491 call sys.excepthook will generate a regular-looking exception from
1481 1492 IPython, and the CrashHandler will only be triggered by real IPython
1482 1493 crashes.
1483 1494
1484 1495 This hook should be used sparingly, only in places which are not likely
1485 1496 to be true IPython errors.
1486 1497 """
1487 1498 self.showtraceback((etype,value,tb),tb_offset=0)
1488 1499
1489 1500 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1490 1501 exception_only=False):
1491 1502 """Display the exception that just occurred.
1492 1503
1493 1504 If nothing is known about the exception, this is the method which
1494 1505 should be used throughout the code for presenting user tracebacks,
1495 1506 rather than directly invoking the InteractiveTB object.
1496 1507
1497 1508 A specific showsyntaxerror() also exists, but this method can take
1498 1509 care of calling it if needed, so unless you are explicitly catching a
1499 1510 SyntaxError exception, don't try to analyze the stack manually and
1500 1511 simply call this method."""
1501 1512
1502 1513 try:
1503 1514 if exc_tuple is None:
1504 1515 etype, value, tb = sys.exc_info()
1505 1516 else:
1506 1517 etype, value, tb = exc_tuple
1507 1518
1508 1519 if etype is None:
1509 1520 if hasattr(sys, 'last_type'):
1510 1521 etype, value, tb = sys.last_type, sys.last_value, \
1511 1522 sys.last_traceback
1512 1523 else:
1513 1524 self.write_err('No traceback available to show.\n')
1514 1525 return
1515 1526
1516 1527 if etype is SyntaxError:
1517 1528 # Though this won't be called by syntax errors in the input
1518 1529 # line, there may be SyntaxError cases whith imported code.
1519 1530 self.showsyntaxerror(filename)
1520 1531 elif etype is UsageError:
1521 1532 print "UsageError:", value
1522 1533 else:
1523 1534 # WARNING: these variables are somewhat deprecated and not
1524 1535 # necessarily safe to use in a threaded environment, but tools
1525 1536 # like pdb depend on their existence, so let's set them. If we
1526 1537 # find problems in the field, we'll need to revisit their use.
1527 1538 sys.last_type = etype
1528 1539 sys.last_value = value
1529 1540 sys.last_traceback = tb
1530 1541 if etype in self.custom_exceptions:
1531 1542 # FIXME: Old custom traceback objects may just return a
1532 1543 # string, in that case we just put it into a list
1533 1544 stb = self.CustomTB(etype, value, tb, tb_offset)
1534 1545 if isinstance(ctb, basestring):
1535 1546 stb = [stb]
1536 1547 else:
1537 1548 if exception_only:
1538 1549 stb = ['An exception has occurred, use %tb to see '
1539 1550 'the full traceback.\n']
1540 1551 stb.extend(self.InteractiveTB.get_exception_only(etype,
1541 1552 value))
1542 1553 else:
1543 1554 stb = self.InteractiveTB.structured_traceback(etype,
1544 1555 value, tb, tb_offset=tb_offset)
1545 1556
1546 1557 if self.call_pdb:
1547 1558 # drop into debugger
1548 1559 self.debugger(force=True)
1549 1560
1550 1561 # Actually show the traceback
1551 1562 self._showtraceback(etype, value, stb)
1552 1563
1553 1564 except KeyboardInterrupt:
1554 1565 self.write_err("\nKeyboardInterrupt\n")
1555 1566
1556 1567 def _showtraceback(self, etype, evalue, stb):
1557 1568 """Actually show a traceback.
1558 1569
1559 1570 Subclasses may override this method to put the traceback on a different
1560 1571 place, like a side channel.
1561 1572 """
1562 1573 print >> io.stdout, self.InteractiveTB.stb2text(stb)
1563 1574
1564 1575 def showsyntaxerror(self, filename=None):
1565 1576 """Display the syntax error that just occurred.
1566 1577
1567 1578 This doesn't display a stack trace because there isn't one.
1568 1579
1569 1580 If a filename is given, it is stuffed in the exception instead
1570 1581 of what was there before (because Python's parser always uses
1571 1582 "<string>" when reading from a string).
1572 1583 """
1573 1584 etype, value, last_traceback = sys.exc_info()
1574 1585
1575 1586 # See note about these variables in showtraceback() above
1576 1587 sys.last_type = etype
1577 1588 sys.last_value = value
1578 1589 sys.last_traceback = last_traceback
1579 1590
1580 1591 if filename and etype is SyntaxError:
1581 1592 # Work hard to stuff the correct filename in the exception
1582 1593 try:
1583 1594 msg, (dummy_filename, lineno, offset, line) = value
1584 1595 except:
1585 1596 # Not the format we expect; leave it alone
1586 1597 pass
1587 1598 else:
1588 1599 # Stuff in the right filename
1589 1600 try:
1590 1601 # Assume SyntaxError is a class exception
1591 1602 value = SyntaxError(msg, (filename, lineno, offset, line))
1592 1603 except:
1593 1604 # If that failed, assume SyntaxError is a string
1594 1605 value = msg, (filename, lineno, offset, line)
1595 1606 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1596 1607 self._showtraceback(etype, value, stb)
1597 1608
1598 1609 #-------------------------------------------------------------------------
1599 1610 # Things related to readline
1600 1611 #-------------------------------------------------------------------------
1601 1612
1602 1613 def init_readline(self):
1603 1614 """Command history completion/saving/reloading."""
1604 1615
1605 1616 if self.readline_use:
1606 1617 import IPython.utils.rlineimpl as readline
1607 1618
1608 1619 self.rl_next_input = None
1609 1620 self.rl_do_indent = False
1610 1621
1611 1622 if not self.readline_use or not readline.have_readline:
1612 1623 self.has_readline = False
1613 1624 self.readline = None
1614 1625 # Set a number of methods that depend on readline to be no-op
1615 1626 self.set_readline_completer = no_op
1616 1627 self.set_custom_completer = no_op
1617 1628 self.set_completer_frame = no_op
1618 1629 warn('Readline services not available or not loaded.')
1619 1630 else:
1620 1631 self.has_readline = True
1621 1632 self.readline = readline
1622 1633 sys.modules['readline'] = readline
1623 1634
1624 1635 # Platform-specific configuration
1625 1636 if os.name == 'nt':
1626 1637 # FIXME - check with Frederick to see if we can harmonize
1627 1638 # naming conventions with pyreadline to avoid this
1628 1639 # platform-dependent check
1629 1640 self.readline_startup_hook = readline.set_pre_input_hook
1630 1641 else:
1631 1642 self.readline_startup_hook = readline.set_startup_hook
1632 1643
1633 1644 # Load user's initrc file (readline config)
1634 1645 # Or if libedit is used, load editrc.
1635 1646 inputrc_name = os.environ.get('INPUTRC')
1636 1647 if inputrc_name is None:
1637 1648 home_dir = get_home_dir()
1638 1649 if home_dir is not None:
1639 1650 inputrc_name = '.inputrc'
1640 1651 if readline.uses_libedit:
1641 1652 inputrc_name = '.editrc'
1642 1653 inputrc_name = os.path.join(home_dir, inputrc_name)
1643 1654 if os.path.isfile(inputrc_name):
1644 1655 try:
1645 1656 readline.read_init_file(inputrc_name)
1646 1657 except:
1647 1658 warn('Problems reading readline initialization file <%s>'
1648 1659 % inputrc_name)
1649 1660
1650 1661 # Configure readline according to user's prefs
1651 1662 # This is only done if GNU readline is being used. If libedit
1652 1663 # is being used (as on Leopard) the readline config is
1653 1664 # not run as the syntax for libedit is different.
1654 1665 if not readline.uses_libedit:
1655 1666 for rlcommand in self.readline_parse_and_bind:
1656 1667 #print "loading rl:",rlcommand # dbg
1657 1668 readline.parse_and_bind(rlcommand)
1658 1669
1659 1670 # Remove some chars from the delimiters list. If we encounter
1660 1671 # unicode chars, discard them.
1661 1672 delims = readline.get_completer_delims().encode("ascii", "ignore")
1662 1673 delims = delims.translate(None, self.readline_remove_delims)
1663 1674 delims = delims.replace(ESC_MAGIC, '')
1664 1675 readline.set_completer_delims(delims)
1665 1676 # otherwise we end up with a monster history after a while:
1666 1677 readline.set_history_length(self.history_length)
1667 1678
1668 1679 self.refill_readline_hist()
1669 1680 self.readline_no_record = ReadlineNoRecord(self)
1670 1681
1671 1682 # Configure auto-indent for all platforms
1672 1683 self.set_autoindent(self.autoindent)
1673 1684
1674 1685 def refill_readline_hist(self):
1675 1686 # Load the last 1000 lines from history
1676 1687 self.readline.clear_history()
1677 1688 stdin_encoding = sys.stdin.encoding or "utf-8"
1678 1689 for _, _, cell in self.history_manager.get_tail(1000,
1679 1690 include_latest=True):
1680 1691 if cell.strip(): # Ignore blank lines
1681 1692 for line in cell.splitlines():
1682 1693 self.readline.add_history(line.encode(stdin_encoding, 'replace'))
1683 1694
1684 1695 def set_next_input(self, s):
1685 1696 """ Sets the 'default' input string for the next command line.
1686 1697
1687 1698 Requires readline.
1688 1699
1689 1700 Example:
1690 1701
1691 1702 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1692 1703 [D:\ipython]|2> Hello Word_ # cursor is here
1693 1704 """
1694 1705
1695 1706 self.rl_next_input = s
1696 1707
1697 1708 # Maybe move this to the terminal subclass?
1698 1709 def pre_readline(self):
1699 1710 """readline hook to be used at the start of each line.
1700 1711
1701 1712 Currently it handles auto-indent only."""
1702 1713
1703 1714 if self.rl_do_indent:
1704 1715 self.readline.insert_text(self._indent_current_str())
1705 1716 if self.rl_next_input is not None:
1706 1717 self.readline.insert_text(self.rl_next_input)
1707 1718 self.rl_next_input = None
1708 1719
1709 1720 def _indent_current_str(self):
1710 1721 """return the current level of indentation as a string"""
1711 1722 return self.input_splitter.indent_spaces * ' '
1712 1723
1713 1724 #-------------------------------------------------------------------------
1714 1725 # Things related to text completion
1715 1726 #-------------------------------------------------------------------------
1716 1727
1717 1728 def init_completer(self):
1718 1729 """Initialize the completion machinery.
1719 1730
1720 1731 This creates completion machinery that can be used by client code,
1721 1732 either interactively in-process (typically triggered by the readline
1722 1733 library), programatically (such as in test suites) or out-of-prcess
1723 1734 (typically over the network by remote frontends).
1724 1735 """
1725 1736 from IPython.core.completer import IPCompleter
1726 1737 from IPython.core.completerlib import (module_completer,
1727 1738 magic_run_completer, cd_completer)
1728 1739
1729 1740 self.Completer = IPCompleter(self,
1730 1741 self.user_ns,
1731 1742 self.user_global_ns,
1732 1743 self.readline_omit__names,
1733 1744 self.alias_manager.alias_table,
1734 1745 self.has_readline)
1735 1746
1736 1747 # Add custom completers to the basic ones built into IPCompleter
1737 1748 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1738 1749 self.strdispatchers['complete_command'] = sdisp
1739 1750 self.Completer.custom_completers = sdisp
1740 1751
1741 1752 self.set_hook('complete_command', module_completer, str_key = 'import')
1742 1753 self.set_hook('complete_command', module_completer, str_key = 'from')
1743 1754 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1744 1755 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1745 1756
1746 1757 # Only configure readline if we truly are using readline. IPython can
1747 1758 # do tab-completion over the network, in GUIs, etc, where readline
1748 1759 # itself may be absent
1749 1760 if self.has_readline:
1750 1761 self.set_readline_completer()
1751 1762
1752 1763 def complete(self, text, line=None, cursor_pos=None):
1753 1764 """Return the completed text and a list of completions.
1754 1765
1755 1766 Parameters
1756 1767 ----------
1757 1768
1758 1769 text : string
1759 1770 A string of text to be completed on. It can be given as empty and
1760 1771 instead a line/position pair are given. In this case, the
1761 1772 completer itself will split the line like readline does.
1762 1773
1763 1774 line : string, optional
1764 1775 The complete line that text is part of.
1765 1776
1766 1777 cursor_pos : int, optional
1767 1778 The position of the cursor on the input line.
1768 1779
1769 1780 Returns
1770 1781 -------
1771 1782 text : string
1772 1783 The actual text that was completed.
1773 1784
1774 1785 matches : list
1775 1786 A sorted list with all possible completions.
1776 1787
1777 1788 The optional arguments allow the completion to take more context into
1778 1789 account, and are part of the low-level completion API.
1779 1790
1780 1791 This is a wrapper around the completion mechanism, similar to what
1781 1792 readline does at the command line when the TAB key is hit. By
1782 1793 exposing it as a method, it can be used by other non-readline
1783 1794 environments (such as GUIs) for text completion.
1784 1795
1785 1796 Simple usage example:
1786 1797
1787 1798 In [1]: x = 'hello'
1788 1799
1789 1800 In [2]: _ip.complete('x.l')
1790 1801 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1791 1802 """
1792 1803
1793 1804 # Inject names into __builtin__ so we can complete on the added names.
1794 1805 with self.builtin_trap:
1795 1806 return self.Completer.complete(text, line, cursor_pos)
1796 1807
1797 1808 def set_custom_completer(self, completer, pos=0):
1798 1809 """Adds a new custom completer function.
1799 1810
1800 1811 The position argument (defaults to 0) is the index in the completers
1801 1812 list where you want the completer to be inserted."""
1802 1813
1803 1814 newcomp = types.MethodType(completer,self.Completer)
1804 1815 self.Completer.matchers.insert(pos,newcomp)
1805 1816
1806 1817 def set_readline_completer(self):
1807 1818 """Reset readline's completer to be our own."""
1808 1819 self.readline.set_completer(self.Completer.rlcomplete)
1809 1820
1810 1821 def set_completer_frame(self, frame=None):
1811 1822 """Set the frame of the completer."""
1812 1823 if frame:
1813 1824 self.Completer.namespace = frame.f_locals
1814 1825 self.Completer.global_namespace = frame.f_globals
1815 1826 else:
1816 1827 self.Completer.namespace = self.user_ns
1817 1828 self.Completer.global_namespace = self.user_global_ns
1818 1829
1819 1830 #-------------------------------------------------------------------------
1820 1831 # Things related to magics
1821 1832 #-------------------------------------------------------------------------
1822 1833
1823 1834 def init_magics(self):
1824 1835 # FIXME: Move the color initialization to the DisplayHook, which
1825 1836 # should be split into a prompt manager and displayhook. We probably
1826 1837 # even need a centralize colors management object.
1827 1838 self.magic_colors(self.colors)
1828 1839 # History was moved to a separate module
1829 1840 from . import history
1830 1841 history.init_ipython(self)
1831 1842
1832 1843 def magic(self,arg_s):
1833 1844 """Call a magic function by name.
1834 1845
1835 1846 Input: a string containing the name of the magic function to call and
1836 1847 any additional arguments to be passed to the magic.
1837 1848
1838 1849 magic('name -opt foo bar') is equivalent to typing at the ipython
1839 1850 prompt:
1840 1851
1841 1852 In[1]: %name -opt foo bar
1842 1853
1843 1854 To call a magic without arguments, simply use magic('name').
1844 1855
1845 1856 This provides a proper Python function to call IPython's magics in any
1846 1857 valid Python code you can type at the interpreter, including loops and
1847 1858 compound statements.
1848 1859 """
1849 1860 args = arg_s.split(' ',1)
1850 1861 magic_name = args[0]
1851 1862 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1852 1863
1853 1864 try:
1854 1865 magic_args = args[1]
1855 1866 except IndexError:
1856 1867 magic_args = ''
1857 1868 fn = getattr(self,'magic_'+magic_name,None)
1858 1869 if fn is None:
1859 1870 error("Magic function `%s` not found." % magic_name)
1860 1871 else:
1861 1872 magic_args = self.var_expand(magic_args,1)
1862 1873 # Grab local namespace if we need it:
1863 1874 if getattr(fn, "needs_local_scope", False):
1864 1875 self._magic_locals = sys._getframe(1).f_locals
1865 1876 with self.builtin_trap:
1866 1877 result = fn(magic_args)
1867 1878 # Ensure we're not keeping object references around:
1868 1879 self._magic_locals = {}
1869 1880 return result
1870 1881
1871 1882 def define_magic(self, magicname, func):
1872 1883 """Expose own function as magic function for ipython
1873 1884
1874 1885 def foo_impl(self,parameter_s=''):
1875 1886 'My very own magic!. (Use docstrings, IPython reads them).'
1876 1887 print 'Magic function. Passed parameter is between < >:'
1877 1888 print '<%s>' % parameter_s
1878 1889 print 'The self object is:',self
1879 1890
1880 1891 self.define_magic('foo',foo_impl)
1881 1892 """
1882 1893
1883 1894 import new
1884 1895 im = types.MethodType(func,self)
1885 1896 old = getattr(self, "magic_" + magicname, None)
1886 1897 setattr(self, "magic_" + magicname, im)
1887 1898 return old
1888 1899
1889 1900 #-------------------------------------------------------------------------
1890 1901 # Things related to macros
1891 1902 #-------------------------------------------------------------------------
1892 1903
1893 1904 def define_macro(self, name, themacro):
1894 1905 """Define a new macro
1895 1906
1896 1907 Parameters
1897 1908 ----------
1898 1909 name : str
1899 1910 The name of the macro.
1900 1911 themacro : str or Macro
1901 1912 The action to do upon invoking the macro. If a string, a new
1902 1913 Macro object is created by passing the string to it.
1903 1914 """
1904 1915
1905 1916 from IPython.core import macro
1906 1917
1907 1918 if isinstance(themacro, basestring):
1908 1919 themacro = macro.Macro(themacro)
1909 1920 if not isinstance(themacro, macro.Macro):
1910 1921 raise ValueError('A macro must be a string or a Macro instance.')
1911 1922 self.user_ns[name] = themacro
1912 1923
1913 1924 #-------------------------------------------------------------------------
1914 1925 # Things related to the running of system commands
1915 1926 #-------------------------------------------------------------------------
1916 1927
1917 1928 def system_piped(self, cmd):
1918 1929 """Call the given cmd in a subprocess, piping stdout/err
1919 1930
1920 1931 Parameters
1921 1932 ----------
1922 1933 cmd : str
1923 1934 Command to execute (can not end in '&', as background processes are
1924 1935 not supported. Should not be a command that expects input
1925 1936 other than simple text.
1926 1937 """
1927 1938 if cmd.rstrip().endswith('&'):
1928 1939 # this is *far* from a rigorous test
1929 1940 # We do not support backgrounding processes because we either use
1930 1941 # pexpect or pipes to read from. Users can always just call
1931 1942 # os.system() or use ip.system=ip.system_raw
1932 1943 # if they really want a background process.
1933 1944 raise OSError("Background processes not supported.")
1934 1945
1935 1946 # we explicitly do NOT return the subprocess status code, because
1936 1947 # a non-None value would trigger :func:`sys.displayhook` calls.
1937 1948 # Instead, we store the exit_code in user_ns.
1938 1949 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=2))
1939 1950
1940 1951 def system_raw(self, cmd):
1941 1952 """Call the given cmd in a subprocess using os.system
1942 1953
1943 1954 Parameters
1944 1955 ----------
1945 1956 cmd : str
1946 1957 Command to execute.
1947 1958 """
1948 1959 # We explicitly do NOT return the subprocess status code, because
1949 1960 # a non-None value would trigger :func:`sys.displayhook` calls.
1950 1961 # Instead, we store the exit_code in user_ns.
1951 1962 self.user_ns['_exit_code'] = os.system(self.var_expand(cmd, depth=2))
1952 1963
1953 1964 # use piped system by default, because it is better behaved
1954 1965 system = system_piped
1955 1966
1956 1967 def getoutput(self, cmd, split=True):
1957 1968 """Get output (possibly including stderr) from a subprocess.
1958 1969
1959 1970 Parameters
1960 1971 ----------
1961 1972 cmd : str
1962 1973 Command to execute (can not end in '&', as background processes are
1963 1974 not supported.
1964 1975 split : bool, optional
1965 1976
1966 1977 If True, split the output into an IPython SList. Otherwise, an
1967 1978 IPython LSString is returned. These are objects similar to normal
1968 1979 lists and strings, with a few convenience attributes for easier
1969 1980 manipulation of line-based output. You can use '?' on them for
1970 1981 details.
1971 1982 """
1972 1983 if cmd.rstrip().endswith('&'):
1973 1984 # this is *far* from a rigorous test
1974 1985 raise OSError("Background processes not supported.")
1975 1986 out = getoutput(self.var_expand(cmd, depth=2))
1976 1987 if split:
1977 1988 out = SList(out.splitlines())
1978 1989 else:
1979 1990 out = LSString(out)
1980 1991 return out
1981 1992
1982 1993 #-------------------------------------------------------------------------
1983 1994 # Things related to aliases
1984 1995 #-------------------------------------------------------------------------
1985 1996
1986 1997 def init_alias(self):
1987 1998 self.alias_manager = AliasManager(shell=self, config=self.config)
1988 1999 self.ns_table['alias'] = self.alias_manager.alias_table,
1989 2000
1990 2001 #-------------------------------------------------------------------------
1991 2002 # Things related to extensions and plugins
1992 2003 #-------------------------------------------------------------------------
1993 2004
1994 2005 def init_extension_manager(self):
1995 2006 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1996 2007
1997 2008 def init_plugin_manager(self):
1998 2009 self.plugin_manager = PluginManager(config=self.config)
1999 2010
2000 2011 #-------------------------------------------------------------------------
2001 2012 # Things related to payloads
2002 2013 #-------------------------------------------------------------------------
2003 2014
2004 2015 def init_payload(self):
2005 2016 self.payload_manager = PayloadManager(config=self.config)
2006 2017
2007 2018 #-------------------------------------------------------------------------
2008 2019 # Things related to the prefilter
2009 2020 #-------------------------------------------------------------------------
2010 2021
2011 2022 def init_prefilter(self):
2012 2023 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
2013 2024 # Ultimately this will be refactored in the new interpreter code, but
2014 2025 # for now, we should expose the main prefilter method (there's legacy
2015 2026 # code out there that may rely on this).
2016 2027 self.prefilter = self.prefilter_manager.prefilter_lines
2017 2028
2018 2029 def auto_rewrite_input(self, cmd):
2019 2030 """Print to the screen the rewritten form of the user's command.
2020 2031
2021 2032 This shows visual feedback by rewriting input lines that cause
2022 2033 automatic calling to kick in, like::
2023 2034
2024 2035 /f x
2025 2036
2026 2037 into::
2027 2038
2028 2039 ------> f(x)
2029 2040
2030 2041 after the user's input prompt. This helps the user understand that the
2031 2042 input line was transformed automatically by IPython.
2032 2043 """
2033 2044 rw = self.displayhook.prompt1.auto_rewrite() + cmd
2034 2045
2035 2046 try:
2036 2047 # plain ascii works better w/ pyreadline, on some machines, so
2037 2048 # we use it and only print uncolored rewrite if we have unicode
2038 2049 rw = str(rw)
2039 2050 print >> io.stdout, rw
2040 2051 except UnicodeEncodeError:
2041 2052 print "------> " + cmd
2042 2053
2043 2054 #-------------------------------------------------------------------------
2044 2055 # Things related to extracting values/expressions from kernel and user_ns
2045 2056 #-------------------------------------------------------------------------
2046 2057
2047 2058 def _simple_error(self):
2048 2059 etype, value = sys.exc_info()[:2]
2049 2060 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
2050 2061
2051 2062 def user_variables(self, names):
2052 2063 """Get a list of variable names from the user's namespace.
2053 2064
2054 2065 Parameters
2055 2066 ----------
2056 2067 names : list of strings
2057 2068 A list of names of variables to be read from the user namespace.
2058 2069
2059 2070 Returns
2060 2071 -------
2061 2072 A dict, keyed by the input names and with the repr() of each value.
2062 2073 """
2063 2074 out = {}
2064 2075 user_ns = self.user_ns
2065 2076 for varname in names:
2066 2077 try:
2067 2078 value = repr(user_ns[varname])
2068 2079 except:
2069 2080 value = self._simple_error()
2070 2081 out[varname] = value
2071 2082 return out
2072 2083
2073 2084 def user_expressions(self, expressions):
2074 2085 """Evaluate a dict of expressions in the user's namespace.
2075 2086
2076 2087 Parameters
2077 2088 ----------
2078 2089 expressions : dict
2079 2090 A dict with string keys and string values. The expression values
2080 2091 should be valid Python expressions, each of which will be evaluated
2081 2092 in the user namespace.
2082 2093
2083 2094 Returns
2084 2095 -------
2085 2096 A dict, keyed like the input expressions dict, with the repr() of each
2086 2097 value.
2087 2098 """
2088 2099 out = {}
2089 2100 user_ns = self.user_ns
2090 2101 global_ns = self.user_global_ns
2091 2102 for key, expr in expressions.iteritems():
2092 2103 try:
2093 2104 value = repr(eval(expr, global_ns, user_ns))
2094 2105 except:
2095 2106 value = self._simple_error()
2096 2107 out[key] = value
2097 2108 return out
2098 2109
2099 2110 #-------------------------------------------------------------------------
2100 2111 # Things related to the running of code
2101 2112 #-------------------------------------------------------------------------
2102 2113
2103 2114 def ex(self, cmd):
2104 2115 """Execute a normal python statement in user namespace."""
2105 2116 with self.builtin_trap:
2106 2117 exec cmd in self.user_global_ns, self.user_ns
2107 2118
2108 2119 def ev(self, expr):
2109 2120 """Evaluate python expression expr in user namespace.
2110 2121
2111 2122 Returns the result of evaluation
2112 2123 """
2113 2124 with self.builtin_trap:
2114 2125 return eval(expr, self.user_global_ns, self.user_ns)
2115 2126
2116 2127 def safe_execfile(self, fname, *where, **kw):
2117 2128 """A safe version of the builtin execfile().
2118 2129
2119 2130 This version will never throw an exception, but instead print
2120 2131 helpful error messages to the screen. This only works on pure
2121 2132 Python files with the .py extension.
2122 2133
2123 2134 Parameters
2124 2135 ----------
2125 2136 fname : string
2126 2137 The name of the file to be executed.
2127 2138 where : tuple
2128 2139 One or two namespaces, passed to execfile() as (globals,locals).
2129 2140 If only one is given, it is passed as both.
2130 2141 exit_ignore : bool (False)
2131 2142 If True, then silence SystemExit for non-zero status (it is always
2132 2143 silenced for zero status, as it is so common).
2133 2144 """
2134 2145 kw.setdefault('exit_ignore', False)
2135 2146
2136 2147 fname = os.path.abspath(os.path.expanduser(fname))
2137 2148 # Make sure we have a .py file
2138 2149 if not fname.endswith('.py'):
2139 2150 warn('File must end with .py to be run using execfile: <%s>' % fname)
2140 2151
2141 2152 # Make sure we can open the file
2142 2153 try:
2143 2154 with open(fname) as thefile:
2144 2155 pass
2145 2156 except:
2146 2157 warn('Could not open file <%s> for safe execution.' % fname)
2147 2158 return
2148 2159
2149 2160 # Find things also in current directory. This is needed to mimic the
2150 2161 # behavior of running a script from the system command line, where
2151 2162 # Python inserts the script's directory into sys.path
2152 2163 dname = os.path.dirname(fname)
2153 2164
2154 2165 if isinstance(fname, unicode):
2155 2166 # execfile uses default encoding instead of filesystem encoding
2156 2167 # so unicode filenames will fail
2157 2168 fname = fname.encode(sys.getfilesystemencoding() or sys.getdefaultencoding())
2158 2169
2159 2170 with prepended_to_syspath(dname):
2160 2171 try:
2161 2172 execfile(fname,*where)
2162 2173 except SystemExit, status:
2163 2174 # If the call was made with 0 or None exit status (sys.exit(0)
2164 2175 # or sys.exit() ), don't bother showing a traceback, as both of
2165 2176 # these are considered normal by the OS:
2166 2177 # > python -c'import sys;sys.exit(0)'; echo $?
2167 2178 # 0
2168 2179 # > python -c'import sys;sys.exit()'; echo $?
2169 2180 # 0
2170 2181 # For other exit status, we show the exception unless
2171 2182 # explicitly silenced, but only in short form.
2172 2183 if status.code not in (0, None) and not kw['exit_ignore']:
2173 2184 self.showtraceback(exception_only=True)
2174 2185 except:
2175 2186 self.showtraceback()
2176 2187
2177 2188 def safe_execfile_ipy(self, fname):
2178 2189 """Like safe_execfile, but for .ipy files with IPython syntax.
2179 2190
2180 2191 Parameters
2181 2192 ----------
2182 2193 fname : str
2183 2194 The name of the file to execute. The filename must have a
2184 2195 .ipy extension.
2185 2196 """
2186 2197 fname = os.path.abspath(os.path.expanduser(fname))
2187 2198
2188 2199 # Make sure we have a .py file
2189 2200 if not fname.endswith('.ipy'):
2190 2201 warn('File must end with .py to be run using execfile: <%s>' % fname)
2191 2202
2192 2203 # Make sure we can open the file
2193 2204 try:
2194 2205 with open(fname) as thefile:
2195 2206 pass
2196 2207 except:
2197 2208 warn('Could not open file <%s> for safe execution.' % fname)
2198 2209 return
2199 2210
2200 2211 # Find things also in current directory. This is needed to mimic the
2201 2212 # behavior of running a script from the system command line, where
2202 2213 # Python inserts the script's directory into sys.path
2203 2214 dname = os.path.dirname(fname)
2204 2215
2205 2216 with prepended_to_syspath(dname):
2206 2217 try:
2207 2218 with open(fname) as thefile:
2208 2219 # self.run_cell currently captures all exceptions
2209 2220 # raised in user code. It would be nice if there were
2210 2221 # versions of runlines, execfile that did raise, so
2211 2222 # we could catch the errors.
2212 2223 self.run_cell(thefile.read(), store_history=False)
2213 2224 except:
2214 2225 self.showtraceback()
2215 2226 warn('Unknown failure executing file: <%s>' % fname)
2216 2227
2217 2228 def run_cell(self, raw_cell, store_history=True):
2218 2229 """Run a complete IPython cell.
2219 2230
2220 2231 Parameters
2221 2232 ----------
2222 2233 raw_cell : str
2223 2234 The code (including IPython code such as %magic functions) to run.
2224 2235 store_history : bool
2225 2236 If True, the raw and translated cell will be stored in IPython's
2226 2237 history. For user code calling back into IPython's machinery, this
2227 2238 should be set to False.
2228 2239 """
2229 2240 if (not raw_cell) or raw_cell.isspace():
2230 2241 return
2231 2242
2232 2243 for line in raw_cell.splitlines():
2233 2244 self.input_splitter.push(line)
2234 2245 cell = self.input_splitter.source_reset()
2235 2246
2236 2247 with self.builtin_trap:
2237 2248 prefilter_failed = False
2238 2249 if len(cell.splitlines()) == 1:
2239 2250 try:
2240 2251 # use prefilter_lines to handle trailing newlines
2241 2252 # restore trailing newline for ast.parse
2242 2253 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2243 2254 except AliasError as e:
2244 2255 error(e)
2245 2256 prefilter_failed=True
2246 2257 except Exception:
2247 2258 # don't allow prefilter errors to crash IPython
2248 2259 self.showtraceback()
2249 2260 prefilter_failed = True
2250 2261
2251 2262 # Store raw and processed history
2252 2263 if store_history:
2253 2264 self.history_manager.store_inputs(self.execution_count,
2254 2265 cell, raw_cell)
2255 2266
2256 2267 self.logger.log(cell, raw_cell)
2257 2268
2258 2269 if not prefilter_failed:
2259 2270 # don't run if prefilter failed
2260 2271 cell_name = self.compile.cache(cell, self.execution_count)
2261 2272
2262 2273 with self.display_trap:
2263 2274 try:
2264 2275 code_ast = ast.parse(cell, filename=cell_name)
2265 2276 except (OverflowError, SyntaxError, ValueError, TypeError,
2266 2277 MemoryError):
2267 2278 self.showsyntaxerror()
2268 2279 self.execution_count += 1
2269 2280 return None
2270 2281
2271 2282 self.run_ast_nodes(code_ast.body, cell_name,
2272 2283 interactivity="last_expr")
2273 2284
2274 2285 # Execute any registered post-execution functions.
2275 2286 for func, status in self._post_execute.iteritems():
2276 2287 if not status:
2277 2288 continue
2278 2289 try:
2279 2290 func()
2280 2291 except:
2281 2292 self.showtraceback()
2282 2293 # Deactivate failing function
2283 2294 self._post_execute[func] = False
2284 2295
2285 2296 if store_history:
2286 2297 # Write output to the database. Does nothing unless
2287 2298 # history output logging is enabled.
2288 2299 self.history_manager.store_output(self.execution_count)
2289 2300 # Each cell is a *single* input, regardless of how many lines it has
2290 2301 self.execution_count += 1
2291 2302
2292 2303 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'):
2293 2304 """Run a sequence of AST nodes. The execution mode depends on the
2294 2305 interactivity parameter.
2295 2306
2296 2307 Parameters
2297 2308 ----------
2298 2309 nodelist : list
2299 2310 A sequence of AST nodes to run.
2300 2311 cell_name : str
2301 2312 Will be passed to the compiler as the filename of the cell. Typically
2302 2313 the value returned by ip.compile.cache(cell).
2303 2314 interactivity : str
2304 2315 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2305 2316 run interactively (displaying output from expressions). 'last_expr'
2306 2317 will run the last node interactively only if it is an expression (i.e.
2307 2318 expressions in loops or other blocks are not displayed. Other values
2308 2319 for this parameter will raise a ValueError.
2309 2320 """
2310 2321 if not nodelist:
2311 2322 return
2312 2323
2313 2324 if interactivity == 'last_expr':
2314 2325 if isinstance(nodelist[-1], ast.Expr):
2315 2326 interactivity = "last"
2316 2327 else:
2317 2328 interactivity = "none"
2318 2329
2319 2330 if interactivity == 'none':
2320 2331 to_run_exec, to_run_interactive = nodelist, []
2321 2332 elif interactivity == 'last':
2322 2333 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2323 2334 elif interactivity == 'all':
2324 2335 to_run_exec, to_run_interactive = [], nodelist
2325 2336 else:
2326 2337 raise ValueError("Interactivity was %r" % interactivity)
2327 2338
2328 2339 exec_count = self.execution_count
2329 2340
2330 2341 for i, node in enumerate(to_run_exec):
2331 2342 mod = ast.Module([node])
2332 2343 code = self.compile(mod, cell_name, "exec")
2333 2344 if self.run_code(code):
2334 2345 return True
2335 2346
2336 2347 for i, node in enumerate(to_run_interactive):
2337 2348 mod = ast.Interactive([node])
2338 2349 code = self.compile(mod, cell_name, "single")
2339 2350 if self.run_code(code):
2340 2351 return True
2341 2352
2342 2353 return False
2343 2354
2344 2355 def run_code(self, code_obj):
2345 2356 """Execute a code object.
2346 2357
2347 2358 When an exception occurs, self.showtraceback() is called to display a
2348 2359 traceback.
2349 2360
2350 2361 Parameters
2351 2362 ----------
2352 2363 code_obj : code object
2353 2364 A compiled code object, to be executed
2354 2365 post_execute : bool [default: True]
2355 2366 whether to call post_execute hooks after this particular execution.
2356 2367
2357 2368 Returns
2358 2369 -------
2359 2370 False : successful execution.
2360 2371 True : an error occurred.
2361 2372 """
2362 2373
2363 2374 # Set our own excepthook in case the user code tries to call it
2364 2375 # directly, so that the IPython crash handler doesn't get triggered
2365 2376 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2366 2377
2367 2378 # we save the original sys.excepthook in the instance, in case config
2368 2379 # code (such as magics) needs access to it.
2369 2380 self.sys_excepthook = old_excepthook
2370 2381 outflag = 1 # happens in more places, so it's easier as default
2371 2382 try:
2372 2383 try:
2373 2384 self.hooks.pre_run_code_hook()
2374 2385 #rprint('Running code', repr(code_obj)) # dbg
2375 2386 exec code_obj in self.user_global_ns, self.user_ns
2376 2387 finally:
2377 2388 # Reset our crash handler in place
2378 2389 sys.excepthook = old_excepthook
2379 2390 except SystemExit:
2380 2391 self.showtraceback(exception_only=True)
2381 2392 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2382 2393 except self.custom_exceptions:
2383 2394 etype,value,tb = sys.exc_info()
2384 2395 self.CustomTB(etype,value,tb)
2385 2396 except:
2386 2397 self.showtraceback()
2387 2398 else:
2388 2399 outflag = 0
2389 2400 if softspace(sys.stdout, 0):
2390 2401 print
2391 2402
2392 2403 return outflag
2393 2404
2394 2405 # For backwards compatibility
2395 2406 runcode = run_code
2396 2407
2397 2408 #-------------------------------------------------------------------------
2398 2409 # Things related to GUI support and pylab
2399 2410 #-------------------------------------------------------------------------
2400 2411
2401 2412 def enable_pylab(self, gui=None):
2402 2413 raise NotImplementedError('Implement enable_pylab in a subclass')
2403 2414
2404 2415 #-------------------------------------------------------------------------
2405 2416 # Utilities
2406 2417 #-------------------------------------------------------------------------
2407 2418
2408 2419 def var_expand(self,cmd,depth=0):
2409 2420 """Expand python variables in a string.
2410 2421
2411 2422 The depth argument indicates how many frames above the caller should
2412 2423 be walked to look for the local namespace where to expand variables.
2413 2424
2414 2425 The global namespace for expansion is always the user's interactive
2415 2426 namespace.
2416 2427 """
2417 2428 res = ItplNS(cmd, self.user_ns, # globals
2418 2429 # Skip our own frame in searching for locals:
2419 2430 sys._getframe(depth+1).f_locals # locals
2420 2431 )
2421 2432 return str(res).decode(res.codec)
2422 2433
2423 2434 def mktempfile(self, data=None, prefix='ipython_edit_'):
2424 2435 """Make a new tempfile and return its filename.
2425 2436
2426 2437 This makes a call to tempfile.mktemp, but it registers the created
2427 2438 filename internally so ipython cleans it up at exit time.
2428 2439
2429 2440 Optional inputs:
2430 2441
2431 2442 - data(None): if data is given, it gets written out to the temp file
2432 2443 immediately, and the file is closed again."""
2433 2444
2434 2445 filename = tempfile.mktemp('.py', prefix)
2435 2446 self.tempfiles.append(filename)
2436 2447
2437 2448 if data:
2438 2449 tmp_file = open(filename,'w')
2439 2450 tmp_file.write(data)
2440 2451 tmp_file.close()
2441 2452 return filename
2442 2453
2443 2454 # TODO: This should be removed when Term is refactored.
2444 2455 def write(self,data):
2445 2456 """Write a string to the default output"""
2446 2457 io.stdout.write(data)
2447 2458
2448 2459 # TODO: This should be removed when Term is refactored.
2449 2460 def write_err(self,data):
2450 2461 """Write a string to the default error output"""
2451 2462 io.stderr.write(data)
2452 2463
2453 2464 def ask_yes_no(self,prompt,default=True):
2454 2465 if self.quiet:
2455 2466 return True
2456 2467 return ask_yes_no(prompt,default)
2457 2468
2458 2469 def show_usage(self):
2459 2470 """Show a usage message"""
2460 2471 page.page(IPython.core.usage.interactive_usage)
2461 2472
2462 2473 def find_user_code(self, target, raw=True):
2463 2474 """Get a code string from history, file, or a string or macro.
2464 2475
2465 2476 This is mainly used by magic functions.
2466 2477
2467 2478 Parameters
2468 2479 ----------
2469 2480 target : str
2470 2481 A string specifying code to retrieve. This will be tried respectively
2471 2482 as: ranges of input history (see %history for syntax), a filename, or
2472 2483 an expression evaluating to a string or Macro in the user namespace.
2473 2484 raw : bool
2474 2485 If true (default), retrieve raw history. Has no effect on the other
2475 2486 retrieval mechanisms.
2476 2487
2477 2488 Returns
2478 2489 -------
2479 2490 A string of code.
2480 2491
2481 2492 ValueError is raised if nothing is found, and TypeError if it evaluates
2482 2493 to an object of another type. In each case, .args[0] is a printable
2483 2494 message.
2484 2495 """
2485 2496 code = self.extract_input_lines(target, raw=raw) # Grab history
2486 2497 if code:
2487 2498 return code
2488 2499 if os.path.isfile(target): # Read file
2489 2500 return open(target, "r").read()
2490 2501
2491 2502 try: # User namespace
2492 2503 codeobj = eval(target, self.user_ns)
2493 2504 except Exception:
2494 2505 raise ValueError(("'%s' was not found in history, as a file, nor in"
2495 2506 " the user namespace.") % target)
2496 2507 if isinstance(codeobj, basestring):
2497 2508 return codeobj
2498 2509 elif isinstance(codeobj, Macro):
2499 2510 return codeobj.value
2500 2511
2501 2512 raise TypeError("%s is neither a string nor a macro." % target,
2502 2513 codeobj)
2503 2514
2504 2515 #-------------------------------------------------------------------------
2505 2516 # Things related to IPython exiting
2506 2517 #-------------------------------------------------------------------------
2507 2518 def atexit_operations(self):
2508 2519 """This will be executed at the time of exit.
2509 2520
2510 2521 Cleanup operations and saving of persistent data that is done
2511 2522 unconditionally by IPython should be performed here.
2512 2523
2513 2524 For things that may depend on startup flags or platform specifics (such
2514 2525 as having readline or not), register a separate atexit function in the
2515 2526 code that has the appropriate information, rather than trying to
2516 2527 clutter
2517 2528 """
2518 2529 # Cleanup all tempfiles left around
2519 2530 for tfile in self.tempfiles:
2520 2531 try:
2521 2532 os.unlink(tfile)
2522 2533 except OSError:
2523 2534 pass
2524 2535
2525 2536 # Close the history session (this stores the end time and line count)
2526 2537 self.history_manager.end_session()
2527 2538
2528 2539 # Clear all user namespaces to release all references cleanly.
2529 2540 self.reset(new_session=False)
2530 2541
2531 2542 # Run user hooks
2532 2543 self.hooks.shutdown_hook()
2533 2544
2534 2545 def cleanup(self):
2535 2546 self.restore_sys_module_state()
2536 2547
2537 2548
2538 2549 class InteractiveShellABC(object):
2539 2550 """An abstract base class for InteractiveShell."""
2540 2551 __metaclass__ = abc.ABCMeta
2541 2552
2542 2553 InteractiveShellABC.register(InteractiveShell)
@@ -1,3518 +1,3504
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 from cStringIO import StringIO
29 29 from getopt import getopt,GetoptError
30 30 from pprint import pformat
31 31 from xmlrpclib import ServerProxy
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 from IPython.core.newapplication import ProfileDir
49 50 from IPython.core.macro import Macro
50 51 from IPython.core import page
51 52 from IPython.core.prefilter import ESC_MAGIC
52 53 from IPython.lib.pylabtools import mpl_runner
53 54 from IPython.external.Itpl import itpl, printpl
54 55 from IPython.testing.skipdoctest import skip_doctest
55 56 from IPython.utils.io import file_read, nlprint
56 57 from IPython.utils.path import get_py_filename
57 58 from IPython.utils.process import arg_split, abbrev_cwd
58 59 from IPython.utils.terminal import set_term_title
59 60 from IPython.utils.text import LSString, SList, format_screen
60 61 from IPython.utils.timing import clock, clock2
61 62 from IPython.utils.warn import warn, error
62 63 from IPython.utils.ipstruct import Struct
63 64 import IPython.utils.generics
64 65
65 66 #-----------------------------------------------------------------------------
66 67 # Utility functions
67 68 #-----------------------------------------------------------------------------
68 69
69 70 def on_off(tag):
70 71 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
71 72 return ['OFF','ON'][tag]
72 73
73 74 class Bunch: pass
74 75
75 76 def compress_dhist(dh):
76 77 head, tail = dh[:-10], dh[-10:]
77 78
78 79 newhead = []
79 80 done = set()
80 81 for h in head:
81 82 if h in done:
82 83 continue
83 84 newhead.append(h)
84 85 done.add(h)
85 86
86 87 return newhead + tail
87 88
88 89 def needs_local_scope(func):
89 90 """Decorator to mark magic functions which need to local scope to run."""
90 91 func.needs_local_scope = True
91 92 return func
92 93
93 94 # Used for exception handling in magic_edit
94 95 class MacroToEdit(ValueError): pass
95 96
96 97 #***************************************************************************
97 98 # Main class implementing Magic functionality
98 99
99 100 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
100 101 # on construction of the main InteractiveShell object. Something odd is going
101 102 # on with super() calls, Configurable and the MRO... For now leave it as-is, but
102 103 # eventually this needs to be clarified.
103 104 # BG: This is because InteractiveShell inherits from this, but is itself a
104 105 # Configurable. This messes up the MRO in some way. The fix is that we need to
105 106 # make Magic a configurable that InteractiveShell does not subclass.
106 107
107 108 class Magic:
108 109 """Magic functions for InteractiveShell.
109 110
110 111 Shell functions which can be reached as %function_name. All magic
111 112 functions should accept a string, which they can parse for their own
112 113 needs. This can make some functions easier to type, eg `%cd ../`
113 114 vs. `%cd("../")`
114 115
115 116 ALL definitions MUST begin with the prefix magic_. The user won't need it
116 117 at the command line, but it is is needed in the definition. """
117 118
118 119 # class globals
119 120 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
120 121 'Automagic is ON, % prefix NOT needed for magic functions.']
121 122
122 123 #......................................................................
123 124 # some utility functions
124 125
125 126 def __init__(self,shell):
126 127
127 128 self.options_table = {}
128 129 if profile is None:
129 130 self.magic_prun = self.profile_missing_notice
130 131 self.shell = shell
131 132
132 133 # namespace for holding state we may need
133 134 self._magic_state = Bunch()
134 135
135 136 def profile_missing_notice(self, *args, **kwargs):
136 137 error("""\
137 138 The profile module could not be found. It has been removed from the standard
138 139 python packages because of its non-free license. To use profiling, install the
139 140 python-profiler package from non-free.""")
140 141
141 142 def default_option(self,fn,optstr):
142 143 """Make an entry in the options_table for fn, with value optstr"""
143 144
144 145 if fn not in self.lsmagic():
145 146 error("%s is not a magic function" % fn)
146 147 self.options_table[fn] = optstr
147 148
148 149 def lsmagic(self):
149 150 """Return a list of currently available magic functions.
150 151
151 152 Gives a list of the bare names after mangling (['ls','cd', ...], not
152 153 ['magic_ls','magic_cd',...]"""
153 154
154 155 # FIXME. This needs a cleanup, in the way the magics list is built.
155 156
156 157 # magics in class definition
157 158 class_magic = lambda fn: fn.startswith('magic_') and \
158 159 callable(Magic.__dict__[fn])
159 160 # in instance namespace (run-time user additions)
160 161 inst_magic = lambda fn: fn.startswith('magic_') and \
161 162 callable(self.__dict__[fn])
162 163 # and bound magics by user (so they can access self):
163 164 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
164 165 callable(self.__class__.__dict__[fn])
165 166 magics = filter(class_magic,Magic.__dict__.keys()) + \
166 167 filter(inst_magic,self.__dict__.keys()) + \
167 168 filter(inst_bound_magic,self.__class__.__dict__.keys())
168 169 out = []
169 170 for fn in set(magics):
170 171 out.append(fn.replace('magic_','',1))
171 172 out.sort()
172 173 return out
173 174
174 175 def extract_input_lines(self, range_str, raw=False):
175 176 """Return as a string a set of input history slices.
176 177
177 178 Inputs:
178 179
179 180 - range_str: the set of slices is given as a string, like
180 181 "~5/6-~4/2 4:8 9", since this function is for use by magic functions
181 182 which get their arguments as strings. The number before the / is the
182 183 session number: ~n goes n back from the current session.
183 184
184 185 Optional inputs:
185 186
186 187 - raw(False): by default, the processed input is used. If this is
187 188 true, the raw input history is used instead.
188 189
189 190 Note that slices can be called with two notations:
190 191
191 192 N:M -> standard python form, means including items N...(M-1).
192 193
193 194 N-M -> include items N..M (closed endpoint)."""
194 195 lines = self.shell.history_manager.\
195 196 get_range_by_str(range_str, raw=raw)
196 197 return "\n".join(x for _, _, x in lines)
197 198
198 199 def arg_err(self,func):
199 200 """Print docstring if incorrect arguments were passed"""
200 201 print 'Error in arguments:'
201 202 print oinspect.getdoc(func)
202 203
203 204 def format_latex(self,strng):
204 205 """Format a string for latex inclusion."""
205 206
206 207 # Characters that need to be escaped for latex:
207 208 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
208 209 # Magic command names as headers:
209 210 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
210 211 re.MULTILINE)
211 212 # Magic commands
212 213 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
213 214 re.MULTILINE)
214 215 # Paragraph continue
215 216 par_re = re.compile(r'\\$',re.MULTILINE)
216 217
217 218 # The "\n" symbol
218 219 newline_re = re.compile(r'\\n')
219 220
220 221 # Now build the string for output:
221 222 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
222 223 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
223 224 strng)
224 225 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
225 226 strng = par_re.sub(r'\\\\',strng)
226 227 strng = escape_re.sub(r'\\\1',strng)
227 228 strng = newline_re.sub(r'\\textbackslash{}n',strng)
228 229 return strng
229 230
230 231 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
231 232 """Parse options passed to an argument string.
232 233
233 234 The interface is similar to that of getopt(), but it returns back a
234 235 Struct with the options as keys and the stripped argument string still
235 236 as a string.
236 237
237 238 arg_str is quoted as a true sys.argv vector by using shlex.split.
238 239 This allows us to easily expand variables, glob files, quote
239 240 arguments, etc.
240 241
241 242 Options:
242 243 -mode: default 'string'. If given as 'list', the argument string is
243 244 returned as a list (split on whitespace) instead of a string.
244 245
245 246 -list_all: put all option values in lists. Normally only options
246 247 appearing more than once are put in a list.
247 248
248 249 -posix (True): whether to split the input line in POSIX mode or not,
249 250 as per the conventions outlined in the shlex module from the
250 251 standard library."""
251 252
252 253 # inject default options at the beginning of the input line
253 254 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
254 255 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
255 256
256 257 mode = kw.get('mode','string')
257 258 if mode not in ['string','list']:
258 259 raise ValueError,'incorrect mode given: %s' % mode
259 260 # Get options
260 261 list_all = kw.get('list_all',0)
261 262 posix = kw.get('posix', os.name == 'posix')
262 263
263 264 # Check if we have more than one argument to warrant extra processing:
264 265 odict = {} # Dictionary with options
265 266 args = arg_str.split()
266 267 if len(args) >= 1:
267 268 # If the list of inputs only has 0 or 1 thing in it, there's no
268 269 # need to look for options
269 270 argv = arg_split(arg_str,posix)
270 271 # Do regular option processing
271 272 try:
272 273 opts,args = getopt(argv,opt_str,*long_opts)
273 274 except GetoptError,e:
274 275 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
275 276 " ".join(long_opts)))
276 277 for o,a in opts:
277 278 if o.startswith('--'):
278 279 o = o[2:]
279 280 else:
280 281 o = o[1:]
281 282 try:
282 283 odict[o].append(a)
283 284 except AttributeError:
284 285 odict[o] = [odict[o],a]
285 286 except KeyError:
286 287 if list_all:
287 288 odict[o] = [a]
288 289 else:
289 290 odict[o] = a
290 291
291 292 # Prepare opts,args for return
292 293 opts = Struct(odict)
293 294 if mode == 'string':
294 295 args = ' '.join(args)
295 296
296 297 return opts,args
297 298
298 299 #......................................................................
299 300 # And now the actual magic functions
300 301
301 302 # Functions for IPython shell work (vars,funcs, config, etc)
302 303 def magic_lsmagic(self, parameter_s = ''):
303 304 """List currently available magic functions."""
304 305 mesc = ESC_MAGIC
305 306 print 'Available magic functions:\n'+mesc+\
306 307 (' '+mesc).join(self.lsmagic())
307 308 print '\n' + Magic.auto_status[self.shell.automagic]
308 309 return None
309 310
310 311 def magic_magic(self, parameter_s = ''):
311 312 """Print information about the magic function system.
312 313
313 314 Supported formats: -latex, -brief, -rest
314 315 """
315 316
316 317 mode = ''
317 318 try:
318 319 if parameter_s.split()[0] == '-latex':
319 320 mode = 'latex'
320 321 if parameter_s.split()[0] == '-brief':
321 322 mode = 'brief'
322 323 if parameter_s.split()[0] == '-rest':
323 324 mode = 'rest'
324 325 rest_docs = []
325 326 except:
326 327 pass
327 328
328 329 magic_docs = []
329 330 for fname in self.lsmagic():
330 331 mname = 'magic_' + fname
331 332 for space in (Magic,self,self.__class__):
332 333 try:
333 334 fn = space.__dict__[mname]
334 335 except KeyError:
335 336 pass
336 337 else:
337 338 break
338 339 if mode == 'brief':
339 340 # only first line
340 341 if fn.__doc__:
341 342 fndoc = fn.__doc__.split('\n',1)[0]
342 343 else:
343 344 fndoc = 'No documentation'
344 345 else:
345 346 if fn.__doc__:
346 347 fndoc = fn.__doc__.rstrip()
347 348 else:
348 349 fndoc = 'No documentation'
349 350
350 351
351 352 if mode == 'rest':
352 353 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
353 354 fname,fndoc))
354 355
355 356 else:
356 357 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
357 358 fname,fndoc))
358 359
359 360 magic_docs = ''.join(magic_docs)
360 361
361 362 if mode == 'rest':
362 363 return "".join(rest_docs)
363 364
364 365 if mode == 'latex':
365 366 print self.format_latex(magic_docs)
366 367 return
367 368 else:
368 369 magic_docs = format_screen(magic_docs)
369 370 if mode == 'brief':
370 371 return magic_docs
371 372
372 373 outmsg = """
373 374 IPython's 'magic' functions
374 375 ===========================
375 376
376 377 The magic function system provides a series of functions which allow you to
377 378 control the behavior of IPython itself, plus a lot of system-type
378 379 features. All these functions are prefixed with a % character, but parameters
379 380 are given without parentheses or quotes.
380 381
381 382 NOTE: If you have 'automagic' enabled (via the command line option or with the
382 383 %automagic function), you don't need to type in the % explicitly. By default,
383 384 IPython ships with automagic on, so you should only rarely need the % escape.
384 385
385 386 Example: typing '%cd mydir' (without the quotes) changes you working directory
386 387 to 'mydir', if it exists.
387 388
388 389 You can define your own magic functions to extend the system. See the supplied
389 390 ipythonrc and example-magic.py files for details (in your ipython
390 391 configuration directory, typically $HOME/.config/ipython on Linux or $HOME/.ipython elsewhere).
391 392
392 393 You can also define your own aliased names for magic functions. In your
393 394 ipythonrc file, placing a line like:
394 395
395 396 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
396 397
397 398 will define %pf as a new name for %profile.
398 399
399 400 You can also call magics in code using the magic() function, which IPython
400 401 automatically adds to the builtin namespace. Type 'magic?' for details.
401 402
402 403 For a list of the available magic functions, use %lsmagic. For a description
403 404 of any of them, type %magic_name?, e.g. '%cd?'.
404 405
405 406 Currently the magic system has the following functions:\n"""
406 407
407 408 mesc = ESC_MAGIC
408 409 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
409 410 "\n\n%s%s\n\n%s" % (outmsg,
410 411 magic_docs,mesc,mesc,
411 412 (' '+mesc).join(self.lsmagic()),
412 413 Magic.auto_status[self.shell.automagic] ) )
413 414 page.page(outmsg)
414 415
415 416 def magic_automagic(self, parameter_s = ''):
416 417 """Make magic functions callable without having to type the initial %.
417 418
418 419 Without argumentsl toggles on/off (when off, you must call it as
419 420 %automagic, of course). With arguments it sets the value, and you can
420 421 use any of (case insensitive):
421 422
422 423 - on,1,True: to activate
423 424
424 425 - off,0,False: to deactivate.
425 426
426 427 Note that magic functions have lowest priority, so if there's a
427 428 variable whose name collides with that of a magic fn, automagic won't
428 429 work for that function (you get the variable instead). However, if you
429 430 delete the variable (del var), the previously shadowed magic function
430 431 becomes visible to automagic again."""
431 432
432 433 arg = parameter_s.lower()
433 434 if parameter_s in ('on','1','true'):
434 435 self.shell.automagic = True
435 436 elif parameter_s in ('off','0','false'):
436 437 self.shell.automagic = False
437 438 else:
438 439 self.shell.automagic = not self.shell.automagic
439 440 print '\n' + Magic.auto_status[self.shell.automagic]
440 441
441 442 @skip_doctest
442 443 def magic_autocall(self, parameter_s = ''):
443 444 """Make functions callable without having to type parentheses.
444 445
445 446 Usage:
446 447
447 448 %autocall [mode]
448 449
449 450 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
450 451 value is toggled on and off (remembering the previous state).
451 452
452 453 In more detail, these values mean:
453 454
454 455 0 -> fully disabled
455 456
456 457 1 -> active, but do not apply if there are no arguments on the line.
457 458
458 459 In this mode, you get:
459 460
460 461 In [1]: callable
461 462 Out[1]: <built-in function callable>
462 463
463 464 In [2]: callable 'hello'
464 465 ------> callable('hello')
465 466 Out[2]: False
466 467
467 468 2 -> Active always. Even if no arguments are present, the callable
468 469 object is called:
469 470
470 471 In [2]: float
471 472 ------> float()
472 473 Out[2]: 0.0
473 474
474 475 Note that even with autocall off, you can still use '/' at the start of
475 476 a line to treat the first argument on the command line as a function
476 477 and add parentheses to it:
477 478
478 479 In [8]: /str 43
479 480 ------> str(43)
480 481 Out[8]: '43'
481 482
482 483 # all-random (note for auto-testing)
483 484 """
484 485
485 486 if parameter_s:
486 487 arg = int(parameter_s)
487 488 else:
488 489 arg = 'toggle'
489 490
490 491 if not arg in (0,1,2,'toggle'):
491 492 error('Valid modes: (0->Off, 1->Smart, 2->Full')
492 493 return
493 494
494 495 if arg in (0,1,2):
495 496 self.shell.autocall = arg
496 497 else: # toggle
497 498 if self.shell.autocall:
498 499 self._magic_state.autocall_save = self.shell.autocall
499 500 self.shell.autocall = 0
500 501 else:
501 502 try:
502 503 self.shell.autocall = self._magic_state.autocall_save
503 504 except AttributeError:
504 505 self.shell.autocall = self._magic_state.autocall_save = 1
505 506
506 507 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
507 508
508 509
509 510 def magic_page(self, parameter_s=''):
510 511 """Pretty print the object and display it through a pager.
511 512
512 513 %page [options] OBJECT
513 514
514 515 If no object is given, use _ (last output).
515 516
516 517 Options:
517 518
518 519 -r: page str(object), don't pretty-print it."""
519 520
520 521 # After a function contributed by Olivier Aubert, slightly modified.
521 522
522 523 # Process options/args
523 524 opts,args = self.parse_options(parameter_s,'r')
524 525 raw = 'r' in opts
525 526
526 527 oname = args and args or '_'
527 528 info = self._ofind(oname)
528 529 if info['found']:
529 530 txt = (raw and str or pformat)( info['obj'] )
530 531 page.page(txt)
531 532 else:
532 533 print 'Object `%s` not found' % oname
533 534
534 535 def magic_profile(self, parameter_s=''):
535 536 """Print your currently active IPython profile."""
536 if self.shell.profile:
537 printpl('Current IPython profile: $self.shell.profile.')
538 else:
539 print 'No profile active.'
537 print self.shell.profile
540 538
541 539 def magic_pinfo(self, parameter_s='', namespaces=None):
542 540 """Provide detailed information about an object.
543 541
544 542 '%pinfo object' is just a synonym for object? or ?object."""
545 543
546 544 #print 'pinfo par: <%s>' % parameter_s # dbg
547 545
548 546
549 547 # detail_level: 0 -> obj? , 1 -> obj??
550 548 detail_level = 0
551 549 # We need to detect if we got called as 'pinfo pinfo foo', which can
552 550 # happen if the user types 'pinfo foo?' at the cmd line.
553 551 pinfo,qmark1,oname,qmark2 = \
554 552 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
555 553 if pinfo or qmark1 or qmark2:
556 554 detail_level = 1
557 555 if "*" in oname:
558 556 self.magic_psearch(oname)
559 557 else:
560 558 self.shell._inspect('pinfo', oname, detail_level=detail_level,
561 559 namespaces=namespaces)
562 560
563 561 def magic_pinfo2(self, parameter_s='', namespaces=None):
564 562 """Provide extra detailed information about an object.
565 563
566 564 '%pinfo2 object' is just a synonym for object?? or ??object."""
567 565 self.shell._inspect('pinfo', parameter_s, detail_level=1,
568 566 namespaces=namespaces)
569 567
570 568 @skip_doctest
571 569 def magic_pdef(self, parameter_s='', namespaces=None):
572 570 """Print the definition header for any callable object.
573 571
574 572 If the object is a class, print the constructor information.
575 573
576 574 Examples
577 575 --------
578 576 ::
579 577
580 578 In [3]: %pdef urllib.urlopen
581 579 urllib.urlopen(url, data=None, proxies=None)
582 580 """
583 581 self._inspect('pdef',parameter_s, namespaces)
584 582
585 583 def magic_pdoc(self, parameter_s='', namespaces=None):
586 584 """Print the docstring for an object.
587 585
588 586 If the given object is a class, it will print both the class and the
589 587 constructor docstrings."""
590 588 self._inspect('pdoc',parameter_s, namespaces)
591 589
592 590 def magic_psource(self, parameter_s='', namespaces=None):
593 591 """Print (or run through pager) the source code for an object."""
594 592 self._inspect('psource',parameter_s, namespaces)
595 593
596 594 def magic_pfile(self, parameter_s=''):
597 595 """Print (or run through pager) the file where an object is defined.
598 596
599 597 The file opens at the line where the object definition begins. IPython
600 598 will honor the environment variable PAGER if set, and otherwise will
601 599 do its best to print the file in a convenient form.
602 600
603 601 If the given argument is not an object currently defined, IPython will
604 602 try to interpret it as a filename (automatically adding a .py extension
605 603 if needed). You can thus use %pfile as a syntax highlighting code
606 604 viewer."""
607 605
608 606 # first interpret argument as an object name
609 607 out = self._inspect('pfile',parameter_s)
610 608 # if not, try the input as a filename
611 609 if out == 'not found':
612 610 try:
613 611 filename = get_py_filename(parameter_s)
614 612 except IOError,msg:
615 613 print msg
616 614 return
617 615 page.page(self.shell.inspector.format(file(filename).read()))
618 616
619 617 def magic_psearch(self, parameter_s=''):
620 618 """Search for object in namespaces by wildcard.
621 619
622 620 %psearch [options] PATTERN [OBJECT TYPE]
623 621
624 622 Note: ? can be used as a synonym for %psearch, at the beginning or at
625 623 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
626 624 rest of the command line must be unchanged (options come first), so
627 625 for example the following forms are equivalent
628 626
629 627 %psearch -i a* function
630 628 -i a* function?
631 629 ?-i a* function
632 630
633 631 Arguments:
634 632
635 633 PATTERN
636 634
637 635 where PATTERN is a string containing * as a wildcard similar to its
638 636 use in a shell. The pattern is matched in all namespaces on the
639 637 search path. By default objects starting with a single _ are not
640 638 matched, many IPython generated objects have a single
641 639 underscore. The default is case insensitive matching. Matching is
642 640 also done on the attributes of objects and not only on the objects
643 641 in a module.
644 642
645 643 [OBJECT TYPE]
646 644
647 645 Is the name of a python type from the types module. The name is
648 646 given in lowercase without the ending type, ex. StringType is
649 647 written string. By adding a type here only objects matching the
650 648 given type are matched. Using all here makes the pattern match all
651 649 types (this is the default).
652 650
653 651 Options:
654 652
655 653 -a: makes the pattern match even objects whose names start with a
656 654 single underscore. These names are normally ommitted from the
657 655 search.
658 656
659 657 -i/-c: make the pattern case insensitive/sensitive. If neither of
660 658 these options is given, the default is read from your ipythonrc
661 659 file. The option name which sets this value is
662 660 'wildcards_case_sensitive'. If this option is not specified in your
663 661 ipythonrc file, IPython's internal default is to do a case sensitive
664 662 search.
665 663
666 664 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
667 665 specifiy can be searched in any of the following namespaces:
668 666 'builtin', 'user', 'user_global','internal', 'alias', where
669 667 'builtin' and 'user' are the search defaults. Note that you should
670 668 not use quotes when specifying namespaces.
671 669
672 670 'Builtin' contains the python module builtin, 'user' contains all
673 671 user data, 'alias' only contain the shell aliases and no python
674 672 objects, 'internal' contains objects used by IPython. The
675 673 'user_global' namespace is only used by embedded IPython instances,
676 674 and it contains module-level globals. You can add namespaces to the
677 675 search with -s or exclude them with -e (these options can be given
678 676 more than once).
679 677
680 678 Examples:
681 679
682 680 %psearch a* -> objects beginning with an a
683 681 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
684 682 %psearch a* function -> all functions beginning with an a
685 683 %psearch re.e* -> objects beginning with an e in module re
686 684 %psearch r*.e* -> objects that start with e in modules starting in r
687 685 %psearch r*.* string -> all strings in modules beginning with r
688 686
689 687 Case sensitve search:
690 688
691 689 %psearch -c a* list all object beginning with lower case a
692 690
693 691 Show objects beginning with a single _:
694 692
695 693 %psearch -a _* list objects beginning with a single underscore"""
696 694 try:
697 695 parameter_s = parameter_s.encode('ascii')
698 696 except UnicodeEncodeError:
699 697 print 'Python identifiers can only contain ascii characters.'
700 698 return
701 699
702 700 # default namespaces to be searched
703 701 def_search = ['user','builtin']
704 702
705 703 # Process options/args
706 704 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
707 705 opt = opts.get
708 706 shell = self.shell
709 707 psearch = shell.inspector.psearch
710 708
711 709 # select case options
712 710 if opts.has_key('i'):
713 711 ignore_case = True
714 712 elif opts.has_key('c'):
715 713 ignore_case = False
716 714 else:
717 715 ignore_case = not shell.wildcards_case_sensitive
718 716
719 717 # Build list of namespaces to search from user options
720 718 def_search.extend(opt('s',[]))
721 719 ns_exclude = ns_exclude=opt('e',[])
722 720 ns_search = [nm for nm in def_search if nm not in ns_exclude]
723 721
724 722 # Call the actual search
725 723 try:
726 724 psearch(args,shell.ns_table,ns_search,
727 725 show_all=opt('a'),ignore_case=ignore_case)
728 726 except:
729 727 shell.showtraceback()
730 728
731 729 @skip_doctest
732 730 def magic_who_ls(self, parameter_s=''):
733 731 """Return a sorted list of all interactive variables.
734 732
735 733 If arguments are given, only variables of types matching these
736 734 arguments are returned.
737 735
738 736 Examples
739 737 --------
740 738
741 739 Define two variables and list them with who_ls::
742 740
743 741 In [1]: alpha = 123
744 742
745 743 In [2]: beta = 'test'
746 744
747 745 In [3]: %who_ls
748 746 Out[3]: ['alpha', 'beta']
749 747
750 748 In [4]: %who_ls int
751 749 Out[4]: ['alpha']
752 750
753 751 In [5]: %who_ls str
754 752 Out[5]: ['beta']
755 753 """
756 754
757 755 user_ns = self.shell.user_ns
758 756 internal_ns = self.shell.internal_ns
759 757 user_ns_hidden = self.shell.user_ns_hidden
760 758 out = [ i for i in user_ns
761 759 if not i.startswith('_') \
762 760 and not (i in internal_ns or i in user_ns_hidden) ]
763 761
764 762 typelist = parameter_s.split()
765 763 if typelist:
766 764 typeset = set(typelist)
767 765 out = [i for i in out if type(user_ns[i]).__name__ in typeset]
768 766
769 767 out.sort()
770 768 return out
771 769
772 770 @skip_doctest
773 771 def magic_who(self, parameter_s=''):
774 772 """Print all interactive variables, with some minimal formatting.
775 773
776 774 If any arguments are given, only variables whose type matches one of
777 775 these are printed. For example:
778 776
779 777 %who function str
780 778
781 779 will only list functions and strings, excluding all other types of
782 780 variables. To find the proper type names, simply use type(var) at a
783 781 command line to see how python prints type names. For example:
784 782
785 783 In [1]: type('hello')\\
786 784 Out[1]: <type 'str'>
787 785
788 786 indicates that the type name for strings is 'str'.
789 787
790 788 %who always excludes executed names loaded through your configuration
791 789 file and things which are internal to IPython.
792 790
793 791 This is deliberate, as typically you may load many modules and the
794 792 purpose of %who is to show you only what you've manually defined.
795 793
796 794 Examples
797 795 --------
798 796
799 797 Define two variables and list them with who::
800 798
801 799 In [1]: alpha = 123
802 800
803 801 In [2]: beta = 'test'
804 802
805 803 In [3]: %who
806 804 alpha beta
807 805
808 806 In [4]: %who int
809 807 alpha
810 808
811 809 In [5]: %who str
812 810 beta
813 811 """
814 812
815 813 varlist = self.magic_who_ls(parameter_s)
816 814 if not varlist:
817 815 if parameter_s:
818 816 print 'No variables match your requested type.'
819 817 else:
820 818 print 'Interactive namespace is empty.'
821 819 return
822 820
823 821 # if we have variables, move on...
824 822 count = 0
825 823 for i in varlist:
826 824 print i+'\t',
827 825 count += 1
828 826 if count > 8:
829 827 count = 0
830 828 print
831 829 print
832 830
833 831 @skip_doctest
834 832 def magic_whos(self, parameter_s=''):
835 833 """Like %who, but gives some extra information about each variable.
836 834
837 835 The same type filtering of %who can be applied here.
838 836
839 837 For all variables, the type is printed. Additionally it prints:
840 838
841 839 - For {},[],(): their length.
842 840
843 841 - For numpy arrays, a summary with shape, number of
844 842 elements, typecode and size in memory.
845 843
846 844 - Everything else: a string representation, snipping their middle if
847 845 too long.
848 846
849 847 Examples
850 848 --------
851 849
852 850 Define two variables and list them with whos::
853 851
854 852 In [1]: alpha = 123
855 853
856 854 In [2]: beta = 'test'
857 855
858 856 In [3]: %whos
859 857 Variable Type Data/Info
860 858 --------------------------------
861 859 alpha int 123
862 860 beta str test
863 861 """
864 862
865 863 varnames = self.magic_who_ls(parameter_s)
866 864 if not varnames:
867 865 if parameter_s:
868 866 print 'No variables match your requested type.'
869 867 else:
870 868 print 'Interactive namespace is empty.'
871 869 return
872 870
873 871 # if we have variables, move on...
874 872
875 873 # for these types, show len() instead of data:
876 874 seq_types = ['dict', 'list', 'tuple']
877 875
878 876 # for numpy/Numeric arrays, display summary info
879 877 try:
880 878 import numpy
881 879 except ImportError:
882 880 ndarray_type = None
883 881 else:
884 882 ndarray_type = numpy.ndarray.__name__
885 883 try:
886 884 import Numeric
887 885 except ImportError:
888 886 array_type = None
889 887 else:
890 888 array_type = Numeric.ArrayType.__name__
891 889
892 890 # Find all variable names and types so we can figure out column sizes
893 891 def get_vars(i):
894 892 return self.shell.user_ns[i]
895 893
896 894 # some types are well known and can be shorter
897 895 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
898 896 def type_name(v):
899 897 tn = type(v).__name__
900 898 return abbrevs.get(tn,tn)
901 899
902 900 varlist = map(get_vars,varnames)
903 901
904 902 typelist = []
905 903 for vv in varlist:
906 904 tt = type_name(vv)
907 905
908 906 if tt=='instance':
909 907 typelist.append( abbrevs.get(str(vv.__class__),
910 908 str(vv.__class__)))
911 909 else:
912 910 typelist.append(tt)
913 911
914 912 # column labels and # of spaces as separator
915 913 varlabel = 'Variable'
916 914 typelabel = 'Type'
917 915 datalabel = 'Data/Info'
918 916 colsep = 3
919 917 # variable format strings
920 918 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
921 919 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
922 920 aformat = "%s: %s elems, type `%s`, %s bytes"
923 921 # find the size of the columns to format the output nicely
924 922 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
925 923 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
926 924 # table header
927 925 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
928 926 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
929 927 # and the table itself
930 928 kb = 1024
931 929 Mb = 1048576 # kb**2
932 930 for vname,var,vtype in zip(varnames,varlist,typelist):
933 931 print itpl(vformat),
934 932 if vtype in seq_types:
935 933 print "n="+str(len(var))
936 934 elif vtype in [array_type,ndarray_type]:
937 935 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
938 936 if vtype==ndarray_type:
939 937 # numpy
940 938 vsize = var.size
941 939 vbytes = vsize*var.itemsize
942 940 vdtype = var.dtype
943 941 else:
944 942 # Numeric
945 943 vsize = Numeric.size(var)
946 944 vbytes = vsize*var.itemsize()
947 945 vdtype = var.typecode()
948 946
949 947 if vbytes < 100000:
950 948 print aformat % (vshape,vsize,vdtype,vbytes)
951 949 else:
952 950 print aformat % (vshape,vsize,vdtype,vbytes),
953 951 if vbytes < Mb:
954 952 print '(%s kb)' % (vbytes/kb,)
955 953 else:
956 954 print '(%s Mb)' % (vbytes/Mb,)
957 955 else:
958 956 try:
959 957 vstr = str(var)
960 958 except UnicodeEncodeError:
961 959 vstr = unicode(var).encode(sys.getdefaultencoding(),
962 960 'backslashreplace')
963 961 vstr = vstr.replace('\n','\\n')
964 962 if len(vstr) < 50:
965 963 print vstr
966 964 else:
967 965 printpl(vfmt_short)
968 966
969 967 def magic_reset(self, parameter_s=''):
970 968 """Resets the namespace by removing all names defined by the user.
971 969
972 970 Parameters
973 971 ----------
974 972 -f : force reset without asking for confirmation.
975 973
976 974 -s : 'Soft' reset: Only clears your namespace, leaving history intact.
977 975 References to objects may be kept. By default (without this option),
978 976 we do a 'hard' reset, giving you a new session and removing all
979 977 references to objects from the current session.
980 978
981 979 Examples
982 980 --------
983 981 In [6]: a = 1
984 982
985 983 In [7]: a
986 984 Out[7]: 1
987 985
988 986 In [8]: 'a' in _ip.user_ns
989 987 Out[8]: True
990 988
991 989 In [9]: %reset -f
992 990
993 991 In [1]: 'a' in _ip.user_ns
994 992 Out[1]: False
995 993 """
996 994 opts, args = self.parse_options(parameter_s,'sf')
997 995 if 'f' in opts:
998 996 ans = True
999 997 else:
1000 998 ans = self.shell.ask_yes_no(
1001 999 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1002 1000 if not ans:
1003 1001 print 'Nothing done.'
1004 1002 return
1005 1003
1006 1004 if 's' in opts: # Soft reset
1007 1005 user_ns = self.shell.user_ns
1008 1006 for i in self.magic_who_ls():
1009 1007 del(user_ns[i])
1010 1008
1011 1009 else: # Hard reset
1012 1010 self.shell.reset(new_session = False)
1013 1011
1014 1012
1015 1013
1016 1014 def magic_reset_selective(self, parameter_s=''):
1017 1015 """Resets the namespace by removing names defined by the user.
1018 1016
1019 1017 Input/Output history are left around in case you need them.
1020 1018
1021 1019 %reset_selective [-f] regex
1022 1020
1023 1021 No action is taken if regex is not included
1024 1022
1025 1023 Options
1026 1024 -f : force reset without asking for confirmation.
1027 1025
1028 1026 Examples
1029 1027 --------
1030 1028
1031 1029 We first fully reset the namespace so your output looks identical to
1032 1030 this example for pedagogical reasons; in practice you do not need a
1033 1031 full reset.
1034 1032
1035 1033 In [1]: %reset -f
1036 1034
1037 1035 Now, with a clean namespace we can make a few variables and use
1038 1036 %reset_selective to only delete names that match our regexp:
1039 1037
1040 1038 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1041 1039
1042 1040 In [3]: who_ls
1043 1041 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1044 1042
1045 1043 In [4]: %reset_selective -f b[2-3]m
1046 1044
1047 1045 In [5]: who_ls
1048 1046 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1049 1047
1050 1048 In [6]: %reset_selective -f d
1051 1049
1052 1050 In [7]: who_ls
1053 1051 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1054 1052
1055 1053 In [8]: %reset_selective -f c
1056 1054
1057 1055 In [9]: who_ls
1058 1056 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1059 1057
1060 1058 In [10]: %reset_selective -f b
1061 1059
1062 1060 In [11]: who_ls
1063 1061 Out[11]: ['a']
1064 1062 """
1065 1063
1066 1064 opts, regex = self.parse_options(parameter_s,'f')
1067 1065
1068 1066 if opts.has_key('f'):
1069 1067 ans = True
1070 1068 else:
1071 1069 ans = self.shell.ask_yes_no(
1072 1070 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1073 1071 if not ans:
1074 1072 print 'Nothing done.'
1075 1073 return
1076 1074 user_ns = self.shell.user_ns
1077 1075 if not regex:
1078 1076 print 'No regex pattern specified. Nothing done.'
1079 1077 return
1080 1078 else:
1081 1079 try:
1082 1080 m = re.compile(regex)
1083 1081 except TypeError:
1084 1082 raise TypeError('regex must be a string or compiled pattern')
1085 1083 for i in self.magic_who_ls():
1086 1084 if m.search(i):
1087 1085 del(user_ns[i])
1088 1086
1089 1087 def magic_xdel(self, parameter_s=''):
1090 1088 """Delete a variable, trying to clear it from anywhere that
1091 1089 IPython's machinery has references to it. By default, this uses
1092 1090 the identity of the named object in the user namespace to remove
1093 1091 references held under other names. The object is also removed
1094 1092 from the output history.
1095 1093
1096 1094 Options
1097 1095 -n : Delete the specified name from all namespaces, without
1098 1096 checking their identity.
1099 1097 """
1100 1098 opts, varname = self.parse_options(parameter_s,'n')
1101 1099 try:
1102 1100 self.shell.del_var(varname, ('n' in opts))
1103 1101 except (NameError, ValueError) as e:
1104 1102 print type(e).__name__ +": "+ str(e)
1105 1103
1106 1104 def magic_logstart(self,parameter_s=''):
1107 1105 """Start logging anywhere in a session.
1108 1106
1109 1107 %logstart [-o|-r|-t] [log_name [log_mode]]
1110 1108
1111 1109 If no name is given, it defaults to a file named 'ipython_log.py' in your
1112 1110 current directory, in 'rotate' mode (see below).
1113 1111
1114 1112 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1115 1113 history up to that point and then continues logging.
1116 1114
1117 1115 %logstart takes a second optional parameter: logging mode. This can be one
1118 1116 of (note that the modes are given unquoted):\\
1119 1117 append: well, that says it.\\
1120 1118 backup: rename (if exists) to name~ and start name.\\
1121 1119 global: single logfile in your home dir, appended to.\\
1122 1120 over : overwrite existing log.\\
1123 1121 rotate: create rotating logs name.1~, name.2~, etc.
1124 1122
1125 1123 Options:
1126 1124
1127 1125 -o: log also IPython's output. In this mode, all commands which
1128 1126 generate an Out[NN] prompt are recorded to the logfile, right after
1129 1127 their corresponding input line. The output lines are always
1130 1128 prepended with a '#[Out]# ' marker, so that the log remains valid
1131 1129 Python code.
1132 1130
1133 1131 Since this marker is always the same, filtering only the output from
1134 1132 a log is very easy, using for example a simple awk call:
1135 1133
1136 1134 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1137 1135
1138 1136 -r: log 'raw' input. Normally, IPython's logs contain the processed
1139 1137 input, so that user lines are logged in their final form, converted
1140 1138 into valid Python. For example, %Exit is logged as
1141 1139 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1142 1140 exactly as typed, with no transformations applied.
1143 1141
1144 1142 -t: put timestamps before each input line logged (these are put in
1145 1143 comments)."""
1146 1144
1147 1145 opts,par = self.parse_options(parameter_s,'ort')
1148 1146 log_output = 'o' in opts
1149 1147 log_raw_input = 'r' in opts
1150 1148 timestamp = 't' in opts
1151 1149
1152 1150 logger = self.shell.logger
1153 1151
1154 1152 # if no args are given, the defaults set in the logger constructor by
1155 1153 # ipytohn remain valid
1156 1154 if par:
1157 1155 try:
1158 1156 logfname,logmode = par.split()
1159 1157 except:
1160 1158 logfname = par
1161 1159 logmode = 'backup'
1162 1160 else:
1163 1161 logfname = logger.logfname
1164 1162 logmode = logger.logmode
1165 1163 # put logfname into rc struct as if it had been called on the command
1166 1164 # line, so it ends up saved in the log header Save it in case we need
1167 1165 # to restore it...
1168 1166 old_logfile = self.shell.logfile
1169 1167 if logfname:
1170 1168 logfname = os.path.expanduser(logfname)
1171 1169 self.shell.logfile = logfname
1172 1170
1173 1171 loghead = '# IPython log file\n\n'
1174 1172 try:
1175 1173 started = logger.logstart(logfname,loghead,logmode,
1176 1174 log_output,timestamp,log_raw_input)
1177 1175 except:
1178 1176 self.shell.logfile = old_logfile
1179 1177 warn("Couldn't start log: %s" % sys.exc_info()[1])
1180 1178 else:
1181 1179 # log input history up to this point, optionally interleaving
1182 1180 # output if requested
1183 1181
1184 1182 if timestamp:
1185 1183 # disable timestamping for the previous history, since we've
1186 1184 # lost those already (no time machine here).
1187 1185 logger.timestamp = False
1188 1186
1189 1187 if log_raw_input:
1190 1188 input_hist = self.shell.history_manager.input_hist_raw
1191 1189 else:
1192 1190 input_hist = self.shell.history_manager.input_hist_parsed
1193 1191
1194 1192 if log_output:
1195 1193 log_write = logger.log_write
1196 1194 output_hist = self.shell.history_manager.output_hist
1197 1195 for n in range(1,len(input_hist)-1):
1198 1196 log_write(input_hist[n].rstrip() + '\n')
1199 1197 if n in output_hist:
1200 1198 log_write(repr(output_hist[n]),'output')
1201 1199 else:
1202 1200 logger.log_write('\n'.join(input_hist[1:]))
1203 1201 logger.log_write('\n')
1204 1202 if timestamp:
1205 1203 # re-enable timestamping
1206 1204 logger.timestamp = True
1207 1205
1208 1206 print ('Activating auto-logging. '
1209 1207 'Current session state plus future input saved.')
1210 1208 logger.logstate()
1211 1209
1212 1210 def magic_logstop(self,parameter_s=''):
1213 1211 """Fully stop logging and close log file.
1214 1212
1215 1213 In order to start logging again, a new %logstart call needs to be made,
1216 1214 possibly (though not necessarily) with a new filename, mode and other
1217 1215 options."""
1218 1216 self.logger.logstop()
1219 1217
1220 1218 def magic_logoff(self,parameter_s=''):
1221 1219 """Temporarily stop logging.
1222 1220
1223 1221 You must have previously started logging."""
1224 1222 self.shell.logger.switch_log(0)
1225 1223
1226 1224 def magic_logon(self,parameter_s=''):
1227 1225 """Restart logging.
1228 1226
1229 1227 This function is for restarting logging which you've temporarily
1230 1228 stopped with %logoff. For starting logging for the first time, you
1231 1229 must use the %logstart function, which allows you to specify an
1232 1230 optional log filename."""
1233 1231
1234 1232 self.shell.logger.switch_log(1)
1235 1233
1236 1234 def magic_logstate(self,parameter_s=''):
1237 1235 """Print the status of the logging system."""
1238 1236
1239 1237 self.shell.logger.logstate()
1240 1238
1241 1239 def magic_pdb(self, parameter_s=''):
1242 1240 """Control the automatic calling of the pdb interactive debugger.
1243 1241
1244 1242 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1245 1243 argument it works as a toggle.
1246 1244
1247 1245 When an exception is triggered, IPython can optionally call the
1248 1246 interactive pdb debugger after the traceback printout. %pdb toggles
1249 1247 this feature on and off.
1250 1248
1251 1249 The initial state of this feature is set in your ipythonrc
1252 1250 configuration file (the variable is called 'pdb').
1253 1251
1254 1252 If you want to just activate the debugger AFTER an exception has fired,
1255 1253 without having to type '%pdb on' and rerunning your code, you can use
1256 1254 the %debug magic."""
1257 1255
1258 1256 par = parameter_s.strip().lower()
1259 1257
1260 1258 if par:
1261 1259 try:
1262 1260 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1263 1261 except KeyError:
1264 1262 print ('Incorrect argument. Use on/1, off/0, '
1265 1263 'or nothing for a toggle.')
1266 1264 return
1267 1265 else:
1268 1266 # toggle
1269 1267 new_pdb = not self.shell.call_pdb
1270 1268
1271 1269 # set on the shell
1272 1270 self.shell.call_pdb = new_pdb
1273 1271 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1274 1272
1275 1273 def magic_debug(self, parameter_s=''):
1276 1274 """Activate the interactive debugger in post-mortem mode.
1277 1275
1278 1276 If an exception has just occurred, this lets you inspect its stack
1279 1277 frames interactively. Note that this will always work only on the last
1280 1278 traceback that occurred, so you must call this quickly after an
1281 1279 exception that you wish to inspect has fired, because if another one
1282 1280 occurs, it clobbers the previous one.
1283 1281
1284 1282 If you want IPython to automatically do this on every exception, see
1285 1283 the %pdb magic for more details.
1286 1284 """
1287 1285 self.shell.debugger(force=True)
1288 1286
1289 1287 @skip_doctest
1290 1288 def magic_prun(self, parameter_s ='',user_mode=1,
1291 1289 opts=None,arg_lst=None,prog_ns=None):
1292 1290
1293 1291 """Run a statement through the python code profiler.
1294 1292
1295 1293 Usage:
1296 1294 %prun [options] statement
1297 1295
1298 1296 The given statement (which doesn't require quote marks) is run via the
1299 1297 python profiler in a manner similar to the profile.run() function.
1300 1298 Namespaces are internally managed to work correctly; profile.run
1301 1299 cannot be used in IPython because it makes certain assumptions about
1302 1300 namespaces which do not hold under IPython.
1303 1301
1304 1302 Options:
1305 1303
1306 1304 -l <limit>: you can place restrictions on what or how much of the
1307 1305 profile gets printed. The limit value can be:
1308 1306
1309 1307 * A string: only information for function names containing this string
1310 1308 is printed.
1311 1309
1312 1310 * An integer: only these many lines are printed.
1313 1311
1314 1312 * A float (between 0 and 1): this fraction of the report is printed
1315 1313 (for example, use a limit of 0.4 to see the topmost 40% only).
1316 1314
1317 1315 You can combine several limits with repeated use of the option. For
1318 1316 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1319 1317 information about class constructors.
1320 1318
1321 1319 -r: return the pstats.Stats object generated by the profiling. This
1322 1320 object has all the information about the profile in it, and you can
1323 1321 later use it for further analysis or in other functions.
1324 1322
1325 1323 -s <key>: sort profile by given key. You can provide more than one key
1326 1324 by using the option several times: '-s key1 -s key2 -s key3...'. The
1327 1325 default sorting key is 'time'.
1328 1326
1329 1327 The following is copied verbatim from the profile documentation
1330 1328 referenced below:
1331 1329
1332 1330 When more than one key is provided, additional keys are used as
1333 1331 secondary criteria when the there is equality in all keys selected
1334 1332 before them.
1335 1333
1336 1334 Abbreviations can be used for any key names, as long as the
1337 1335 abbreviation is unambiguous. The following are the keys currently
1338 1336 defined:
1339 1337
1340 1338 Valid Arg Meaning
1341 1339 "calls" call count
1342 1340 "cumulative" cumulative time
1343 1341 "file" file name
1344 1342 "module" file name
1345 1343 "pcalls" primitive call count
1346 1344 "line" line number
1347 1345 "name" function name
1348 1346 "nfl" name/file/line
1349 1347 "stdname" standard name
1350 1348 "time" internal time
1351 1349
1352 1350 Note that all sorts on statistics are in descending order (placing
1353 1351 most time consuming items first), where as name, file, and line number
1354 1352 searches are in ascending order (i.e., alphabetical). The subtle
1355 1353 distinction between "nfl" and "stdname" is that the standard name is a
1356 1354 sort of the name as printed, which means that the embedded line
1357 1355 numbers get compared in an odd way. For example, lines 3, 20, and 40
1358 1356 would (if the file names were the same) appear in the string order
1359 1357 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1360 1358 line numbers. In fact, sort_stats("nfl") is the same as
1361 1359 sort_stats("name", "file", "line").
1362 1360
1363 1361 -T <filename>: save profile results as shown on screen to a text
1364 1362 file. The profile is still shown on screen.
1365 1363
1366 1364 -D <filename>: save (via dump_stats) profile statistics to given
1367 1365 filename. This data is in a format understod by the pstats module, and
1368 1366 is generated by a call to the dump_stats() method of profile
1369 1367 objects. The profile is still shown on screen.
1370 1368
1371 1369 If you want to run complete programs under the profiler's control, use
1372 1370 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1373 1371 contains profiler specific options as described here.
1374 1372
1375 1373 You can read the complete documentation for the profile module with::
1376 1374
1377 1375 In [1]: import profile; profile.help()
1378 1376 """
1379 1377
1380 1378 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1381 1379 # protect user quote marks
1382 1380 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1383 1381
1384 1382 if user_mode: # regular user call
1385 1383 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1386 1384 list_all=1)
1387 1385 namespace = self.shell.user_ns
1388 1386 else: # called to run a program by %run -p
1389 1387 try:
1390 1388 filename = get_py_filename(arg_lst[0])
1391 1389 except IOError,msg:
1392 1390 error(msg)
1393 1391 return
1394 1392
1395 1393 arg_str = 'execfile(filename,prog_ns)'
1396 1394 namespace = locals()
1397 1395
1398 1396 opts.merge(opts_def)
1399 1397
1400 1398 prof = profile.Profile()
1401 1399 try:
1402 1400 prof = prof.runctx(arg_str,namespace,namespace)
1403 1401 sys_exit = ''
1404 1402 except SystemExit:
1405 1403 sys_exit = """*** SystemExit exception caught in code being profiled."""
1406 1404
1407 1405 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1408 1406
1409 1407 lims = opts.l
1410 1408 if lims:
1411 1409 lims = [] # rebuild lims with ints/floats/strings
1412 1410 for lim in opts.l:
1413 1411 try:
1414 1412 lims.append(int(lim))
1415 1413 except ValueError:
1416 1414 try:
1417 1415 lims.append(float(lim))
1418 1416 except ValueError:
1419 1417 lims.append(lim)
1420 1418
1421 1419 # Trap output.
1422 1420 stdout_trap = StringIO()
1423 1421
1424 1422 if hasattr(stats,'stream'):
1425 1423 # In newer versions of python, the stats object has a 'stream'
1426 1424 # attribute to write into.
1427 1425 stats.stream = stdout_trap
1428 1426 stats.print_stats(*lims)
1429 1427 else:
1430 1428 # For older versions, we manually redirect stdout during printing
1431 1429 sys_stdout = sys.stdout
1432 1430 try:
1433 1431 sys.stdout = stdout_trap
1434 1432 stats.print_stats(*lims)
1435 1433 finally:
1436 1434 sys.stdout = sys_stdout
1437 1435
1438 1436 output = stdout_trap.getvalue()
1439 1437 output = output.rstrip()
1440 1438
1441 1439 page.page(output)
1442 1440 print sys_exit,
1443 1441
1444 1442 dump_file = opts.D[0]
1445 1443 text_file = opts.T[0]
1446 1444 if dump_file:
1447 1445 prof.dump_stats(dump_file)
1448 1446 print '\n*** Profile stats marshalled to file',\
1449 1447 `dump_file`+'.',sys_exit
1450 1448 if text_file:
1451 1449 pfile = file(text_file,'w')
1452 1450 pfile.write(output)
1453 1451 pfile.close()
1454 1452 print '\n*** Profile printout saved to text file',\
1455 1453 `text_file`+'.',sys_exit
1456 1454
1457 1455 if opts.has_key('r'):
1458 1456 return stats
1459 1457 else:
1460 1458 return None
1461 1459
1462 1460 @skip_doctest
1463 1461 def magic_run(self, parameter_s ='',runner=None,
1464 1462 file_finder=get_py_filename):
1465 1463 """Run the named file inside IPython as a program.
1466 1464
1467 1465 Usage:\\
1468 1466 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1469 1467
1470 1468 Parameters after the filename are passed as command-line arguments to
1471 1469 the program (put in sys.argv). Then, control returns to IPython's
1472 1470 prompt.
1473 1471
1474 1472 This is similar to running at a system prompt:\\
1475 1473 $ python file args\\
1476 1474 but with the advantage of giving you IPython's tracebacks, and of
1477 1475 loading all variables into your interactive namespace for further use
1478 1476 (unless -p is used, see below).
1479 1477
1480 1478 The file is executed in a namespace initially consisting only of
1481 1479 __name__=='__main__' and sys.argv constructed as indicated. It thus
1482 1480 sees its environment as if it were being run as a stand-alone program
1483 1481 (except for sharing global objects such as previously imported
1484 1482 modules). But after execution, the IPython interactive namespace gets
1485 1483 updated with all variables defined in the program (except for __name__
1486 1484 and sys.argv). This allows for very convenient loading of code for
1487 1485 interactive work, while giving each program a 'clean sheet' to run in.
1488 1486
1489 1487 Options:
1490 1488
1491 1489 -n: __name__ is NOT set to '__main__', but to the running file's name
1492 1490 without extension (as python does under import). This allows running
1493 1491 scripts and reloading the definitions in them without calling code
1494 1492 protected by an ' if __name__ == "__main__" ' clause.
1495 1493
1496 1494 -i: run the file in IPython's namespace instead of an empty one. This
1497 1495 is useful if you are experimenting with code written in a text editor
1498 1496 which depends on variables defined interactively.
1499 1497
1500 1498 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1501 1499 being run. This is particularly useful if IPython is being used to
1502 1500 run unittests, which always exit with a sys.exit() call. In such
1503 1501 cases you are interested in the output of the test results, not in
1504 1502 seeing a traceback of the unittest module.
1505 1503
1506 1504 -t: print timing information at the end of the run. IPython will give
1507 1505 you an estimated CPU time consumption for your script, which under
1508 1506 Unix uses the resource module to avoid the wraparound problems of
1509 1507 time.clock(). Under Unix, an estimate of time spent on system tasks
1510 1508 is also given (for Windows platforms this is reported as 0.0).
1511 1509
1512 1510 If -t is given, an additional -N<N> option can be given, where <N>
1513 1511 must be an integer indicating how many times you want the script to
1514 1512 run. The final timing report will include total and per run results.
1515 1513
1516 1514 For example (testing the script uniq_stable.py):
1517 1515
1518 1516 In [1]: run -t uniq_stable
1519 1517
1520 1518 IPython CPU timings (estimated):\\
1521 1519 User : 0.19597 s.\\
1522 1520 System: 0.0 s.\\
1523 1521
1524 1522 In [2]: run -t -N5 uniq_stable
1525 1523
1526 1524 IPython CPU timings (estimated):\\
1527 1525 Total runs performed: 5\\
1528 1526 Times : Total Per run\\
1529 1527 User : 0.910862 s, 0.1821724 s.\\
1530 1528 System: 0.0 s, 0.0 s.
1531 1529
1532 1530 -d: run your program under the control of pdb, the Python debugger.
1533 1531 This allows you to execute your program step by step, watch variables,
1534 1532 etc. Internally, what IPython does is similar to calling:
1535 1533
1536 1534 pdb.run('execfile("YOURFILENAME")')
1537 1535
1538 1536 with a breakpoint set on line 1 of your file. You can change the line
1539 1537 number for this automatic breakpoint to be <N> by using the -bN option
1540 1538 (where N must be an integer). For example:
1541 1539
1542 1540 %run -d -b40 myscript
1543 1541
1544 1542 will set the first breakpoint at line 40 in myscript.py. Note that
1545 1543 the first breakpoint must be set on a line which actually does
1546 1544 something (not a comment or docstring) for it to stop execution.
1547 1545
1548 1546 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1549 1547 first enter 'c' (without qoutes) to start execution up to the first
1550 1548 breakpoint.
1551 1549
1552 1550 Entering 'help' gives information about the use of the debugger. You
1553 1551 can easily see pdb's full documentation with "import pdb;pdb.help()"
1554 1552 at a prompt.
1555 1553
1556 1554 -p: run program under the control of the Python profiler module (which
1557 1555 prints a detailed report of execution times, function calls, etc).
1558 1556
1559 1557 You can pass other options after -p which affect the behavior of the
1560 1558 profiler itself. See the docs for %prun for details.
1561 1559
1562 1560 In this mode, the program's variables do NOT propagate back to the
1563 1561 IPython interactive namespace (because they remain in the namespace
1564 1562 where the profiler executes them).
1565 1563
1566 1564 Internally this triggers a call to %prun, see its documentation for
1567 1565 details on the options available specifically for profiling.
1568 1566
1569 1567 There is one special usage for which the text above doesn't apply:
1570 1568 if the filename ends with .ipy, the file is run as ipython script,
1571 1569 just as if the commands were written on IPython prompt.
1572 1570 """
1573 1571
1574 1572 # get arguments and set sys.argv for program to be run.
1575 1573 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1576 1574 mode='list',list_all=1)
1577 1575
1578 1576 try:
1579 1577 filename = file_finder(arg_lst[0])
1580 1578 except IndexError:
1581 1579 warn('you must provide at least a filename.')
1582 1580 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1583 1581 return
1584 1582 except IOError,msg:
1585 1583 error(msg)
1586 1584 return
1587 1585
1588 1586 if filename.lower().endswith('.ipy'):
1589 1587 self.shell.safe_execfile_ipy(filename)
1590 1588 return
1591 1589
1592 1590 # Control the response to exit() calls made by the script being run
1593 1591 exit_ignore = opts.has_key('e')
1594 1592
1595 1593 # Make sure that the running script gets a proper sys.argv as if it
1596 1594 # were run from a system shell.
1597 1595 save_argv = sys.argv # save it for later restoring
1598 1596 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1599 1597
1600 1598 if opts.has_key('i'):
1601 1599 # Run in user's interactive namespace
1602 1600 prog_ns = self.shell.user_ns
1603 1601 __name__save = self.shell.user_ns['__name__']
1604 1602 prog_ns['__name__'] = '__main__'
1605 1603 main_mod = self.shell.new_main_mod(prog_ns)
1606 1604 else:
1607 1605 # Run in a fresh, empty namespace
1608 1606 if opts.has_key('n'):
1609 1607 name = os.path.splitext(os.path.basename(filename))[0]
1610 1608 else:
1611 1609 name = '__main__'
1612 1610
1613 1611 main_mod = self.shell.new_main_mod()
1614 1612 prog_ns = main_mod.__dict__
1615 1613 prog_ns['__name__'] = name
1616 1614
1617 1615 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1618 1616 # set the __file__ global in the script's namespace
1619 1617 prog_ns['__file__'] = filename
1620 1618
1621 1619 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1622 1620 # that, if we overwrite __main__, we replace it at the end
1623 1621 main_mod_name = prog_ns['__name__']
1624 1622
1625 1623 if main_mod_name == '__main__':
1626 1624 restore_main = sys.modules['__main__']
1627 1625 else:
1628 1626 restore_main = False
1629 1627
1630 1628 # This needs to be undone at the end to prevent holding references to
1631 1629 # every single object ever created.
1632 1630 sys.modules[main_mod_name] = main_mod
1633 1631
1634 1632 try:
1635 1633 stats = None
1636 1634 with self.readline_no_record:
1637 1635 if opts.has_key('p'):
1638 1636 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1639 1637 else:
1640 1638 if opts.has_key('d'):
1641 1639 deb = debugger.Pdb(self.shell.colors)
1642 1640 # reset Breakpoint state, which is moronically kept
1643 1641 # in a class
1644 1642 bdb.Breakpoint.next = 1
1645 1643 bdb.Breakpoint.bplist = {}
1646 1644 bdb.Breakpoint.bpbynumber = [None]
1647 1645 # Set an initial breakpoint to stop execution
1648 1646 maxtries = 10
1649 1647 bp = int(opts.get('b',[1])[0])
1650 1648 checkline = deb.checkline(filename,bp)
1651 1649 if not checkline:
1652 1650 for bp in range(bp+1,bp+maxtries+1):
1653 1651 if deb.checkline(filename,bp):
1654 1652 break
1655 1653 else:
1656 1654 msg = ("\nI failed to find a valid line to set "
1657 1655 "a breakpoint\n"
1658 1656 "after trying up to line: %s.\n"
1659 1657 "Please set a valid breakpoint manually "
1660 1658 "with the -b option." % bp)
1661 1659 error(msg)
1662 1660 return
1663 1661 # if we find a good linenumber, set the breakpoint
1664 1662 deb.do_break('%s:%s' % (filename,bp))
1665 1663 # Start file run
1666 1664 print "NOTE: Enter 'c' at the",
1667 1665 print "%s prompt to start your script." % deb.prompt
1668 1666 try:
1669 1667 deb.run('execfile("%s")' % filename,prog_ns)
1670 1668
1671 1669 except:
1672 1670 etype, value, tb = sys.exc_info()
1673 1671 # Skip three frames in the traceback: the %run one,
1674 1672 # one inside bdb.py, and the command-line typed by the
1675 1673 # user (run by exec in pdb itself).
1676 1674 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1677 1675 else:
1678 1676 if runner is None:
1679 1677 runner = self.shell.safe_execfile
1680 1678 if opts.has_key('t'):
1681 1679 # timed execution
1682 1680 try:
1683 1681 nruns = int(opts['N'][0])
1684 1682 if nruns < 1:
1685 1683 error('Number of runs must be >=1')
1686 1684 return
1687 1685 except (KeyError):
1688 1686 nruns = 1
1689 1687 if nruns == 1:
1690 1688 t0 = clock2()
1691 1689 runner(filename,prog_ns,prog_ns,
1692 1690 exit_ignore=exit_ignore)
1693 1691 t1 = clock2()
1694 1692 t_usr = t1[0]-t0[0]
1695 1693 t_sys = t1[1]-t0[1]
1696 1694 print "\nIPython CPU timings (estimated):"
1697 1695 print " User : %10s s." % t_usr
1698 1696 print " System: %10s s." % t_sys
1699 1697 else:
1700 1698 runs = range(nruns)
1701 1699 t0 = clock2()
1702 1700 for nr in runs:
1703 1701 runner(filename,prog_ns,prog_ns,
1704 1702 exit_ignore=exit_ignore)
1705 1703 t1 = clock2()
1706 1704 t_usr = t1[0]-t0[0]
1707 1705 t_sys = t1[1]-t0[1]
1708 1706 print "\nIPython CPU timings (estimated):"
1709 1707 print "Total runs performed:",nruns
1710 1708 print " Times : %10s %10s" % ('Total','Per run')
1711 1709 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1712 1710 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1713 1711
1714 1712 else:
1715 1713 # regular execution
1716 1714 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1717 1715
1718 1716 if opts.has_key('i'):
1719 1717 self.shell.user_ns['__name__'] = __name__save
1720 1718 else:
1721 1719 # The shell MUST hold a reference to prog_ns so after %run
1722 1720 # exits, the python deletion mechanism doesn't zero it out
1723 1721 # (leaving dangling references).
1724 1722 self.shell.cache_main_mod(prog_ns,filename)
1725 1723 # update IPython interactive namespace
1726 1724
1727 1725 # Some forms of read errors on the file may mean the
1728 1726 # __name__ key was never set; using pop we don't have to
1729 1727 # worry about a possible KeyError.
1730 1728 prog_ns.pop('__name__', None)
1731 1729
1732 1730 self.shell.user_ns.update(prog_ns)
1733 1731 finally:
1734 1732 # It's a bit of a mystery why, but __builtins__ can change from
1735 1733 # being a module to becoming a dict missing some key data after
1736 1734 # %run. As best I can see, this is NOT something IPython is doing
1737 1735 # at all, and similar problems have been reported before:
1738 1736 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1739 1737 # Since this seems to be done by the interpreter itself, the best
1740 1738 # we can do is to at least restore __builtins__ for the user on
1741 1739 # exit.
1742 1740 self.shell.user_ns['__builtins__'] = __builtin__
1743 1741
1744 1742 # Ensure key global structures are restored
1745 1743 sys.argv = save_argv
1746 1744 if restore_main:
1747 1745 sys.modules['__main__'] = restore_main
1748 1746 else:
1749 1747 # Remove from sys.modules the reference to main_mod we'd
1750 1748 # added. Otherwise it will trap references to objects
1751 1749 # contained therein.
1752 1750 del sys.modules[main_mod_name]
1753 1751
1754 1752 return stats
1755 1753
1756 1754 @skip_doctest
1757 1755 def magic_timeit(self, parameter_s =''):
1758 1756 """Time execution of a Python statement or expression
1759 1757
1760 1758 Usage:\\
1761 1759 %timeit [-n<N> -r<R> [-t|-c]] statement
1762 1760
1763 1761 Time execution of a Python statement or expression using the timeit
1764 1762 module.
1765 1763
1766 1764 Options:
1767 1765 -n<N>: execute the given statement <N> times in a loop. If this value
1768 1766 is not given, a fitting value is chosen.
1769 1767
1770 1768 -r<R>: repeat the loop iteration <R> times and take the best result.
1771 1769 Default: 3
1772 1770
1773 1771 -t: use time.time to measure the time, which is the default on Unix.
1774 1772 This function measures wall time.
1775 1773
1776 1774 -c: use time.clock to measure the time, which is the default on
1777 1775 Windows and measures wall time. On Unix, resource.getrusage is used
1778 1776 instead and returns the CPU user time.
1779 1777
1780 1778 -p<P>: use a precision of <P> digits to display the timing result.
1781 1779 Default: 3
1782 1780
1783 1781
1784 1782 Examples:
1785 1783
1786 1784 In [1]: %timeit pass
1787 1785 10000000 loops, best of 3: 53.3 ns per loop
1788 1786
1789 1787 In [2]: u = None
1790 1788
1791 1789 In [3]: %timeit u is None
1792 1790 10000000 loops, best of 3: 184 ns per loop
1793 1791
1794 1792 In [4]: %timeit -r 4 u == None
1795 1793 1000000 loops, best of 4: 242 ns per loop
1796 1794
1797 1795 In [5]: import time
1798 1796
1799 1797 In [6]: %timeit -n1 time.sleep(2)
1800 1798 1 loops, best of 3: 2 s per loop
1801 1799
1802 1800
1803 1801 The times reported by %timeit will be slightly higher than those
1804 1802 reported by the timeit.py script when variables are accessed. This is
1805 1803 due to the fact that %timeit executes the statement in the namespace
1806 1804 of the shell, compared with timeit.py, which uses a single setup
1807 1805 statement to import function or create variables. Generally, the bias
1808 1806 does not matter as long as results from timeit.py are not mixed with
1809 1807 those from %timeit."""
1810 1808
1811 1809 import timeit
1812 1810 import math
1813 1811
1814 1812 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1815 1813 # certain terminals. Until we figure out a robust way of
1816 1814 # auto-detecting if the terminal can deal with it, use plain 'us' for
1817 1815 # microseconds. I am really NOT happy about disabling the proper
1818 1816 # 'micro' prefix, but crashing is worse... If anyone knows what the
1819 1817 # right solution for this is, I'm all ears...
1820 1818 #
1821 1819 # Note: using
1822 1820 #
1823 1821 # s = u'\xb5'
1824 1822 # s.encode(sys.getdefaultencoding())
1825 1823 #
1826 1824 # is not sufficient, as I've seen terminals where that fails but
1827 1825 # print s
1828 1826 #
1829 1827 # succeeds
1830 1828 #
1831 1829 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1832 1830
1833 1831 #units = [u"s", u"ms",u'\xb5',"ns"]
1834 1832 units = [u"s", u"ms",u'us',"ns"]
1835 1833
1836 1834 scaling = [1, 1e3, 1e6, 1e9]
1837 1835
1838 1836 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1839 1837 posix=False)
1840 1838 if stmt == "":
1841 1839 return
1842 1840 timefunc = timeit.default_timer
1843 1841 number = int(getattr(opts, "n", 0))
1844 1842 repeat = int(getattr(opts, "r", timeit.default_repeat))
1845 1843 precision = int(getattr(opts, "p", 3))
1846 1844 if hasattr(opts, "t"):
1847 1845 timefunc = time.time
1848 1846 if hasattr(opts, "c"):
1849 1847 timefunc = clock
1850 1848
1851 1849 timer = timeit.Timer(timer=timefunc)
1852 1850 # this code has tight coupling to the inner workings of timeit.Timer,
1853 1851 # but is there a better way to achieve that the code stmt has access
1854 1852 # to the shell namespace?
1855 1853
1856 1854 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1857 1855 'setup': "pass"}
1858 1856 # Track compilation time so it can be reported if too long
1859 1857 # Minimum time above which compilation time will be reported
1860 1858 tc_min = 0.1
1861 1859
1862 1860 t0 = clock()
1863 1861 code = compile(src, "<magic-timeit>", "exec")
1864 1862 tc = clock()-t0
1865 1863
1866 1864 ns = {}
1867 1865 exec code in self.shell.user_ns, ns
1868 1866 timer.inner = ns["inner"]
1869 1867
1870 1868 if number == 0:
1871 1869 # determine number so that 0.2 <= total time < 2.0
1872 1870 number = 1
1873 1871 for i in range(1, 10):
1874 1872 if timer.timeit(number) >= 0.2:
1875 1873 break
1876 1874 number *= 10
1877 1875
1878 1876 best = min(timer.repeat(repeat, number)) / number
1879 1877
1880 1878 if best > 0.0 and best < 1000.0:
1881 1879 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1882 1880 elif best >= 1000.0:
1883 1881 order = 0
1884 1882 else:
1885 1883 order = 3
1886 1884 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1887 1885 precision,
1888 1886 best * scaling[order],
1889 1887 units[order])
1890 1888 if tc > tc_min:
1891 1889 print "Compiler time: %.2f s" % tc
1892 1890
1893 1891 @skip_doctest
1894 1892 @needs_local_scope
1895 1893 def magic_time(self,parameter_s = ''):
1896 1894 """Time execution of a Python statement or expression.
1897 1895
1898 1896 The CPU and wall clock times are printed, and the value of the
1899 1897 expression (if any) is returned. Note that under Win32, system time
1900 1898 is always reported as 0, since it can not be measured.
1901 1899
1902 1900 This function provides very basic timing functionality. In Python
1903 1901 2.3, the timeit module offers more control and sophistication, so this
1904 1902 could be rewritten to use it (patches welcome).
1905 1903
1906 1904 Some examples:
1907 1905
1908 1906 In [1]: time 2**128
1909 1907 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1910 1908 Wall time: 0.00
1911 1909 Out[1]: 340282366920938463463374607431768211456L
1912 1910
1913 1911 In [2]: n = 1000000
1914 1912
1915 1913 In [3]: time sum(range(n))
1916 1914 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1917 1915 Wall time: 1.37
1918 1916 Out[3]: 499999500000L
1919 1917
1920 1918 In [4]: time print 'hello world'
1921 1919 hello world
1922 1920 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1923 1921 Wall time: 0.00
1924 1922
1925 1923 Note that the time needed by Python to compile the given expression
1926 1924 will be reported if it is more than 0.1s. In this example, the
1927 1925 actual exponentiation is done by Python at compilation time, so while
1928 1926 the expression can take a noticeable amount of time to compute, that
1929 1927 time is purely due to the compilation:
1930 1928
1931 1929 In [5]: time 3**9999;
1932 1930 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1933 1931 Wall time: 0.00 s
1934 1932
1935 1933 In [6]: time 3**999999;
1936 1934 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1937 1935 Wall time: 0.00 s
1938 1936 Compiler : 0.78 s
1939 1937 """
1940 1938
1941 1939 # fail immediately if the given expression can't be compiled
1942 1940
1943 1941 expr = self.shell.prefilter(parameter_s,False)
1944 1942
1945 1943 # Minimum time above which compilation time will be reported
1946 1944 tc_min = 0.1
1947 1945
1948 1946 try:
1949 1947 mode = 'eval'
1950 1948 t0 = clock()
1951 1949 code = compile(expr,'<timed eval>',mode)
1952 1950 tc = clock()-t0
1953 1951 except SyntaxError:
1954 1952 mode = 'exec'
1955 1953 t0 = clock()
1956 1954 code = compile(expr,'<timed exec>',mode)
1957 1955 tc = clock()-t0
1958 1956 # skew measurement as little as possible
1959 1957 glob = self.shell.user_ns
1960 1958 locs = self._magic_locals
1961 1959 clk = clock2
1962 1960 wtime = time.time
1963 1961 # time execution
1964 1962 wall_st = wtime()
1965 1963 if mode=='eval':
1966 1964 st = clk()
1967 1965 out = eval(code, glob, locs)
1968 1966 end = clk()
1969 1967 else:
1970 1968 st = clk()
1971 1969 exec code in glob, locs
1972 1970 end = clk()
1973 1971 out = None
1974 1972 wall_end = wtime()
1975 1973 # Compute actual times and report
1976 1974 wall_time = wall_end-wall_st
1977 1975 cpu_user = end[0]-st[0]
1978 1976 cpu_sys = end[1]-st[1]
1979 1977 cpu_tot = cpu_user+cpu_sys
1980 1978 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1981 1979 (cpu_user,cpu_sys,cpu_tot)
1982 1980 print "Wall time: %.2f s" % wall_time
1983 1981 if tc > tc_min:
1984 1982 print "Compiler : %.2f s" % tc
1985 1983 return out
1986 1984
1987 1985 @skip_doctest
1988 1986 def magic_macro(self,parameter_s = ''):
1989 1987 """Define a macro for future re-execution. It accepts ranges of history,
1990 1988 filenames or string objects.
1991 1989
1992 1990 Usage:\\
1993 1991 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1994 1992
1995 1993 Options:
1996 1994
1997 1995 -r: use 'raw' input. By default, the 'processed' history is used,
1998 1996 so that magics are loaded in their transformed version to valid
1999 1997 Python. If this option is given, the raw input as typed as the
2000 1998 command line is used instead.
2001 1999
2002 2000 This will define a global variable called `name` which is a string
2003 2001 made of joining the slices and lines you specify (n1,n2,... numbers
2004 2002 above) from your input history into a single string. This variable
2005 2003 acts like an automatic function which re-executes those lines as if
2006 2004 you had typed them. You just type 'name' at the prompt and the code
2007 2005 executes.
2008 2006
2009 2007 The syntax for indicating input ranges is described in %history.
2010 2008
2011 2009 Note: as a 'hidden' feature, you can also use traditional python slice
2012 2010 notation, where N:M means numbers N through M-1.
2013 2011
2014 2012 For example, if your history contains (%hist prints it):
2015 2013
2016 2014 44: x=1
2017 2015 45: y=3
2018 2016 46: z=x+y
2019 2017 47: print x
2020 2018 48: a=5
2021 2019 49: print 'x',x,'y',y
2022 2020
2023 2021 you can create a macro with lines 44 through 47 (included) and line 49
2024 2022 called my_macro with:
2025 2023
2026 2024 In [55]: %macro my_macro 44-47 49
2027 2025
2028 2026 Now, typing `my_macro` (without quotes) will re-execute all this code
2029 2027 in one pass.
2030 2028
2031 2029 You don't need to give the line-numbers in order, and any given line
2032 2030 number can appear multiple times. You can assemble macros with any
2033 2031 lines from your input history in any order.
2034 2032
2035 2033 The macro is a simple object which holds its value in an attribute,
2036 2034 but IPython's display system checks for macros and executes them as
2037 2035 code instead of printing them when you type their name.
2038 2036
2039 2037 You can view a macro's contents by explicitly printing it with:
2040 2038
2041 2039 'print macro_name'.
2042 2040
2043 2041 """
2044 2042 opts,args = self.parse_options(parameter_s,'r',mode='list')
2045 2043 if not args: # List existing macros
2046 2044 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
2047 2045 isinstance(v, Macro))
2048 2046 if len(args) == 1:
2049 2047 raise UsageError(
2050 2048 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2051 2049 name, codefrom = args[0], " ".join(args[1:])
2052 2050
2053 2051 #print 'rng',ranges # dbg
2054 2052 try:
2055 2053 lines = self.shell.find_user_code(codefrom, 'r' in opts)
2056 2054 except (ValueError, TypeError) as e:
2057 2055 print e.args[0]
2058 2056 return
2059 2057 macro = Macro(lines)
2060 2058 self.shell.define_macro(name, macro)
2061 2059 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2062 2060 print '=== Macro contents: ==='
2063 2061 print macro,
2064 2062
2065 2063 def magic_save(self,parameter_s = ''):
2066 2064 """Save a set of lines or a macro to a given filename.
2067 2065
2068 2066 Usage:\\
2069 2067 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2070 2068
2071 2069 Options:
2072 2070
2073 2071 -r: use 'raw' input. By default, the 'processed' history is used,
2074 2072 so that magics are loaded in their transformed version to valid
2075 2073 Python. If this option is given, the raw input as typed as the
2076 2074 command line is used instead.
2077 2075
2078 2076 This function uses the same syntax as %history for input ranges,
2079 2077 then saves the lines to the filename you specify.
2080 2078
2081 2079 It adds a '.py' extension to the file if you don't do so yourself, and
2082 2080 it asks for confirmation before overwriting existing files."""
2083 2081
2084 2082 opts,args = self.parse_options(parameter_s,'r',mode='list')
2085 2083 fname, codefrom = args[0], " ".join(args[1:])
2086 2084 if not fname.endswith('.py'):
2087 2085 fname += '.py'
2088 2086 if os.path.isfile(fname):
2089 2087 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2090 2088 if ans.lower() not in ['y','yes']:
2091 2089 print 'Operation cancelled.'
2092 2090 return
2093 2091 try:
2094 2092 cmds = self.shell.find_user_code(codefrom, 'r' in opts)
2095 2093 except (TypeError, ValueError) as e:
2096 2094 print e.args[0]
2097 2095 return
2098 2096 if isinstance(cmds, unicode):
2099 2097 cmds = cmds.encode("utf-8")
2100 2098 with open(fname,'w') as f:
2101 2099 f.write("# coding: utf-8\n")
2102 2100 f.write(cmds)
2103 2101 print 'The following commands were written to file `%s`:' % fname
2104 2102 print cmds
2105 2103
2106 2104 def magic_pastebin(self, parameter_s = ''):
2107 2105 """Upload code to the 'Lodge it' paste bin, returning the URL."""
2108 2106 try:
2109 2107 code = self.shell.find_user_code(parameter_s)
2110 2108 except (ValueError, TypeError) as e:
2111 2109 print e.args[0]
2112 2110 return
2113 2111 pbserver = ServerProxy('http://paste.pocoo.org/xmlrpc/')
2114 2112 id = pbserver.pastes.newPaste("python", code)
2115 2113 return "http://paste.pocoo.org/show/" + id
2116 2114
2117 2115 def magic_loadpy(self, arg_s):
2118 2116 """Load a .py python script into the GUI console.
2119 2117
2120 2118 This magic command can either take a local filename or a url::
2121 2119
2122 2120 %loadpy myscript.py
2123 2121 %loadpy http://www.example.com/myscript.py
2124 2122 """
2125 2123 if not arg_s.endswith('.py'):
2126 2124 raise ValueError('%%load only works with .py files: %s' % arg_s)
2127 2125 if arg_s.startswith('http'):
2128 2126 import urllib2
2129 2127 response = urllib2.urlopen(arg_s)
2130 2128 content = response.read()
2131 2129 else:
2132 2130 content = open(arg_s).read()
2133 2131 self.set_next_input(content)
2134 2132
2135 2133 def _find_edit_target(self, args, opts, last_call):
2136 2134 """Utility method used by magic_edit to find what to edit."""
2137 2135
2138 2136 def make_filename(arg):
2139 2137 "Make a filename from the given args"
2140 2138 try:
2141 2139 filename = get_py_filename(arg)
2142 2140 except IOError:
2143 2141 # If it ends with .py but doesn't already exist, assume we want
2144 2142 # a new file.
2145 2143 if args.endswith('.py'):
2146 2144 filename = arg
2147 2145 else:
2148 2146 filename = None
2149 2147 return filename
2150 2148
2151 2149 # Set a few locals from the options for convenience:
2152 2150 opts_prev = 'p' in opts
2153 2151 opts_raw = 'r' in opts
2154 2152
2155 2153 # custom exceptions
2156 2154 class DataIsObject(Exception): pass
2157 2155
2158 2156 # Default line number value
2159 2157 lineno = opts.get('n',None)
2160 2158
2161 2159 if opts_prev:
2162 2160 args = '_%s' % last_call[0]
2163 2161 if not self.shell.user_ns.has_key(args):
2164 2162 args = last_call[1]
2165 2163
2166 2164 # use last_call to remember the state of the previous call, but don't
2167 2165 # let it be clobbered by successive '-p' calls.
2168 2166 try:
2169 2167 last_call[0] = self.shell.displayhook.prompt_count
2170 2168 if not opts_prev:
2171 2169 last_call[1] = parameter_s
2172 2170 except:
2173 2171 pass
2174 2172
2175 2173 # by default this is done with temp files, except when the given
2176 2174 # arg is a filename
2177 2175 use_temp = True
2178 2176
2179 2177 data = ''
2180 2178
2181 2179 # First, see if the arguments should be a filename.
2182 2180 filename = make_filename(args)
2183 2181 if filename:
2184 2182 use_temp = False
2185 2183 elif args:
2186 2184 # Mode where user specifies ranges of lines, like in %macro.
2187 2185 data = self.extract_input_lines(args, opts_raw)
2188 2186 if not data:
2189 2187 try:
2190 2188 # Load the parameter given as a variable. If not a string,
2191 2189 # process it as an object instead (below)
2192 2190
2193 2191 #print '*** args',args,'type',type(args) # dbg
2194 2192 data = eval(args, self.shell.user_ns)
2195 2193 if not isinstance(data, basestring):
2196 2194 raise DataIsObject
2197 2195
2198 2196 except (NameError,SyntaxError):
2199 2197 # given argument is not a variable, try as a filename
2200 2198 filename = make_filename(args)
2201 2199 if filename is None:
2202 2200 warn("Argument given (%s) can't be found as a variable "
2203 2201 "or as a filename." % args)
2204 2202 return
2205 2203 use_temp = False
2206 2204
2207 2205 except DataIsObject:
2208 2206 # macros have a special edit function
2209 2207 if isinstance(data, Macro):
2210 2208 raise MacroToEdit(data)
2211 2209
2212 2210 # For objects, try to edit the file where they are defined
2213 2211 try:
2214 2212 filename = inspect.getabsfile(data)
2215 2213 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2216 2214 # class created by %edit? Try to find source
2217 2215 # by looking for method definitions instead, the
2218 2216 # __module__ in those classes is FakeModule.
2219 2217 attrs = [getattr(data, aname) for aname in dir(data)]
2220 2218 for attr in attrs:
2221 2219 if not inspect.ismethod(attr):
2222 2220 continue
2223 2221 filename = inspect.getabsfile(attr)
2224 2222 if filename and 'fakemodule' not in filename.lower():
2225 2223 # change the attribute to be the edit target instead
2226 2224 data = attr
2227 2225 break
2228 2226
2229 2227 datafile = 1
2230 2228 except TypeError:
2231 2229 filename = make_filename(args)
2232 2230 datafile = 1
2233 2231 warn('Could not find file where `%s` is defined.\n'
2234 2232 'Opening a file named `%s`' % (args,filename))
2235 2233 # Now, make sure we can actually read the source (if it was in
2236 2234 # a temp file it's gone by now).
2237 2235 if datafile:
2238 2236 try:
2239 2237 if lineno is None:
2240 2238 lineno = inspect.getsourcelines(data)[1]
2241 2239 except IOError:
2242 2240 filename = make_filename(args)
2243 2241 if filename is None:
2244 2242 warn('The file `%s` where `%s` was defined cannot '
2245 2243 'be read.' % (filename,data))
2246 2244 return
2247 2245 use_temp = False
2248 2246
2249 2247 if use_temp:
2250 2248 filename = self.shell.mktempfile(data)
2251 2249 print 'IPython will make a temporary file named:',filename
2252 2250
2253 2251 return filename, lineno, use_temp
2254 2252
2255 2253 def _edit_macro(self,mname,macro):
2256 2254 """open an editor with the macro data in a file"""
2257 2255 filename = self.shell.mktempfile(macro.value)
2258 2256 self.shell.hooks.editor(filename)
2259 2257
2260 2258 # and make a new macro object, to replace the old one
2261 2259 mfile = open(filename)
2262 2260 mvalue = mfile.read()
2263 2261 mfile.close()
2264 2262 self.shell.user_ns[mname] = Macro(mvalue)
2265 2263
2266 2264 def magic_ed(self,parameter_s=''):
2267 2265 """Alias to %edit."""
2268 2266 return self.magic_edit(parameter_s)
2269 2267
2270 2268 @skip_doctest
2271 2269 def magic_edit(self,parameter_s='',last_call=['','']):
2272 2270 """Bring up an editor and execute the resulting code.
2273 2271
2274 2272 Usage:
2275 2273 %edit [options] [args]
2276 2274
2277 2275 %edit runs IPython's editor hook. The default version of this hook is
2278 2276 set to call the __IPYTHON__.rc.editor command. This is read from your
2279 2277 environment variable $EDITOR. If this isn't found, it will default to
2280 2278 vi under Linux/Unix and to notepad under Windows. See the end of this
2281 2279 docstring for how to change the editor hook.
2282 2280
2283 2281 You can also set the value of this editor via the command line option
2284 2282 '-editor' or in your ipythonrc file. This is useful if you wish to use
2285 2283 specifically for IPython an editor different from your typical default
2286 2284 (and for Windows users who typically don't set environment variables).
2287 2285
2288 2286 This command allows you to conveniently edit multi-line code right in
2289 2287 your IPython session.
2290 2288
2291 2289 If called without arguments, %edit opens up an empty editor with a
2292 2290 temporary file and will execute the contents of this file when you
2293 2291 close it (don't forget to save it!).
2294 2292
2295 2293
2296 2294 Options:
2297 2295
2298 2296 -n <number>: open the editor at a specified line number. By default,
2299 2297 the IPython editor hook uses the unix syntax 'editor +N filename', but
2300 2298 you can configure this by providing your own modified hook if your
2301 2299 favorite editor supports line-number specifications with a different
2302 2300 syntax.
2303 2301
2304 2302 -p: this will call the editor with the same data as the previous time
2305 2303 it was used, regardless of how long ago (in your current session) it
2306 2304 was.
2307 2305
2308 2306 -r: use 'raw' input. This option only applies to input taken from the
2309 2307 user's history. By default, the 'processed' history is used, so that
2310 2308 magics are loaded in their transformed version to valid Python. If
2311 2309 this option is given, the raw input as typed as the command line is
2312 2310 used instead. When you exit the editor, it will be executed by
2313 2311 IPython's own processor.
2314 2312
2315 2313 -x: do not execute the edited code immediately upon exit. This is
2316 2314 mainly useful if you are editing programs which need to be called with
2317 2315 command line arguments, which you can then do using %run.
2318 2316
2319 2317
2320 2318 Arguments:
2321 2319
2322 2320 If arguments are given, the following possibilites exist:
2323 2321
2324 2322 - If the argument is a filename, IPython will load that into the
2325 2323 editor. It will execute its contents with execfile() when you exit,
2326 2324 loading any code in the file into your interactive namespace.
2327 2325
2328 2326 - The arguments are ranges of input history, e.g. "7 ~1/4-6".
2329 2327 The syntax is the same as in the %history magic.
2330 2328
2331 2329 - If the argument is a string variable, its contents are loaded
2332 2330 into the editor. You can thus edit any string which contains
2333 2331 python code (including the result of previous edits).
2334 2332
2335 2333 - If the argument is the name of an object (other than a string),
2336 2334 IPython will try to locate the file where it was defined and open the
2337 2335 editor at the point where it is defined. You can use `%edit function`
2338 2336 to load an editor exactly at the point where 'function' is defined,
2339 2337 edit it and have the file be executed automatically.
2340 2338
2341 2339 If the object is a macro (see %macro for details), this opens up your
2342 2340 specified editor with a temporary file containing the macro's data.
2343 2341 Upon exit, the macro is reloaded with the contents of the file.
2344 2342
2345 2343 Note: opening at an exact line is only supported under Unix, and some
2346 2344 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2347 2345 '+NUMBER' parameter necessary for this feature. Good editors like
2348 2346 (X)Emacs, vi, jed, pico and joe all do.
2349 2347
2350 2348 After executing your code, %edit will return as output the code you
2351 2349 typed in the editor (except when it was an existing file). This way
2352 2350 you can reload the code in further invocations of %edit as a variable,
2353 2351 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2354 2352 the output.
2355 2353
2356 2354 Note that %edit is also available through the alias %ed.
2357 2355
2358 2356 This is an example of creating a simple function inside the editor and
2359 2357 then modifying it. First, start up the editor:
2360 2358
2361 2359 In [1]: ed
2362 2360 Editing... done. Executing edited code...
2363 2361 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2364 2362
2365 2363 We can then call the function foo():
2366 2364
2367 2365 In [2]: foo()
2368 2366 foo() was defined in an editing session
2369 2367
2370 2368 Now we edit foo. IPython automatically loads the editor with the
2371 2369 (temporary) file where foo() was previously defined:
2372 2370
2373 2371 In [3]: ed foo
2374 2372 Editing... done. Executing edited code...
2375 2373
2376 2374 And if we call foo() again we get the modified version:
2377 2375
2378 2376 In [4]: foo()
2379 2377 foo() has now been changed!
2380 2378
2381 2379 Here is an example of how to edit a code snippet successive
2382 2380 times. First we call the editor:
2383 2381
2384 2382 In [5]: ed
2385 2383 Editing... done. Executing edited code...
2386 2384 hello
2387 2385 Out[5]: "print 'hello'n"
2388 2386
2389 2387 Now we call it again with the previous output (stored in _):
2390 2388
2391 2389 In [6]: ed _
2392 2390 Editing... done. Executing edited code...
2393 2391 hello world
2394 2392 Out[6]: "print 'hello world'n"
2395 2393
2396 2394 Now we call it with the output #8 (stored in _8, also as Out[8]):
2397 2395
2398 2396 In [7]: ed _8
2399 2397 Editing... done. Executing edited code...
2400 2398 hello again
2401 2399 Out[7]: "print 'hello again'n"
2402 2400
2403 2401
2404 2402 Changing the default editor hook:
2405 2403
2406 2404 If you wish to write your own editor hook, you can put it in a
2407 2405 configuration file which you load at startup time. The default hook
2408 2406 is defined in the IPython.core.hooks module, and you can use that as a
2409 2407 starting example for further modifications. That file also has
2410 2408 general instructions on how to set a new hook for use once you've
2411 2409 defined it."""
2412 2410 opts,args = self.parse_options(parameter_s,'prxn:')
2413 2411
2414 2412 try:
2415 2413 filename, lineno, is_temp = self._find_edit_target(args, opts, last_call)
2416 2414 except MacroToEdit as e:
2417 2415 self._edit_macro(args, e.args[0])
2418 2416 return
2419 2417
2420 2418 # do actual editing here
2421 2419 print 'Editing...',
2422 2420 sys.stdout.flush()
2423 2421 try:
2424 2422 # Quote filenames that may have spaces in them
2425 2423 if ' ' in filename:
2426 2424 filename = "'%s'" % filename
2427 2425 self.shell.hooks.editor(filename,lineno)
2428 2426 except TryNext:
2429 2427 warn('Could not open editor')
2430 2428 return
2431 2429
2432 2430 # XXX TODO: should this be generalized for all string vars?
2433 2431 # For now, this is special-cased to blocks created by cpaste
2434 2432 if args.strip() == 'pasted_block':
2435 2433 self.shell.user_ns['pasted_block'] = file_read(filename)
2436 2434
2437 2435 if 'x' in opts: # -x prevents actual execution
2438 2436 print
2439 2437 else:
2440 2438 print 'done. Executing edited code...'
2441 2439 if 'r' in opts: # Untranslated IPython code
2442 2440 self.shell.run_cell(file_read(filename),
2443 2441 store_history=False)
2444 2442 else:
2445 2443 self.shell.safe_execfile(filename,self.shell.user_ns,
2446 2444 self.shell.user_ns)
2447 2445
2448 2446 if is_temp:
2449 2447 try:
2450 2448 return open(filename).read()
2451 2449 except IOError,msg:
2452 2450 if msg.filename == filename:
2453 2451 warn('File not found. Did you forget to save?')
2454 2452 return
2455 2453 else:
2456 2454 self.shell.showtraceback()
2457 2455
2458 2456 def magic_xmode(self,parameter_s = ''):
2459 2457 """Switch modes for the exception handlers.
2460 2458
2461 2459 Valid modes: Plain, Context and Verbose.
2462 2460
2463 2461 If called without arguments, acts as a toggle."""
2464 2462
2465 2463 def xmode_switch_err(name):
2466 2464 warn('Error changing %s exception modes.\n%s' %
2467 2465 (name,sys.exc_info()[1]))
2468 2466
2469 2467 shell = self.shell
2470 2468 new_mode = parameter_s.strip().capitalize()
2471 2469 try:
2472 2470 shell.InteractiveTB.set_mode(mode=new_mode)
2473 2471 print 'Exception reporting mode:',shell.InteractiveTB.mode
2474 2472 except:
2475 2473 xmode_switch_err('user')
2476 2474
2477 2475 def magic_colors(self,parameter_s = ''):
2478 2476 """Switch color scheme for prompts, info system and exception handlers.
2479 2477
2480 2478 Currently implemented schemes: NoColor, Linux, LightBG.
2481 2479
2482 2480 Color scheme names are not case-sensitive.
2483 2481
2484 2482 Examples
2485 2483 --------
2486 2484 To get a plain black and white terminal::
2487 2485
2488 2486 %colors nocolor
2489 2487 """
2490 2488
2491 2489 def color_switch_err(name):
2492 2490 warn('Error changing %s color schemes.\n%s' %
2493 2491 (name,sys.exc_info()[1]))
2494 2492
2495 2493
2496 2494 new_scheme = parameter_s.strip()
2497 2495 if not new_scheme:
2498 2496 raise UsageError(
2499 2497 "%colors: you must specify a color scheme. See '%colors?'")
2500 2498 return
2501 2499 # local shortcut
2502 2500 shell = self.shell
2503 2501
2504 2502 import IPython.utils.rlineimpl as readline
2505 2503
2506 2504 if not readline.have_readline and sys.platform == "win32":
2507 2505 msg = """\
2508 2506 Proper color support under MS Windows requires the pyreadline library.
2509 2507 You can find it at:
2510 2508 http://ipython.scipy.org/moin/PyReadline/Intro
2511 2509 Gary's readline needs the ctypes module, from:
2512 2510 http://starship.python.net/crew/theller/ctypes
2513 2511 (Note that ctypes is already part of Python versions 2.5 and newer).
2514 2512
2515 2513 Defaulting color scheme to 'NoColor'"""
2516 2514 new_scheme = 'NoColor'
2517 2515 warn(msg)
2518 2516
2519 2517 # readline option is 0
2520 2518 if not shell.has_readline:
2521 2519 new_scheme = 'NoColor'
2522 2520
2523 2521 # Set prompt colors
2524 2522 try:
2525 2523 shell.displayhook.set_colors(new_scheme)
2526 2524 except:
2527 2525 color_switch_err('prompt')
2528 2526 else:
2529 2527 shell.colors = \
2530 2528 shell.displayhook.color_table.active_scheme_name
2531 2529 # Set exception colors
2532 2530 try:
2533 2531 shell.InteractiveTB.set_colors(scheme = new_scheme)
2534 2532 shell.SyntaxTB.set_colors(scheme = new_scheme)
2535 2533 except:
2536 2534 color_switch_err('exception')
2537 2535
2538 2536 # Set info (for 'object?') colors
2539 2537 if shell.color_info:
2540 2538 try:
2541 2539 shell.inspector.set_active_scheme(new_scheme)
2542 2540 except:
2543 2541 color_switch_err('object inspector')
2544 2542 else:
2545 2543 shell.inspector.set_active_scheme('NoColor')
2546 2544
2547 2545 def magic_pprint(self, parameter_s=''):
2548 2546 """Toggle pretty printing on/off."""
2549 2547 ptformatter = self.shell.display_formatter.formatters['text/plain']
2550 2548 ptformatter.pprint = bool(1 - ptformatter.pprint)
2551 2549 print 'Pretty printing has been turned', \
2552 2550 ['OFF','ON'][ptformatter.pprint]
2553 2551
2554 2552 #......................................................................
2555 2553 # Functions to implement unix shell-type things
2556 2554
2557 2555 @skip_doctest
2558 2556 def magic_alias(self, parameter_s = ''):
2559 2557 """Define an alias for a system command.
2560 2558
2561 2559 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2562 2560
2563 2561 Then, typing 'alias_name params' will execute the system command 'cmd
2564 2562 params' (from your underlying operating system).
2565 2563
2566 2564 Aliases have lower precedence than magic functions and Python normal
2567 2565 variables, so if 'foo' is both a Python variable and an alias, the
2568 2566 alias can not be executed until 'del foo' removes the Python variable.
2569 2567
2570 2568 You can use the %l specifier in an alias definition to represent the
2571 2569 whole line when the alias is called. For example:
2572 2570
2573 2571 In [2]: alias bracket echo "Input in brackets: <%l>"
2574 2572 In [3]: bracket hello world
2575 2573 Input in brackets: <hello world>
2576 2574
2577 2575 You can also define aliases with parameters using %s specifiers (one
2578 2576 per parameter):
2579 2577
2580 2578 In [1]: alias parts echo first %s second %s
2581 2579 In [2]: %parts A B
2582 2580 first A second B
2583 2581 In [3]: %parts A
2584 2582 Incorrect number of arguments: 2 expected.
2585 2583 parts is an alias to: 'echo first %s second %s'
2586 2584
2587 2585 Note that %l and %s are mutually exclusive. You can only use one or
2588 2586 the other in your aliases.
2589 2587
2590 2588 Aliases expand Python variables just like system calls using ! or !!
2591 2589 do: all expressions prefixed with '$' get expanded. For details of
2592 2590 the semantic rules, see PEP-215:
2593 2591 http://www.python.org/peps/pep-0215.html. This is the library used by
2594 2592 IPython for variable expansion. If you want to access a true shell
2595 2593 variable, an extra $ is necessary to prevent its expansion by IPython:
2596 2594
2597 2595 In [6]: alias show echo
2598 2596 In [7]: PATH='A Python string'
2599 2597 In [8]: show $PATH
2600 2598 A Python string
2601 2599 In [9]: show $$PATH
2602 2600 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2603 2601
2604 2602 You can use the alias facility to acess all of $PATH. See the %rehash
2605 2603 and %rehashx functions, which automatically create aliases for the
2606 2604 contents of your $PATH.
2607 2605
2608 2606 If called with no parameters, %alias prints the current alias table."""
2609 2607
2610 2608 par = parameter_s.strip()
2611 2609 if not par:
2612 2610 stored = self.db.get('stored_aliases', {} )
2613 2611 aliases = sorted(self.shell.alias_manager.aliases)
2614 2612 # for k, v in stored:
2615 2613 # atab.append(k, v[0])
2616 2614
2617 2615 print "Total number of aliases:", len(aliases)
2618 2616 sys.stdout.flush()
2619 2617 return aliases
2620 2618
2621 2619 # Now try to define a new one
2622 2620 try:
2623 2621 alias,cmd = par.split(None, 1)
2624 2622 except:
2625 2623 print oinspect.getdoc(self.magic_alias)
2626 2624 else:
2627 2625 self.shell.alias_manager.soft_define_alias(alias, cmd)
2628 2626 # end magic_alias
2629 2627
2630 2628 def magic_unalias(self, parameter_s = ''):
2631 2629 """Remove an alias"""
2632 2630
2633 2631 aname = parameter_s.strip()
2634 2632 self.shell.alias_manager.undefine_alias(aname)
2635 2633 stored = self.db.get('stored_aliases', {} )
2636 2634 if aname in stored:
2637 2635 print "Removing %stored alias",aname
2638 2636 del stored[aname]
2639 2637 self.db['stored_aliases'] = stored
2640 2638
2641 2639 def magic_rehashx(self, parameter_s = ''):
2642 2640 """Update the alias table with all executable files in $PATH.
2643 2641
2644 2642 This version explicitly checks that every entry in $PATH is a file
2645 2643 with execute access (os.X_OK), so it is much slower than %rehash.
2646 2644
2647 2645 Under Windows, it checks executability as a match agains a
2648 2646 '|'-separated string of extensions, stored in the IPython config
2649 2647 variable win_exec_ext. This defaults to 'exe|com|bat'.
2650 2648
2651 2649 This function also resets the root module cache of module completer,
2652 2650 used on slow filesystems.
2653 2651 """
2654 2652 from IPython.core.alias import InvalidAliasError
2655 2653
2656 2654 # for the benefit of module completer in ipy_completers.py
2657 2655 del self.db['rootmodules']
2658 2656
2659 2657 path = [os.path.abspath(os.path.expanduser(p)) for p in
2660 2658 os.environ.get('PATH','').split(os.pathsep)]
2661 2659 path = filter(os.path.isdir,path)
2662 2660
2663 2661 syscmdlist = []
2664 2662 # Now define isexec in a cross platform manner.
2665 2663 if os.name == 'posix':
2666 2664 isexec = lambda fname:os.path.isfile(fname) and \
2667 2665 os.access(fname,os.X_OK)
2668 2666 else:
2669 2667 try:
2670 2668 winext = os.environ['pathext'].replace(';','|').replace('.','')
2671 2669 except KeyError:
2672 2670 winext = 'exe|com|bat|py'
2673 2671 if 'py' not in winext:
2674 2672 winext += '|py'
2675 2673 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2676 2674 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2677 2675 savedir = os.getcwd()
2678 2676
2679 2677 # Now walk the paths looking for executables to alias.
2680 2678 try:
2681 2679 # write the whole loop for posix/Windows so we don't have an if in
2682 2680 # the innermost part
2683 2681 if os.name == 'posix':
2684 2682 for pdir in path:
2685 2683 os.chdir(pdir)
2686 2684 for ff in os.listdir(pdir):
2687 2685 if isexec(ff):
2688 2686 try:
2689 2687 # Removes dots from the name since ipython
2690 2688 # will assume names with dots to be python.
2691 2689 self.shell.alias_manager.define_alias(
2692 2690 ff.replace('.',''), ff)
2693 2691 except InvalidAliasError:
2694 2692 pass
2695 2693 else:
2696 2694 syscmdlist.append(ff)
2697 2695 else:
2698 2696 no_alias = self.shell.alias_manager.no_alias
2699 2697 for pdir in path:
2700 2698 os.chdir(pdir)
2701 2699 for ff in os.listdir(pdir):
2702 2700 base, ext = os.path.splitext(ff)
2703 2701 if isexec(ff) and base.lower() not in no_alias:
2704 2702 if ext.lower() == '.exe':
2705 2703 ff = base
2706 2704 try:
2707 2705 # Removes dots from the name since ipython
2708 2706 # will assume names with dots to be python.
2709 2707 self.shell.alias_manager.define_alias(
2710 2708 base.lower().replace('.',''), ff)
2711 2709 except InvalidAliasError:
2712 2710 pass
2713 2711 syscmdlist.append(ff)
2714 2712 db = self.db
2715 2713 db['syscmdlist'] = syscmdlist
2716 2714 finally:
2717 2715 os.chdir(savedir)
2718 2716
2719 2717 @skip_doctest
2720 2718 def magic_pwd(self, parameter_s = ''):
2721 2719 """Return the current working directory path.
2722 2720
2723 2721 Examples
2724 2722 --------
2725 2723 ::
2726 2724
2727 2725 In [9]: pwd
2728 2726 Out[9]: '/home/tsuser/sprint/ipython'
2729 2727 """
2730 2728 return os.getcwd()
2731 2729
2732 2730 @skip_doctest
2733 2731 def magic_cd(self, parameter_s=''):
2734 2732 """Change the current working directory.
2735 2733
2736 2734 This command automatically maintains an internal list of directories
2737 2735 you visit during your IPython session, in the variable _dh. The
2738 2736 command %dhist shows this history nicely formatted. You can also
2739 2737 do 'cd -<tab>' to see directory history conveniently.
2740 2738
2741 2739 Usage:
2742 2740
2743 2741 cd 'dir': changes to directory 'dir'.
2744 2742
2745 2743 cd -: changes to the last visited directory.
2746 2744
2747 2745 cd -<n>: changes to the n-th directory in the directory history.
2748 2746
2749 2747 cd --foo: change to directory that matches 'foo' in history
2750 2748
2751 2749 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2752 2750 (note: cd <bookmark_name> is enough if there is no
2753 2751 directory <bookmark_name>, but a bookmark with the name exists.)
2754 2752 'cd -b <tab>' allows you to tab-complete bookmark names.
2755 2753
2756 2754 Options:
2757 2755
2758 2756 -q: quiet. Do not print the working directory after the cd command is
2759 2757 executed. By default IPython's cd command does print this directory,
2760 2758 since the default prompts do not display path information.
2761 2759
2762 2760 Note that !cd doesn't work for this purpose because the shell where
2763 2761 !command runs is immediately discarded after executing 'command'.
2764 2762
2765 2763 Examples
2766 2764 --------
2767 2765 ::
2768 2766
2769 2767 In [10]: cd parent/child
2770 2768 /home/tsuser/parent/child
2771 2769 """
2772 2770
2773 2771 parameter_s = parameter_s.strip()
2774 2772 #bkms = self.shell.persist.get("bookmarks",{})
2775 2773
2776 2774 oldcwd = os.getcwd()
2777 2775 numcd = re.match(r'(-)(\d+)$',parameter_s)
2778 2776 # jump in directory history by number
2779 2777 if numcd:
2780 2778 nn = int(numcd.group(2))
2781 2779 try:
2782 2780 ps = self.shell.user_ns['_dh'][nn]
2783 2781 except IndexError:
2784 2782 print 'The requested directory does not exist in history.'
2785 2783 return
2786 2784 else:
2787 2785 opts = {}
2788 2786 elif parameter_s.startswith('--'):
2789 2787 ps = None
2790 2788 fallback = None
2791 2789 pat = parameter_s[2:]
2792 2790 dh = self.shell.user_ns['_dh']
2793 2791 # first search only by basename (last component)
2794 2792 for ent in reversed(dh):
2795 2793 if pat in os.path.basename(ent) and os.path.isdir(ent):
2796 2794 ps = ent
2797 2795 break
2798 2796
2799 2797 if fallback is None and pat in ent and os.path.isdir(ent):
2800 2798 fallback = ent
2801 2799
2802 2800 # if we have no last part match, pick the first full path match
2803 2801 if ps is None:
2804 2802 ps = fallback
2805 2803
2806 2804 if ps is None:
2807 2805 print "No matching entry in directory history"
2808 2806 return
2809 2807 else:
2810 2808 opts = {}
2811 2809
2812 2810
2813 2811 else:
2814 2812 #turn all non-space-escaping backslashes to slashes,
2815 2813 # for c:\windows\directory\names\
2816 2814 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2817 2815 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2818 2816 # jump to previous
2819 2817 if ps == '-':
2820 2818 try:
2821 2819 ps = self.shell.user_ns['_dh'][-2]
2822 2820 except IndexError:
2823 2821 raise UsageError('%cd -: No previous directory to change to.')
2824 2822 # jump to bookmark if needed
2825 2823 else:
2826 2824 if not os.path.isdir(ps) or opts.has_key('b'):
2827 2825 bkms = self.db.get('bookmarks', {})
2828 2826
2829 2827 if bkms.has_key(ps):
2830 2828 target = bkms[ps]
2831 2829 print '(bookmark:%s) -> %s' % (ps,target)
2832 2830 ps = target
2833 2831 else:
2834 2832 if opts.has_key('b'):
2835 2833 raise UsageError("Bookmark '%s' not found. "
2836 2834 "Use '%%bookmark -l' to see your bookmarks." % ps)
2837 2835
2838 2836 # at this point ps should point to the target dir
2839 2837 if ps:
2840 2838 try:
2841 2839 os.chdir(os.path.expanduser(ps))
2842 2840 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2843 2841 set_term_title('IPython: ' + abbrev_cwd())
2844 2842 except OSError:
2845 2843 print sys.exc_info()[1]
2846 2844 else:
2847 2845 cwd = os.getcwd()
2848 2846 dhist = self.shell.user_ns['_dh']
2849 2847 if oldcwd != cwd:
2850 2848 dhist.append(cwd)
2851 2849 self.db['dhist'] = compress_dhist(dhist)[-100:]
2852 2850
2853 2851 else:
2854 2852 os.chdir(self.shell.home_dir)
2855 2853 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2856 2854 set_term_title('IPython: ' + '~')
2857 2855 cwd = os.getcwd()
2858 2856 dhist = self.shell.user_ns['_dh']
2859 2857
2860 2858 if oldcwd != cwd:
2861 2859 dhist.append(cwd)
2862 2860 self.db['dhist'] = compress_dhist(dhist)[-100:]
2863 2861 if not 'q' in opts and self.shell.user_ns['_dh']:
2864 2862 print self.shell.user_ns['_dh'][-1]
2865 2863
2866 2864
2867 2865 def magic_env(self, parameter_s=''):
2868 2866 """List environment variables."""
2869 2867
2870 2868 return os.environ.data
2871 2869
2872 2870 def magic_pushd(self, parameter_s=''):
2873 2871 """Place the current dir on stack and change directory.
2874 2872
2875 2873 Usage:\\
2876 2874 %pushd ['dirname']
2877 2875 """
2878 2876
2879 2877 dir_s = self.shell.dir_stack
2880 2878 tgt = os.path.expanduser(parameter_s)
2881 2879 cwd = os.getcwd().replace(self.home_dir,'~')
2882 2880 if tgt:
2883 2881 self.magic_cd(parameter_s)
2884 2882 dir_s.insert(0,cwd)
2885 2883 return self.magic_dirs()
2886 2884
2887 2885 def magic_popd(self, parameter_s=''):
2888 2886 """Change to directory popped off the top of the stack.
2889 2887 """
2890 2888 if not self.shell.dir_stack:
2891 2889 raise UsageError("%popd on empty stack")
2892 2890 top = self.shell.dir_stack.pop(0)
2893 2891 self.magic_cd(top)
2894 2892 print "popd ->",top
2895 2893
2896 2894 def magic_dirs(self, parameter_s=''):
2897 2895 """Return the current directory stack."""
2898 2896
2899 2897 return self.shell.dir_stack
2900 2898
2901 2899 def magic_dhist(self, parameter_s=''):
2902 2900 """Print your history of visited directories.
2903 2901
2904 2902 %dhist -> print full history\\
2905 2903 %dhist n -> print last n entries only\\
2906 2904 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2907 2905
2908 2906 This history is automatically maintained by the %cd command, and
2909 2907 always available as the global list variable _dh. You can use %cd -<n>
2910 2908 to go to directory number <n>.
2911 2909
2912 2910 Note that most of time, you should view directory history by entering
2913 2911 cd -<TAB>.
2914 2912
2915 2913 """
2916 2914
2917 2915 dh = self.shell.user_ns['_dh']
2918 2916 if parameter_s:
2919 2917 try:
2920 2918 args = map(int,parameter_s.split())
2921 2919 except:
2922 2920 self.arg_err(Magic.magic_dhist)
2923 2921 return
2924 2922 if len(args) == 1:
2925 2923 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2926 2924 elif len(args) == 2:
2927 2925 ini,fin = args
2928 2926 else:
2929 2927 self.arg_err(Magic.magic_dhist)
2930 2928 return
2931 2929 else:
2932 2930 ini,fin = 0,len(dh)
2933 2931 nlprint(dh,
2934 2932 header = 'Directory history (kept in _dh)',
2935 2933 start=ini,stop=fin)
2936 2934
2937 2935 @skip_doctest
2938 2936 def magic_sc(self, parameter_s=''):
2939 2937 """Shell capture - execute a shell command and capture its output.
2940 2938
2941 2939 DEPRECATED. Suboptimal, retained for backwards compatibility.
2942 2940
2943 2941 You should use the form 'var = !command' instead. Example:
2944 2942
2945 2943 "%sc -l myfiles = ls ~" should now be written as
2946 2944
2947 2945 "myfiles = !ls ~"
2948 2946
2949 2947 myfiles.s, myfiles.l and myfiles.n still apply as documented
2950 2948 below.
2951 2949
2952 2950 --
2953 2951 %sc [options] varname=command
2954 2952
2955 2953 IPython will run the given command using commands.getoutput(), and
2956 2954 will then update the user's interactive namespace with a variable
2957 2955 called varname, containing the value of the call. Your command can
2958 2956 contain shell wildcards, pipes, etc.
2959 2957
2960 2958 The '=' sign in the syntax is mandatory, and the variable name you
2961 2959 supply must follow Python's standard conventions for valid names.
2962 2960
2963 2961 (A special format without variable name exists for internal use)
2964 2962
2965 2963 Options:
2966 2964
2967 2965 -l: list output. Split the output on newlines into a list before
2968 2966 assigning it to the given variable. By default the output is stored
2969 2967 as a single string.
2970 2968
2971 2969 -v: verbose. Print the contents of the variable.
2972 2970
2973 2971 In most cases you should not need to split as a list, because the
2974 2972 returned value is a special type of string which can automatically
2975 2973 provide its contents either as a list (split on newlines) or as a
2976 2974 space-separated string. These are convenient, respectively, either
2977 2975 for sequential processing or to be passed to a shell command.
2978 2976
2979 2977 For example:
2980 2978
2981 2979 # all-random
2982 2980
2983 2981 # Capture into variable a
2984 2982 In [1]: sc a=ls *py
2985 2983
2986 2984 # a is a string with embedded newlines
2987 2985 In [2]: a
2988 2986 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2989 2987
2990 2988 # which can be seen as a list:
2991 2989 In [3]: a.l
2992 2990 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2993 2991
2994 2992 # or as a whitespace-separated string:
2995 2993 In [4]: a.s
2996 2994 Out[4]: 'setup.py win32_manual_post_install.py'
2997 2995
2998 2996 # a.s is useful to pass as a single command line:
2999 2997 In [5]: !wc -l $a.s
3000 2998 146 setup.py
3001 2999 130 win32_manual_post_install.py
3002 3000 276 total
3003 3001
3004 3002 # while the list form is useful to loop over:
3005 3003 In [6]: for f in a.l:
3006 3004 ...: !wc -l $f
3007 3005 ...:
3008 3006 146 setup.py
3009 3007 130 win32_manual_post_install.py
3010 3008
3011 3009 Similiarly, the lists returned by the -l option are also special, in
3012 3010 the sense that you can equally invoke the .s attribute on them to
3013 3011 automatically get a whitespace-separated string from their contents:
3014 3012
3015 3013 In [7]: sc -l b=ls *py
3016 3014
3017 3015 In [8]: b
3018 3016 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3019 3017
3020 3018 In [9]: b.s
3021 3019 Out[9]: 'setup.py win32_manual_post_install.py'
3022 3020
3023 3021 In summary, both the lists and strings used for ouptut capture have
3024 3022 the following special attributes:
3025 3023
3026 3024 .l (or .list) : value as list.
3027 3025 .n (or .nlstr): value as newline-separated string.
3028 3026 .s (or .spstr): value as space-separated string.
3029 3027 """
3030 3028
3031 3029 opts,args = self.parse_options(parameter_s,'lv')
3032 3030 # Try to get a variable name and command to run
3033 3031 try:
3034 3032 # the variable name must be obtained from the parse_options
3035 3033 # output, which uses shlex.split to strip options out.
3036 3034 var,_ = args.split('=',1)
3037 3035 var = var.strip()
3038 3036 # But the the command has to be extracted from the original input
3039 3037 # parameter_s, not on what parse_options returns, to avoid the
3040 3038 # quote stripping which shlex.split performs on it.
3041 3039 _,cmd = parameter_s.split('=',1)
3042 3040 except ValueError:
3043 3041 var,cmd = '',''
3044 3042 # If all looks ok, proceed
3045 3043 split = 'l' in opts
3046 3044 out = self.shell.getoutput(cmd, split=split)
3047 3045 if opts.has_key('v'):
3048 3046 print '%s ==\n%s' % (var,pformat(out))
3049 3047 if var:
3050 3048 self.shell.user_ns.update({var:out})
3051 3049 else:
3052 3050 return out
3053 3051
3054 3052 def magic_sx(self, parameter_s=''):
3055 3053 """Shell execute - run a shell command and capture its output.
3056 3054
3057 3055 %sx command
3058 3056
3059 3057 IPython will run the given command using commands.getoutput(), and
3060 3058 return the result formatted as a list (split on '\\n'). Since the
3061 3059 output is _returned_, it will be stored in ipython's regular output
3062 3060 cache Out[N] and in the '_N' automatic variables.
3063 3061
3064 3062 Notes:
3065 3063
3066 3064 1) If an input line begins with '!!', then %sx is automatically
3067 3065 invoked. That is, while:
3068 3066 !ls
3069 3067 causes ipython to simply issue system('ls'), typing
3070 3068 !!ls
3071 3069 is a shorthand equivalent to:
3072 3070 %sx ls
3073 3071
3074 3072 2) %sx differs from %sc in that %sx automatically splits into a list,
3075 3073 like '%sc -l'. The reason for this is to make it as easy as possible
3076 3074 to process line-oriented shell output via further python commands.
3077 3075 %sc is meant to provide much finer control, but requires more
3078 3076 typing.
3079 3077
3080 3078 3) Just like %sc -l, this is a list with special attributes:
3081 3079
3082 3080 .l (or .list) : value as list.
3083 3081 .n (or .nlstr): value as newline-separated string.
3084 3082 .s (or .spstr): value as whitespace-separated string.
3085 3083
3086 3084 This is very useful when trying to use such lists as arguments to
3087 3085 system commands."""
3088 3086
3089 3087 if parameter_s:
3090 3088 return self.shell.getoutput(parameter_s)
3091 3089
3092 3090
3093 3091 def magic_bookmark(self, parameter_s=''):
3094 3092 """Manage IPython's bookmark system.
3095 3093
3096 3094 %bookmark <name> - set bookmark to current dir
3097 3095 %bookmark <name> <dir> - set bookmark to <dir>
3098 3096 %bookmark -l - list all bookmarks
3099 3097 %bookmark -d <name> - remove bookmark
3100 3098 %bookmark -r - remove all bookmarks
3101 3099
3102 3100 You can later on access a bookmarked folder with:
3103 3101 %cd -b <name>
3104 3102 or simply '%cd <name>' if there is no directory called <name> AND
3105 3103 there is such a bookmark defined.
3106 3104
3107 3105 Your bookmarks persist through IPython sessions, but they are
3108 3106 associated with each profile."""
3109 3107
3110 3108 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3111 3109 if len(args) > 2:
3112 3110 raise UsageError("%bookmark: too many arguments")
3113 3111
3114 3112 bkms = self.db.get('bookmarks',{})
3115 3113
3116 3114 if opts.has_key('d'):
3117 3115 try:
3118 3116 todel = args[0]
3119 3117 except IndexError:
3120 3118 raise UsageError(
3121 3119 "%bookmark -d: must provide a bookmark to delete")
3122 3120 else:
3123 3121 try:
3124 3122 del bkms[todel]
3125 3123 except KeyError:
3126 3124 raise UsageError(
3127 3125 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3128 3126
3129 3127 elif opts.has_key('r'):
3130 3128 bkms = {}
3131 3129 elif opts.has_key('l'):
3132 3130 bks = bkms.keys()
3133 3131 bks.sort()
3134 3132 if bks:
3135 3133 size = max(map(len,bks))
3136 3134 else:
3137 3135 size = 0
3138 3136 fmt = '%-'+str(size)+'s -> %s'
3139 3137 print 'Current bookmarks:'
3140 3138 for bk in bks:
3141 3139 print fmt % (bk,bkms[bk])
3142 3140 else:
3143 3141 if not args:
3144 3142 raise UsageError("%bookmark: You must specify the bookmark name")
3145 3143 elif len(args)==1:
3146 3144 bkms[args[0]] = os.getcwd()
3147 3145 elif len(args)==2:
3148 3146 bkms[args[0]] = args[1]
3149 3147 self.db['bookmarks'] = bkms
3150 3148
3151 3149 def magic_pycat(self, parameter_s=''):
3152 3150 """Show a syntax-highlighted file through a pager.
3153 3151
3154 3152 This magic is similar to the cat utility, but it will assume the file
3155 3153 to be Python source and will show it with syntax highlighting. """
3156 3154
3157 3155 try:
3158 3156 filename = get_py_filename(parameter_s)
3159 3157 cont = file_read(filename)
3160 3158 except IOError:
3161 3159 try:
3162 3160 cont = eval(parameter_s,self.user_ns)
3163 3161 except NameError:
3164 3162 cont = None
3165 3163 if cont is None:
3166 3164 print "Error: no such file or variable"
3167 3165 return
3168 3166
3169 3167 page.page(self.shell.pycolorize(cont))
3170 3168
3171 3169 def _rerun_pasted(self):
3172 3170 """ Rerun a previously pasted command.
3173 3171 """
3174 3172 b = self.user_ns.get('pasted_block', None)
3175 3173 if b is None:
3176 3174 raise UsageError('No previous pasted block available')
3177 3175 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3178 3176 exec b in self.user_ns
3179 3177
3180 3178 def _get_pasted_lines(self, sentinel):
3181 3179 """ Yield pasted lines until the user enters the given sentinel value.
3182 3180 """
3183 3181 from IPython.core import interactiveshell
3184 3182 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3185 3183 while True:
3186 3184 l = interactiveshell.raw_input_original(':')
3187 3185 if l == sentinel:
3188 3186 return
3189 3187 else:
3190 3188 yield l
3191 3189
3192 3190 def _strip_pasted_lines_for_code(self, raw_lines):
3193 3191 """ Strip non-code parts of a sequence of lines to return a block of
3194 3192 code.
3195 3193 """
3196 3194 # Regular expressions that declare text we strip from the input:
3197 3195 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3198 3196 r'^\s*(\s?>)+', # Python input prompt
3199 3197 r'^\s*\.{3,}', # Continuation prompts
3200 3198 r'^\++',
3201 3199 ]
3202 3200
3203 3201 strip_from_start = map(re.compile,strip_re)
3204 3202
3205 3203 lines = []
3206 3204 for l in raw_lines:
3207 3205 for pat in strip_from_start:
3208 3206 l = pat.sub('',l)
3209 3207 lines.append(l)
3210 3208
3211 3209 block = "\n".join(lines) + '\n'
3212 3210 #print "block:\n",block
3213 3211 return block
3214 3212
3215 3213 def _execute_block(self, block, par):
3216 3214 """ Execute a block, or store it in a variable, per the user's request.
3217 3215 """
3218 3216 if not par:
3219 3217 b = textwrap.dedent(block)
3220 3218 self.user_ns['pasted_block'] = b
3221 3219 exec b in self.user_ns
3222 3220 else:
3223 3221 self.user_ns[par] = SList(block.splitlines())
3224 3222 print "Block assigned to '%s'" % par
3225 3223
3226 3224 def magic_quickref(self,arg):
3227 3225 """ Show a quick reference sheet """
3228 3226 import IPython.core.usage
3229 3227 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3230 3228
3231 3229 page.page(qr)
3232 3230
3233 3231 def magic_doctest_mode(self,parameter_s=''):
3234 3232 """Toggle doctest mode on and off.
3235 3233
3236 3234 This mode is intended to make IPython behave as much as possible like a
3237 3235 plain Python shell, from the perspective of how its prompts, exceptions
3238 3236 and output look. This makes it easy to copy and paste parts of a
3239 3237 session into doctests. It does so by:
3240 3238
3241 3239 - Changing the prompts to the classic ``>>>`` ones.
3242 3240 - Changing the exception reporting mode to 'Plain'.
3243 3241 - Disabling pretty-printing of output.
3244 3242
3245 3243 Note that IPython also supports the pasting of code snippets that have
3246 3244 leading '>>>' and '...' prompts in them. This means that you can paste
3247 3245 doctests from files or docstrings (even if they have leading
3248 3246 whitespace), and the code will execute correctly. You can then use
3249 3247 '%history -t' to see the translated history; this will give you the
3250 3248 input after removal of all the leading prompts and whitespace, which
3251 3249 can be pasted back into an editor.
3252 3250
3253 3251 With these features, you can switch into this mode easily whenever you
3254 3252 need to do testing and changes to doctests, without having to leave
3255 3253 your existing IPython session.
3256 3254 """
3257 3255
3258 3256 from IPython.utils.ipstruct import Struct
3259 3257
3260 3258 # Shorthands
3261 3259 shell = self.shell
3262 3260 oc = shell.displayhook
3263 3261 meta = shell.meta
3264 3262 disp_formatter = self.shell.display_formatter
3265 3263 ptformatter = disp_formatter.formatters['text/plain']
3266 3264 # dstore is a data store kept in the instance metadata bag to track any
3267 3265 # changes we make, so we can undo them later.
3268 3266 dstore = meta.setdefault('doctest_mode',Struct())
3269 3267 save_dstore = dstore.setdefault
3270 3268
3271 3269 # save a few values we'll need to recover later
3272 3270 mode = save_dstore('mode',False)
3273 3271 save_dstore('rc_pprint',ptformatter.pprint)
3274 3272 save_dstore('xmode',shell.InteractiveTB.mode)
3275 3273 save_dstore('rc_separate_out',shell.separate_out)
3276 3274 save_dstore('rc_separate_out2',shell.separate_out2)
3277 3275 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3278 3276 save_dstore('rc_separate_in',shell.separate_in)
3279 3277 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
3280 3278
3281 3279 if mode == False:
3282 3280 # turn on
3283 3281 oc.prompt1.p_template = '>>> '
3284 3282 oc.prompt2.p_template = '... '
3285 3283 oc.prompt_out.p_template = ''
3286 3284
3287 3285 # Prompt separators like plain python
3288 3286 oc.input_sep = oc.prompt1.sep = ''
3289 3287 oc.output_sep = ''
3290 3288 oc.output_sep2 = ''
3291 3289
3292 3290 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3293 3291 oc.prompt_out.pad_left = False
3294 3292
3295 3293 ptformatter.pprint = False
3296 3294 disp_formatter.plain_text_only = True
3297 3295
3298 3296 shell.magic_xmode('Plain')
3299 3297 else:
3300 3298 # turn off
3301 3299 oc.prompt1.p_template = shell.prompt_in1
3302 3300 oc.prompt2.p_template = shell.prompt_in2
3303 3301 oc.prompt_out.p_template = shell.prompt_out
3304 3302
3305 3303 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3306 3304
3307 3305 oc.output_sep = dstore.rc_separate_out
3308 3306 oc.output_sep2 = dstore.rc_separate_out2
3309 3307
3310 3308 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3311 3309 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3312 3310
3313 3311 ptformatter.pprint = dstore.rc_pprint
3314 3312 disp_formatter.plain_text_only = dstore.rc_plain_text_only
3315 3313
3316 3314 shell.magic_xmode(dstore.xmode)
3317 3315
3318 3316 # Store new mode and inform
3319 3317 dstore.mode = bool(1-int(mode))
3320 3318 mode_label = ['OFF','ON'][dstore.mode]
3321 3319 print 'Doctest mode is:', mode_label
3322 3320
3323 3321 def magic_gui(self, parameter_s=''):
3324 3322 """Enable or disable IPython GUI event loop integration.
3325 3323
3326 3324 %gui [GUINAME]
3327 3325
3328 3326 This magic replaces IPython's threaded shells that were activated
3329 3327 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3330 3328 can now be enabled, disabled and changed at runtime and keyboard
3331 3329 interrupts should work without any problems. The following toolkits
3332 3330 are supported: wxPython, PyQt4, PyGTK, and Tk::
3333 3331
3334 3332 %gui wx # enable wxPython event loop integration
3335 3333 %gui qt4|qt # enable PyQt4 event loop integration
3336 3334 %gui gtk # enable PyGTK event loop integration
3337 3335 %gui tk # enable Tk event loop integration
3338 3336 %gui # disable all event loop integration
3339 3337
3340 3338 WARNING: after any of these has been called you can simply create
3341 3339 an application object, but DO NOT start the event loop yourself, as
3342 3340 we have already handled that.
3343 3341 """
3344 3342 from IPython.lib.inputhook import enable_gui
3345 3343 opts, arg = self.parse_options(parameter_s, '')
3346 3344 if arg=='': arg = None
3347 3345 return enable_gui(arg)
3348 3346
3349 3347 def magic_load_ext(self, module_str):
3350 3348 """Load an IPython extension by its module name."""
3351 3349 return self.extension_manager.load_extension(module_str)
3352 3350
3353 3351 def magic_unload_ext(self, module_str):
3354 3352 """Unload an IPython extension by its module name."""
3355 3353 self.extension_manager.unload_extension(module_str)
3356 3354
3357 3355 def magic_reload_ext(self, module_str):
3358 3356 """Reload an IPython extension by its module name."""
3359 3357 self.extension_manager.reload_extension(module_str)
3360 3358
3361 3359 @skip_doctest
3362 3360 def magic_install_profiles(self, s):
3363 3361 """Install the default IPython profiles into the .ipython dir.
3364 3362
3365 3363 If the default profiles have already been installed, they will not
3366 3364 be overwritten. You can force overwriting them by using the ``-o``
3367 3365 option::
3368 3366
3369 3367 In [1]: %install_profiles -o
3370 3368 """
3371 3369 if '-o' in s:
3372 3370 overwrite = True
3373 3371 else:
3374 3372 overwrite = False
3375 3373 from IPython.config import profile
3376 profile_dir = os.path.split(profile.__file__)[0]
3374 profile_dir = os.path.dirname(profile.__file__)
3377 3375 ipython_dir = self.ipython_dir
3378 files = os.listdir(profile_dir)
3379
3380 to_install = []
3381 for f in files:
3382 if f.startswith('ipython_config'):
3383 src = os.path.join(profile_dir, f)
3384 dst = os.path.join(ipython_dir, f)
3385 if (not os.path.isfile(dst)) or overwrite:
3386 to_install.append((f, src, dst))
3387 if len(to_install)>0:
3388 print "Installing profiles to: ", ipython_dir
3389 for (f, src, dst) in to_install:
3390 shutil.copy(src, dst)
3391 print " %s" % f
3376 print "Installing profiles to: %s [overwrite=%s]"(ipython_dir,overwrite)
3377 for src in os.listdir(profile_dir):
3378 if src.startswith('profile_'):
3379 name = src.replace('profile_', '')
3380 print " %s"%name
3381 pd = ProfileDir.create_profile_dir_by_name(ipython_dir, name)
3382 pd.copy_config_file('ipython_config.py', path=src,
3383 overwrite=overwrite)
3392 3384
3393 3385 @skip_doctest
3394 3386 def magic_install_default_config(self, s):
3395 3387 """Install IPython's default config file into the .ipython dir.
3396 3388
3397 3389 If the default config file (:file:`ipython_config.py`) is already
3398 3390 installed, it will not be overwritten. You can force overwriting
3399 3391 by using the ``-o`` option::
3400 3392
3401 3393 In [1]: %install_default_config
3402 3394 """
3403 3395 if '-o' in s:
3404 3396 overwrite = True
3405 3397 else:
3406 3398 overwrite = False
3407 from IPython.config import default
3408 config_dir = os.path.split(default.__file__)[0]
3409 ipython_dir = self.ipython_dir
3410 default_config_file_name = 'ipython_config.py'
3411 src = os.path.join(config_dir, default_config_file_name)
3412 dst = os.path.join(ipython_dir, default_config_file_name)
3413 if (not os.path.isfile(dst)) or overwrite:
3414 shutil.copy(src, dst)
3415 print "Installing default config file: %s" % dst
3399 pd = self.shell.profile_dir
3400 print "Installing default config file in: %s" % pd.location
3401 pd.copy_config_file('ipython_config.py', overwrite=overwrite)
3416 3402
3417 3403 # Pylab support: simple wrappers that activate pylab, load gui input
3418 3404 # handling and modify slightly %run
3419 3405
3420 3406 @skip_doctest
3421 3407 def _pylab_magic_run(self, parameter_s=''):
3422 3408 Magic.magic_run(self, parameter_s,
3423 3409 runner=mpl_runner(self.shell.safe_execfile))
3424 3410
3425 3411 _pylab_magic_run.__doc__ = magic_run.__doc__
3426 3412
3427 3413 @skip_doctest
3428 3414 def magic_pylab(self, s):
3429 3415 """Load numpy and matplotlib to work interactively.
3430 3416
3431 3417 %pylab [GUINAME]
3432 3418
3433 3419 This function lets you activate pylab (matplotlib, numpy and
3434 3420 interactive support) at any point during an IPython session.
3435 3421
3436 3422 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3437 3423 pylab and mlab, as well as all names from numpy and pylab.
3438 3424
3439 3425 Parameters
3440 3426 ----------
3441 3427 guiname : optional
3442 3428 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk', 'osx' or
3443 3429 'tk'). If given, the corresponding Matplotlib backend is used,
3444 3430 otherwise matplotlib's default (which you can override in your
3445 3431 matplotlib config file) is used.
3446 3432
3447 3433 Examples
3448 3434 --------
3449 3435 In this case, where the MPL default is TkAgg:
3450 3436 In [2]: %pylab
3451 3437
3452 3438 Welcome to pylab, a matplotlib-based Python environment.
3453 3439 Backend in use: TkAgg
3454 3440 For more information, type 'help(pylab)'.
3455 3441
3456 3442 But you can explicitly request a different backend:
3457 3443 In [3]: %pylab qt
3458 3444
3459 3445 Welcome to pylab, a matplotlib-based Python environment.
3460 3446 Backend in use: Qt4Agg
3461 3447 For more information, type 'help(pylab)'.
3462 3448 """
3463 3449 self.shell.enable_pylab(s)
3464 3450
3465 3451 def magic_tb(self, s):
3466 3452 """Print the last traceback with the currently active exception mode.
3467 3453
3468 3454 See %xmode for changing exception reporting modes."""
3469 3455 self.shell.showtraceback()
3470 3456
3471 3457 @skip_doctest
3472 3458 def magic_precision(self, s=''):
3473 3459 """Set floating point precision for pretty printing.
3474 3460
3475 3461 Can set either integer precision or a format string.
3476 3462
3477 3463 If numpy has been imported and precision is an int,
3478 3464 numpy display precision will also be set, via ``numpy.set_printoptions``.
3479 3465
3480 3466 If no argument is given, defaults will be restored.
3481 3467
3482 3468 Examples
3483 3469 --------
3484 3470 ::
3485 3471
3486 3472 In [1]: from math import pi
3487 3473
3488 3474 In [2]: %precision 3
3489 3475 Out[2]: '%.3f'
3490 3476
3491 3477 In [3]: pi
3492 3478 Out[3]: 3.142
3493 3479
3494 3480 In [4]: %precision %i
3495 3481 Out[4]: '%i'
3496 3482
3497 3483 In [5]: pi
3498 3484 Out[5]: 3
3499 3485
3500 3486 In [6]: %precision %e
3501 3487 Out[6]: '%e'
3502 3488
3503 3489 In [7]: pi**10
3504 3490 Out[7]: 9.364805e+04
3505 3491
3506 3492 In [8]: %precision
3507 3493 Out[8]: '%r'
3508 3494
3509 3495 In [9]: pi**10
3510 3496 Out[9]: 93648.047476082982
3511 3497
3512 3498 """
3513 3499
3514 3500 ptformatter = self.shell.display_formatter.formatters['text/plain']
3515 3501 ptformatter.float_precision = s
3516 3502 return ptformatter.float_format
3517 3503
3518 3504 # end Magic
@@ -1,564 +1,590
1 1 # -*- coding: utf-8 -*-
2 2 """Subclass of InteractiveShell for terminal based frontends."""
3 3
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 7 # Copyright (C) 2008-2010 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 __builtin__
18 18 import bdb
19 19 from contextlib import nested
20 20 import os
21 21 import re
22 22 import sys
23 23
24 24 from IPython.core.error import TryNext
25 25 from IPython.core.usage import interactive_usage, default_banner
26 26 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
27 27 from IPython.lib.inputhook import enable_gui
28 28 from IPython.lib.pylabtools import pylab_activate
29 29 from IPython.testing.skipdoctest import skip_doctest
30 30 from IPython.utils.terminal import toggle_set_term_title, set_term_title
31 31 from IPython.utils.process import abbrev_cwd
32 32 from IPython.utils.warn import warn
33 33 from IPython.utils.text import num_ini_spaces
34 34 from IPython.utils.traitlets import Int, Str, CBool, Unicode
35 35
36 36 #-----------------------------------------------------------------------------
37 37 # Utilities
38 38 #-----------------------------------------------------------------------------
39 39
40 40 def get_default_editor():
41 41 try:
42 42 ed = os.environ['EDITOR']
43 43 except KeyError:
44 44 if os.name == 'posix':
45 45 ed = 'vi' # the only one guaranteed to be there!
46 46 else:
47 47 ed = 'notepad' # same in Windows!
48 48 return ed
49 49
50 50
51 51 # store the builtin raw_input globally, and use this always, in case user code
52 52 # overwrites it (like wx.py.PyShell does)
53 53 raw_input_original = raw_input
54 54
55 55 #-----------------------------------------------------------------------------
56 56 # Main class
57 57 #-----------------------------------------------------------------------------
58 58
59 59 class TerminalInteractiveShell(InteractiveShell):
60 60
61 autoedit_syntax = CBool(False, config=True)
61 autoedit_syntax = CBool(False, config=True,
62 help="auto editing of files with syntax errors.")
62 63 banner = Unicode('')
63 banner1 = Unicode(default_banner, config=True)
64 banner2 = Unicode('', config=True)
65 confirm_exit = CBool(True, config=True)
64 banner1 = Unicode(default_banner, config=True,
65 help="""The part of the banner to be printed before the profile"""
66 )
67 banner2 = Unicode('', config=True,
68 help="""The part of the banner to be printed after the profile"""
69 )
70 confirm_exit = CBool(True, config=True,
71 help="""
72 Set to confirm when you try to exit IPython with an EOF (Control-D
73 in Unix, Control-Z/Enter in Windows). By typing 'exit', 'quit' or
74 '%%Exit', you can force a direct exit without any confirmation.""",
75 )
66 76 # This display_banner only controls whether or not self.show_banner()
67 77 # is called when mainloop/interact are called. The default is False
68 78 # because for the terminal based application, the banner behavior
69 79 # is controlled by Global.display_banner, which IPythonApp looks at
70 80 # to determine if *it* should call show_banner() by hand or not.
71 81 display_banner = CBool(False) # This isn't configurable!
72 82 embedded = CBool(False)
73 83 embedded_active = CBool(False)
74 editor = Unicode(get_default_editor(), config=True)
75 pager = Unicode('less', config=True)
76
77 screen_length = Int(0, config=True)
78 term_title = CBool(False, config=True)
79
80 def __init__(self, config=None, ipython_dir=None, user_ns=None,
84 editor = Unicode(get_default_editor(), config=True,
85 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
86 )
87 pager = Unicode('less', config=True,
88 help="The shell program to be used for paging.")
89
90 screen_length = Int(0, config=True,
91 help=
92 """Number of lines of your screen, used to control printing of very
93 long strings. Strings longer than this number of lines will be sent
94 through a pager instead of directly printed. The default value for
95 this is 0, which means IPython will auto-detect your screen size every
96 time it needs to print certain potentially long strings (this doesn't
97 change the behavior of the 'print' keyword, it's only triggered
98 internally). If for some reason this isn't working well (it needs
99 curses support), specify it yourself. Otherwise don't change the
100 default.""",
101 )
102 term_title = CBool(False, config=True,
103 help="Enable auto setting the terminal title."
104 )
105
106 def __init__(self, config=None, ipython_dir=None, profile_dir=None, user_ns=None,
81 107 user_global_ns=None, custom_exceptions=((),None),
82 108 usage=None, banner1=None, banner2=None,
83 109 display_banner=None):
84 110
85 111 super(TerminalInteractiveShell, self).__init__(
86 config=config, ipython_dir=ipython_dir, user_ns=user_ns,
112 config=config, profile_dir=profile_dir, user_ns=user_ns,
87 113 user_global_ns=user_global_ns, custom_exceptions=custom_exceptions
88 114 )
89 115 # use os.system instead of utils.process.system by default, except on Windows
90 116 if os.name == 'nt':
91 117 self.system = self.system_piped
92 118 else:
93 119 self.system = self.system_raw
94 120
95 121 self.init_term_title()
96 122 self.init_usage(usage)
97 123 self.init_banner(banner1, banner2, display_banner)
98 124
99 125 #-------------------------------------------------------------------------
100 126 # Things related to the terminal
101 127 #-------------------------------------------------------------------------
102 128
103 129 @property
104 130 def usable_screen_length(self):
105 131 if self.screen_length == 0:
106 132 return 0
107 133 else:
108 134 num_lines_bot = self.separate_in.count('\n')+1
109 135 return self.screen_length - num_lines_bot
110 136
111 137 def init_term_title(self):
112 138 # Enable or disable the terminal title.
113 139 if self.term_title:
114 140 toggle_set_term_title(True)
115 141 set_term_title('IPython: ' + abbrev_cwd())
116 142 else:
117 143 toggle_set_term_title(False)
118 144
119 145 #-------------------------------------------------------------------------
120 146 # Things related to aliases
121 147 #-------------------------------------------------------------------------
122 148
123 149 def init_alias(self):
124 150 # The parent class defines aliases that can be safely used with any
125 151 # frontend.
126 152 super(TerminalInteractiveShell, self).init_alias()
127 153
128 154 # Now define aliases that only make sense on the terminal, because they
129 155 # need direct access to the console in a way that we can't emulate in
130 156 # GUI or web frontend
131 157 if os.name == 'posix':
132 158 aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'),
133 159 ('man', 'man')]
134 160 elif os.name == 'nt':
135 161 aliases = [('cls', 'cls')]
136 162
137 163
138 164 for name, cmd in aliases:
139 165 self.alias_manager.define_alias(name, cmd)
140 166
141 167 #-------------------------------------------------------------------------
142 168 # Things related to the banner and usage
143 169 #-------------------------------------------------------------------------
144 170
145 171 def _banner1_changed(self):
146 172 self.compute_banner()
147 173
148 174 def _banner2_changed(self):
149 175 self.compute_banner()
150 176
151 177 def _term_title_changed(self, name, new_value):
152 178 self.init_term_title()
153 179
154 180 def init_banner(self, banner1, banner2, display_banner):
155 181 if banner1 is not None:
156 182 self.banner1 = banner1
157 183 if banner2 is not None:
158 184 self.banner2 = banner2
159 185 if display_banner is not None:
160 186 self.display_banner = display_banner
161 187 self.compute_banner()
162 188
163 189 def show_banner(self, banner=None):
164 190 if banner is None:
165 191 banner = self.banner
166 192 self.write(banner)
167 193
168 194 def compute_banner(self):
169 195 self.banner = self.banner1
170 196 if self.profile:
171 197 self.banner += '\nIPython profile: %s\n' % self.profile
172 198 if self.banner2:
173 199 self.banner += '\n' + self.banner2
174 200
175 201 def init_usage(self, usage=None):
176 202 if usage is None:
177 203 self.usage = interactive_usage
178 204 else:
179 205 self.usage = usage
180 206
181 207 #-------------------------------------------------------------------------
182 208 # Mainloop and code execution logic
183 209 #-------------------------------------------------------------------------
184 210
185 211 def mainloop(self, display_banner=None):
186 212 """Start the mainloop.
187 213
188 214 If an optional banner argument is given, it will override the
189 215 internally created default banner.
190 216 """
191 217
192 218 with nested(self.builtin_trap, self.display_trap):
193 219
194 220 while 1:
195 221 try:
196 222 self.interact(display_banner=display_banner)
197 223 #self.interact_with_readline()
198 224 # XXX for testing of a readline-decoupled repl loop, call
199 225 # interact_with_readline above
200 226 break
201 227 except KeyboardInterrupt:
202 228 # this should not be necessary, but KeyboardInterrupt
203 229 # handling seems rather unpredictable...
204 230 self.write("\nKeyboardInterrupt in interact()\n")
205 231
206 232 def interact(self, display_banner=None):
207 233 """Closely emulate the interactive Python console."""
208 234
209 235 # batch run -> do not interact
210 236 if self.exit_now:
211 237 return
212 238
213 239 if display_banner is None:
214 240 display_banner = self.display_banner
215 241 if display_banner:
216 242 self.show_banner()
217 243
218 244 more = False
219 245
220 246 # Mark activity in the builtins
221 247 __builtin__.__dict__['__IPYTHON__active'] += 1
222 248
223 249 if self.has_readline:
224 250 self.readline_startup_hook(self.pre_readline)
225 251 # exit_now is set by a call to %Exit or %Quit, through the
226 252 # ask_exit callback.
227 253
228 254 while not self.exit_now:
229 255 self.hooks.pre_prompt_hook()
230 256 if more:
231 257 try:
232 258 prompt = self.hooks.generate_prompt(True)
233 259 except:
234 260 self.showtraceback()
235 261 if self.autoindent:
236 262 self.rl_do_indent = True
237 263
238 264 else:
239 265 try:
240 266 prompt = self.hooks.generate_prompt(False)
241 267 except:
242 268 self.showtraceback()
243 269 try:
244 270 line = self.raw_input(prompt)
245 271 if self.exit_now:
246 272 # quick exit on sys.std[in|out] close
247 273 break
248 274 if self.autoindent:
249 275 self.rl_do_indent = False
250 276
251 277 except KeyboardInterrupt:
252 278 #double-guard against keyboardinterrupts during kbdint handling
253 279 try:
254 280 self.write('\nKeyboardInterrupt\n')
255 281 self.input_splitter.reset()
256 282 more = False
257 283 except KeyboardInterrupt:
258 284 pass
259 285 except EOFError:
260 286 if self.autoindent:
261 287 self.rl_do_indent = False
262 288 if self.has_readline:
263 289 self.readline_startup_hook(None)
264 290 self.write('\n')
265 291 self.exit()
266 292 except bdb.BdbQuit:
267 293 warn('The Python debugger has exited with a BdbQuit exception.\n'
268 294 'Because of how pdb handles the stack, it is impossible\n'
269 295 'for IPython to properly format this particular exception.\n'
270 296 'IPython will resume normal operation.')
271 297 except:
272 298 # exceptions here are VERY RARE, but they can be triggered
273 299 # asynchronously by signal handlers, for example.
274 300 self.showtraceback()
275 301 else:
276 302 self.input_splitter.push(line)
277 303 more = self.input_splitter.push_accepts_more()
278 304 if (self.SyntaxTB.last_syntax_error and
279 305 self.autoedit_syntax):
280 306 self.edit_syntax_error()
281 307 if not more:
282 308 source_raw = self.input_splitter.source_raw_reset()[1]
283 309 self.run_cell(source_raw)
284 310
285 311 # We are off again...
286 312 __builtin__.__dict__['__IPYTHON__active'] -= 1
287 313
288 314 # Turn off the exit flag, so the mainloop can be restarted if desired
289 315 self.exit_now = False
290 316
291 317 def raw_input(self, prompt=''):
292 318 """Write a prompt and read a line.
293 319
294 320 The returned line does not include the trailing newline.
295 321 When the user enters the EOF key sequence, EOFError is raised.
296 322
297 323 Optional inputs:
298 324
299 325 - prompt(''): a string to be printed to prompt the user.
300 326
301 327 - continue_prompt(False): whether this line is the first one or a
302 328 continuation in a sequence of inputs.
303 329 """
304 330 # Code run by the user may have modified the readline completer state.
305 331 # We must ensure that our completer is back in place.
306 332
307 333 if self.has_readline:
308 334 self.set_readline_completer()
309 335
310 336 try:
311 337 line = raw_input_original(prompt).decode(self.stdin_encoding)
312 338 except ValueError:
313 339 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
314 340 " or sys.stdout.close()!\nExiting IPython!")
315 341 self.ask_exit()
316 342 return ""
317 343
318 344 # Try to be reasonably smart about not re-indenting pasted input more
319 345 # than necessary. We do this by trimming out the auto-indent initial
320 346 # spaces, if the user's actual input started itself with whitespace.
321 347 if self.autoindent:
322 348 if num_ini_spaces(line) > self.indent_current_nsp:
323 349 line = line[self.indent_current_nsp:]
324 350 self.indent_current_nsp = 0
325 351
326 352 return line
327 353
328 354 #-------------------------------------------------------------------------
329 355 # Methods to support auto-editing of SyntaxErrors.
330 356 #-------------------------------------------------------------------------
331 357
332 358 def edit_syntax_error(self):
333 359 """The bottom half of the syntax error handler called in the main loop.
334 360
335 361 Loop until syntax error is fixed or user cancels.
336 362 """
337 363
338 364 while self.SyntaxTB.last_syntax_error:
339 365 # copy and clear last_syntax_error
340 366 err = self.SyntaxTB.clear_err_state()
341 367 if not self._should_recompile(err):
342 368 return
343 369 try:
344 370 # may set last_syntax_error again if a SyntaxError is raised
345 371 self.safe_execfile(err.filename,self.user_ns)
346 372 except:
347 373 self.showtraceback()
348 374 else:
349 375 try:
350 376 f = file(err.filename)
351 377 try:
352 378 # This should be inside a display_trap block and I
353 379 # think it is.
354 380 sys.displayhook(f.read())
355 381 finally:
356 382 f.close()
357 383 except:
358 384 self.showtraceback()
359 385
360 386 def _should_recompile(self,e):
361 387 """Utility routine for edit_syntax_error"""
362 388
363 389 if e.filename in ('<ipython console>','<input>','<string>',
364 390 '<console>','<BackgroundJob compilation>',
365 391 None):
366 392
367 393 return False
368 394 try:
369 395 if (self.autoedit_syntax and
370 396 not self.ask_yes_no('Return to editor to correct syntax error? '
371 397 '[Y/n] ','y')):
372 398 return False
373 399 except EOFError:
374 400 return False
375 401
376 402 def int0(x):
377 403 try:
378 404 return int(x)
379 405 except TypeError:
380 406 return 0
381 407 # always pass integer line and offset values to editor hook
382 408 try:
383 409 self.hooks.fix_error_editor(e.filename,
384 410 int0(e.lineno),int0(e.offset),e.msg)
385 411 except TryNext:
386 412 warn('Could not open editor')
387 413 return False
388 414 return True
389 415
390 416 #-------------------------------------------------------------------------
391 417 # Things related to GUI support and pylab
392 418 #-------------------------------------------------------------------------
393 419
394 420 def enable_pylab(self, gui=None):
395 421 """Activate pylab support at runtime.
396 422
397 423 This turns on support for matplotlib, preloads into the interactive
398 424 namespace all of numpy and pylab, and configures IPython to correcdtly
399 425 interact with the GUI event loop. The GUI backend to be used can be
400 426 optionally selected with the optional :param:`gui` argument.
401 427
402 428 Parameters
403 429 ----------
404 430 gui : optional, string
405 431
406 432 If given, dictates the choice of matplotlib GUI backend to use
407 433 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
408 434 'gtk'), otherwise we use the default chosen by matplotlib (as
409 435 dictated by the matplotlib build-time options plus the user's
410 436 matplotlibrc configuration file).
411 437 """
412 438 # We want to prevent the loading of pylab to pollute the user's
413 439 # namespace as shown by the %who* magics, so we execute the activation
414 440 # code in an empty namespace, and we update *both* user_ns and
415 441 # user_ns_hidden with this information.
416 442 ns = {}
417 443 gui = pylab_activate(ns, gui)
418 444 self.user_ns.update(ns)
419 445 self.user_ns_hidden.update(ns)
420 446 # Now we must activate the gui pylab wants to use, and fix %run to take
421 447 # plot updates into account
422 448 enable_gui(gui)
423 449 self.magic_run = self._pylab_magic_run
424 450
425 451 #-------------------------------------------------------------------------
426 452 # Things related to exiting
427 453 #-------------------------------------------------------------------------
428 454
429 455 def ask_exit(self):
430 456 """ Ask the shell to exit. Can be overiden and used as a callback. """
431 457 self.exit_now = True
432 458
433 459 def exit(self):
434 460 """Handle interactive exit.
435 461
436 462 This method calls the ask_exit callback."""
437 463 if self.confirm_exit:
438 464 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
439 465 self.ask_exit()
440 466 else:
441 467 self.ask_exit()
442 468
443 469 #------------------------------------------------------------------------
444 470 # Magic overrides
445 471 #------------------------------------------------------------------------
446 472 # Once the base class stops inheriting from magic, this code needs to be
447 473 # moved into a separate machinery as well. For now, at least isolate here
448 474 # the magics which this class needs to implement differently from the base
449 475 # class, or that are unique to it.
450 476
451 477 def magic_autoindent(self, parameter_s = ''):
452 478 """Toggle autoindent on/off (if available)."""
453 479
454 480 self.shell.set_autoindent()
455 481 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
456 482
457 483 @skip_doctest
458 484 def magic_cpaste(self, parameter_s=''):
459 485 """Paste & execute a pre-formatted code block from clipboard.
460 486
461 487 You must terminate the block with '--' (two minus-signs) alone on the
462 488 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
463 489 is the new sentinel for this operation)
464 490
465 491 The block is dedented prior to execution to enable execution of method
466 492 definitions. '>' and '+' characters at the beginning of a line are
467 493 ignored, to allow pasting directly from e-mails, diff files and
468 494 doctests (the '...' continuation prompt is also stripped). The
469 495 executed block is also assigned to variable named 'pasted_block' for
470 496 later editing with '%edit pasted_block'.
471 497
472 498 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
473 499 This assigns the pasted block to variable 'foo' as string, without
474 500 dedenting or executing it (preceding >>> and + is still stripped)
475 501
476 502 '%cpaste -r' re-executes the block previously entered by cpaste.
477 503
478 504 Do not be alarmed by garbled output on Windows (it's a readline bug).
479 505 Just press enter and type -- (and press enter again) and the block
480 506 will be what was just pasted.
481 507
482 508 IPython statements (magics, shell escapes) are not supported (yet).
483 509
484 510 See also
485 511 --------
486 512 paste: automatically pull code from clipboard.
487 513
488 514 Examples
489 515 --------
490 516 ::
491 517
492 518 In [8]: %cpaste
493 519 Pasting code; enter '--' alone on the line to stop.
494 520 :>>> a = ["world!", "Hello"]
495 521 :>>> print " ".join(sorted(a))
496 522 :--
497 523 Hello world!
498 524 """
499 525
500 526 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
501 527 par = args.strip()
502 528 if opts.has_key('r'):
503 529 self._rerun_pasted()
504 530 return
505 531
506 532 sentinel = opts.get('s','--')
507 533
508 534 block = self._strip_pasted_lines_for_code(
509 535 self._get_pasted_lines(sentinel))
510 536
511 537 self._execute_block(block, par)
512 538
513 539 def magic_paste(self, parameter_s=''):
514 540 """Paste & execute a pre-formatted code block from clipboard.
515 541
516 542 The text is pulled directly from the clipboard without user
517 543 intervention and printed back on the screen before execution (unless
518 544 the -q flag is given to force quiet mode).
519 545
520 546 The block is dedented prior to execution to enable execution of method
521 547 definitions. '>' and '+' characters at the beginning of a line are
522 548 ignored, to allow pasting directly from e-mails, diff files and
523 549 doctests (the '...' continuation prompt is also stripped). The
524 550 executed block is also assigned to variable named 'pasted_block' for
525 551 later editing with '%edit pasted_block'.
526 552
527 553 You can also pass a variable name as an argument, e.g. '%paste foo'.
528 554 This assigns the pasted block to variable 'foo' as string, without
529 555 dedenting or executing it (preceding >>> and + is still stripped)
530 556
531 557 Options
532 558 -------
533 559
534 560 -r: re-executes the block previously entered by cpaste.
535 561
536 562 -q: quiet mode: do not echo the pasted text back to the terminal.
537 563
538 564 IPython statements (magics, shell escapes) are not supported (yet).
539 565
540 566 See also
541 567 --------
542 568 cpaste: manually paste code into terminal until you mark its end.
543 569 """
544 570 opts,args = self.parse_options(parameter_s,'rq',mode='string')
545 571 par = args.strip()
546 572 if opts.has_key('r'):
547 573 self._rerun_pasted()
548 574 return
549 575
550 576 text = self.shell.hooks.clipboard_get()
551 577 block = self._strip_pasted_lines_for_code(text.splitlines())
552 578
553 579 # By default, echo back to terminal unless quiet mode is requested
554 580 if not opts.has_key('q'):
555 581 write = self.shell.write
556 582 write(self.shell.pycolorize(block))
557 583 if not block.endswith('\n'):
558 584 write('\n')
559 585 write("## -- End pasted text --\n")
560 586
561 587 self._execute_block(block, par)
562 588
563 589
564 590 InteractiveShellABC.register(TerminalInteractiveShell)
This diff has been collapsed as it changes many lines, (768 lines changed) Show them Hide them
@@ -1,666 +1,540
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3 """
4 The :class:`~IPython.core.application.Application` object for the command
4 The :class:`~IPython.core.newapplication.Application` object for the command
5 5 line :command:`ipython` program.
6 6
7 7 Authors
8 8 -------
9 9
10 10 * Brian Granger
11 11 * Fernando Perez
12 * Min Ragan-Kelley
12 13 """
13 14
14 15 #-----------------------------------------------------------------------------
15 16 # Copyright (C) 2008-2010 The IPython Development Team
16 17 #
17 18 # Distributed under the terms of the BSD License. The full license is in
18 19 # the file COPYING, distributed as part of this software.
19 20 #-----------------------------------------------------------------------------
20 21
21 22 #-----------------------------------------------------------------------------
22 23 # Imports
23 24 #-----------------------------------------------------------------------------
24 25
25 26 from __future__ import absolute_import
26 27
27 28 import logging
28 29 import os
29 30 import sys
30 31
32 from IPython.config.loader import (
33 Config, PyFileConfigLoader
34 )
35 from IPython.config.application import boolean_flag
31 36 from IPython.core import release
37 from IPython.core import usage
32 38 from IPython.core.crashhandler import CrashHandler
33 from IPython.core.application import Application, BaseAppConfigLoader
34 from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
35 from IPython.config.loader import (
36 Config,
37 PyFileConfigLoader
39 from IPython.core.formatters import PlainTextFormatter
40 from IPython.core.newapplication import (
41 ProfileDir, BaseIPythonApplication, base_flags, base_aliases
38 42 )
43 from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
39 44 from IPython.lib import inputhook
40 45 from IPython.utils.path import filefind, get_ipython_dir, check_for_old_config
41 from IPython.core import usage
46 from IPython.utils.traitlets import (
47 Bool, Unicode, Dict, Instance, List,CaselessStrEnum
48 )
42 49
43 50 #-----------------------------------------------------------------------------
44 51 # Globals, utilities and helpers
45 52 #-----------------------------------------------------------------------------
46 53
47 54 #: The default config file name for this application.
48 55 default_config_file_name = u'ipython_config.py'
49 56
50 57
51 class IPAppConfigLoader(BaseAppConfigLoader):
52
53 def _add_arguments(self):
54 super(IPAppConfigLoader, self)._add_arguments()
55 paa = self.parser.add_argument
56 paa('-p',
57 '--profile', dest='Global.profile', type=unicode,
58 help=
59 """The string name of the ipython profile to be used. Assume that your
60 config file is ipython_config-<name>.py (looks in current dir first,
61 then in IPYTHON_DIR). This is a quick way to keep and load multiple
62 config files for different tasks, especially if include your basic one
63 in your more specialized ones. You can keep a basic
64 IPYTHON_DIR/ipython_config.py file and then have other 'profiles' which
65 include this one and load extra things for particular tasks.""",
66 metavar='Global.profile')
67 paa('--config-file',
68 dest='Global.config_file', type=unicode,
69 help=
70 """Set the config file name to override default. Normally IPython
71 loads ipython_config.py (from current directory) or
72 IPYTHON_DIR/ipython_config.py. If the loading of your config file
73 fails, IPython starts with a bare bones configuration (no modules
74 loaded at all).""",
75 metavar='Global.config_file')
76 paa('--autocall',
77 dest='InteractiveShell.autocall', type=int,
78 help=
79 """Make IPython automatically call any callable object even if you
80 didn't type explicit parentheses. For example, 'str 43' becomes
81 'str(43)' automatically. The value can be '0' to disable the feature,
82 '1' for 'smart' autocall, where it is not applied if there are no more
83 arguments on the line, and '2' for 'full' autocall, where all callable
84 objects are automatically called (even if no arguments are present).
85 The default is '1'.""",
86 metavar='InteractiveShell.autocall')
87 paa('--autoindent',
88 action='store_true', dest='InteractiveShell.autoindent',
89 help='Turn on autoindenting.')
90 paa('--no-autoindent',
91 action='store_false', dest='InteractiveShell.autoindent',
92 help='Turn off autoindenting.')
93 paa('--automagic',
94 action='store_true', dest='InteractiveShell.automagic',
95 help=
96 """Turn on the auto calling of magic commands. Type %%magic at the
97 IPython prompt for more information.""")
98 paa('--no-automagic',
99 action='store_false', dest='InteractiveShell.automagic',
100 help='Turn off the auto calling of magic commands.')
101 paa('--autoedit-syntax',
102 action='store_true', dest='TerminalInteractiveShell.autoedit_syntax',
103 help='Turn on auto editing of files with syntax errors.')
104 paa('--no-autoedit-syntax',
105 action='store_false', dest='TerminalInteractiveShell.autoedit_syntax',
106 help='Turn off auto editing of files with syntax errors.')
107 paa('--banner',
108 action='store_true', dest='Global.display_banner',
109 help='Display a banner upon starting IPython.')
110 paa('--no-banner',
111 action='store_false', dest='Global.display_banner',
112 help="Don't display a banner upon starting IPython.")
113 paa('--cache-size',
114 type=int, dest='InteractiveShell.cache_size',
115 help=
116 """Set the size of the output cache. The default is 1000, you can
117 change it permanently in your config file. Setting it to 0 completely
118 disables the caching system, and the minimum value accepted is 20 (if
119 you provide a value less than 20, it is reset to 0 and a warning is
120 issued). This limit is defined because otherwise you'll spend more
121 time re-flushing a too small cache than working""",
122 metavar='InteractiveShell.cache_size')
123 paa('--classic',
124 action='store_true', dest='Global.classic',
125 help="Gives IPython a similar feel to the classic Python prompt.")
126 paa('--colors',
127 type=str, dest='InteractiveShell.colors',
128 help="Set the color scheme (NoColor, Linux, and LightBG).",
129 metavar='InteractiveShell.colors')
130 paa('--color-info',
131 action='store_true', dest='InteractiveShell.color_info',
132 help=
133 """IPython can display information about objects via a set of func-
134 tions, and optionally can use colors for this, syntax highlighting
135 source code and various other elements. However, because this
136 information is passed through a pager (like 'less') and many pagers get
137 confused with color codes, this option is off by default. You can test
138 it and turn it on permanently in your ipython_config.py file if it
139 works for you. Test it and turn it on permanently if it works with
140 your system. The magic function %%color_info allows you to toggle this
141 inter- actively for testing.""")
142 paa('--no-color-info',
143 action='store_false', dest='InteractiveShell.color_info',
144 help="Disable using colors for info related things.")
145 paa('--confirm-exit',
146 action='store_true', dest='TerminalInteractiveShell.confirm_exit',
147 help=
148 """Set to confirm when you try to exit IPython with an EOF (Control-D
149 in Unix, Control-Z/Enter in Windows). By typing 'exit', 'quit' or
150 '%%Exit', you can force a direct exit without any confirmation.""")
151 paa('--no-confirm-exit',
152 action='store_false', dest='TerminalInteractiveShell.confirm_exit',
153 help="Don't prompt the user when exiting.")
154 paa('--deep-reload',
155 action='store_true', dest='InteractiveShell.deep_reload',
156 help=
157 """Enable deep (recursive) reloading by default. IPython can use the
158 deep_reload module which reloads changes in modules recursively (it
159 replaces the reload() function, so you don't need to change anything to
160 use it). deep_reload() forces a full reload of modules whose code may
161 have changed, which the default reload() function does not. When
162 deep_reload is off, IPython will use the normal reload(), but
163 deep_reload will still be available as dreload(). This fea- ture is off
164 by default [which means that you have both normal reload() and
165 dreload()].""")
166 paa('--no-deep-reload',
167 action='store_false', dest='InteractiveShell.deep_reload',
168 help="Disable deep (recursive) reloading by default.")
169 paa('--editor',
170 type=str, dest='TerminalInteractiveShell.editor',
171 help="Set the editor used by IPython (default to $EDITOR/vi/notepad).",
172 metavar='TerminalInteractiveShell.editor')
173 paa('--log','-l',
174 action='store_true', dest='InteractiveShell.logstart',
175 help="Start logging to the default log file (./ipython_log.py).")
176 paa('--logfile','-lf',
177 type=unicode, dest='InteractiveShell.logfile',
178 help="Start logging to logfile with this name.",
179 metavar='InteractiveShell.logfile')
180 paa('--log-append','-la',
181 type=unicode, dest='InteractiveShell.logappend',
182 help="Start logging to the given file in append mode.",
183 metavar='InteractiveShell.logfile')
184 paa('--pdb',
185 action='store_true', dest='InteractiveShell.pdb',
186 help="Enable auto calling the pdb debugger after every exception.")
187 paa('--no-pdb',
188 action='store_false', dest='InteractiveShell.pdb',
189 help="Disable auto calling the pdb debugger after every exception.")
190 paa('--pprint',
191 action='store_true', dest='PlainTextFormatter.pprint',
192 help="Enable auto pretty printing of results.")
193 paa('--no-pprint',
194 action='store_false', dest='PlainTextFormatter.pprint',
195 help="Disable auto auto pretty printing of results.")
196 paa('--prompt-in1','-pi1',
197 type=str, dest='InteractiveShell.prompt_in1',
198 help=
199 """Set the main input prompt ('In [\#]: '). Note that if you are using
200 numbered prompts, the number is represented with a '\#' in the string.
201 Don't forget to quote strings with spaces embedded in them. Most
202 bash-like escapes can be used to customize IPython's prompts, as well
203 as a few additional ones which are IPython-spe- cific. All valid
204 prompt escapes are described in detail in the Customization section of
205 the IPython manual.""",
206 metavar='InteractiveShell.prompt_in1')
207 paa('--prompt-in2','-pi2',
208 type=str, dest='InteractiveShell.prompt_in2',
209 help=
210 """Set the secondary input prompt (' .\D.: '). Similar to the previous
211 option, but used for the continuation prompts. The special sequence
212 '\D' is similar to '\#', but with all digits replaced by dots (so you
213 can have your continuation prompt aligned with your input prompt).
214 Default: ' .\D.: ' (note three spaces at the start for alignment with
215 'In [\#]')""",
216 metavar='InteractiveShell.prompt_in2')
217 paa('--prompt-out','-po',
218 type=str, dest='InteractiveShell.prompt_out',
219 help="Set the output prompt ('Out[\#]:')",
220 metavar='InteractiveShell.prompt_out')
221 paa('--quick',
222 action='store_true', dest='Global.quick',
223 help="Enable quick startup with no config files.")
224 paa('--readline',
225 action='store_true', dest='InteractiveShell.readline_use',
226 help="Enable readline for command line usage.")
227 paa('--no-readline',
228 action='store_false', dest='InteractiveShell.readline_use',
229 help="Disable readline for command line usage.")
230 paa('--screen-length','-sl',
231 type=int, dest='TerminalInteractiveShell.screen_length',
232 help=
233 """Number of lines of your screen, used to control printing of very
234 long strings. Strings longer than this number of lines will be sent
235 through a pager instead of directly printed. The default value for
236 this is 0, which means IPython will auto-detect your screen size every
237 time it needs to print certain potentially long strings (this doesn't
238 change the behavior of the 'print' keyword, it's only triggered
239 internally). If for some reason this isn't working well (it needs
240 curses support), specify it yourself. Otherwise don't change the
241 default.""",
242 metavar='TerminalInteractiveShell.screen_length')
243 paa('--separate-in','-si',
244 type=str, dest='InteractiveShell.separate_in',
245 help="Separator before input prompts. Default '\\n'.",
246 metavar='InteractiveShell.separate_in')
247 paa('--separate-out','-so',
248 type=str, dest='InteractiveShell.separate_out',
249 help="Separator before output prompts. Default 0 (nothing).",
250 metavar='InteractiveShell.separate_out')
251 paa('--separate-out2','-so2',
252 type=str, dest='InteractiveShell.separate_out2',
253 help="Separator after output prompts. Default 0 (nonight).",
254 metavar='InteractiveShell.separate_out2')
255 paa('--no-sep',
256 action='store_true', dest='Global.nosep',
257 help="Eliminate all spacing between prompts.")
258 paa('--term-title',
259 action='store_true', dest='TerminalInteractiveShell.term_title',
260 help="Enable auto setting the terminal title.")
261 paa('--no-term-title',
262 action='store_false', dest='TerminalInteractiveShell.term_title',
263 help="Disable auto setting the terminal title.")
264 paa('--xmode',
265 type=str, dest='InteractiveShell.xmode',
266 help=
267 """Exception reporting mode ('Plain','Context','Verbose'). Plain:
268 similar to python's normal traceback printing. Context: prints 5 lines
269 of context source code around each line in the traceback. Verbose:
270 similar to Context, but additionally prints the variables currently
271 visible where the exception happened (shortening their strings if too
272 long). This can potentially be very slow, if you happen to have a huge
273 data structure whose string representation is complex to compute.
274 Your computer may appear to freeze for a while with cpu usage at 100%%.
275 If this occurs, you can cancel the traceback with Ctrl-C (maybe hitting
276 it more than once).
277 """,
278 metavar='InteractiveShell.xmode')
279 paa('--ext',
280 type=str, dest='Global.extra_extension',
281 help="The dotted module name of an IPython extension to load.",
282 metavar='Global.extra_extension')
283 paa('-c',
284 type=str, dest='Global.code_to_run',
285 help="Execute the given command string.",
286 metavar='Global.code_to_run')
287 paa('-i',
288 action='store_true', dest='Global.force_interact',
289 help=
290 "If running code from the command line, become interactive afterwards.")
291
292 # Options to start with GUI control enabled from the beginning
293 paa('--gui',
294 type=str, dest='Global.gui',
295 help="Enable GUI event loop integration ('qt', 'wx', 'gtk').",
296 metavar='gui-mode')
297 paa('--pylab','-pylab',
298 type=str, dest='Global.pylab',
299 nargs='?', const='auto', metavar='gui-mode',
300 help="Pre-load matplotlib and numpy for interactive use. "+
301 "If no value is given, the gui backend is matplotlib's, else use "+
302 "one of: ['tk', 'qt', 'wx', 'gtk', 'osx'].")
303
304 # Legacy GUI options. Leave them in for backwards compatibility, but the
305 # 'thread' names are really a misnomer now.
306 paa('--wthread', '-wthread',
307 action='store_true', dest='Global.wthread',
308 help=
309 """Enable wxPython event loop integration. (DEPRECATED, use --gui wx)""")
310 paa('--q4thread', '--qthread', '-q4thread', '-qthread',
311 action='store_true', dest='Global.q4thread',
312 help=
313 """Enable Qt4 event loop integration. Qt3 is no longer supported.
314 (DEPRECATED, use --gui qt)""")
315 paa('--gthread', '-gthread',
316 action='store_true', dest='Global.gthread',
317 help=
318 """Enable GTK event loop integration. (DEPRECATED, use --gui gtk)""")
319
320 58
321 59 #-----------------------------------------------------------------------------
322 60 # Crash handler for this application
323 61 #-----------------------------------------------------------------------------
324 62
325 63 _message_template = """\
326 64 Oops, $self.app_name crashed. We do our best to make it stable, but...
327 65
328 66 A crash report was automatically generated with the following information:
329 67 - A verbatim copy of the crash traceback.
330 68 - A copy of your input history during this session.
331 69 - Data on your current $self.app_name configuration.
332 70
333 71 It was left in the file named:
334 72 \t'$self.crash_report_fname'
335 73 If you can email this file to the developers, the information in it will help
336 74 them in understanding and correcting the problem.
337 75
338 76 You can mail it to: $self.contact_name at $self.contact_email
339 77 with the subject '$self.app_name Crash Report'.
340 78
341 79 If you want to do it now, the following command will work (under Unix):
342 80 mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname
343 81
344 82 To ensure accurate tracking of this issue, please file a report about it at:
345 83 $self.bug_tracker
346 84 """
347 85
348 86 class IPAppCrashHandler(CrashHandler):
349 87 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
350 88
351 89 message_template = _message_template
352 90
353 91 def __init__(self, app):
354 92 contact_name = release.authors['Fernando'][0]
355 93 contact_email = release.authors['Fernando'][1]
356 94 bug_tracker = 'http://github.com/ipython/ipython/issues'
357 95 super(IPAppCrashHandler,self).__init__(
358 96 app, contact_name, contact_email, bug_tracker
359 97 )
360 98
361 99 def make_report(self,traceback):
362 100 """Return a string containing a crash report."""
363 101
364 102 sec_sep = self.section_sep
365 103 # Start with parent report
366 104 report = [super(IPAppCrashHandler, self).make_report(traceback)]
367 105 # Add interactive-specific info we may have
368 106 rpt_add = report.append
369 107 try:
370 108 rpt_add(sec_sep+"History of session input:")
371 109 for line in self.app.shell.user_ns['_ih']:
372 110 rpt_add(line)
373 111 rpt_add('\n*** Last line of input (may not be in above history):\n')
374 112 rpt_add(self.app.shell._last_input_line+'\n')
375 113 except:
376 114 pass
377 115
378 116 return ''.join(report)
379 117
118 #-----------------------------------------------------------------------------
119 # Aliases and Flags
120 #-----------------------------------------------------------------------------
121 flags = dict(base_flags)
122 flags.update({
123
124
125 })
126 addflag = lambda *args: flags.update(boolean_flag(*args))
127 addflag('autoindent', 'InteractiveShell.autoindent',
128 'Turn on autoindenting.', 'Turn off autoindenting.'
129 )
130 addflag('automagic', 'InteractiveShell.automagic',
131 """Turn on the auto calling of magic commands. Type %%magic at the
132 IPython prompt for more information.""",
133 'Turn off the auto calling of magic commands.'
134 )
135 addflag('autoedit-syntax', 'TerminalInteractiveShell.autoedit_syntax',
136 'Turn on auto editing of files with syntax errors.',
137 'Turn off auto editing of files with syntax errors.'
138 )
139 addflag('banner', 'IPythonApp.display_banner',
140 "Display a banner upon starting IPython.",
141 "Don't display a banner upon starting IPython."
142 )
143 addflag('pdb', 'InteractiveShell.pdb',
144 "Enable auto calling the pdb debugger after every exception.",
145 "Disable auto calling the pdb debugger after every exception."
146 )
147 addflag('pprint', 'PlainTextFormatter.pprint',
148 "Enable auto pretty printing of results.",
149 "Disable auto auto pretty printing of results."
150 )
151 addflag('color-info', 'InteractiveShell.color_info',
152 """IPython can display information about objects via a set of func-
153 tions, and optionally can use colors for this, syntax highlighting
154 source code and various other elements. However, because this
155 information is passed through a pager (like 'less') and many pagers get
156 confused with color codes, this option is off by default. You can test
157 it and turn it on permanently in your ipython_config.py file if it
158 works for you. Test it and turn it on permanently if it works with
159 your system. The magic function %%color_info allows you to toggle this
160 inter- actively for testing.""",
161 "Disable using colors for info related things."
162 )
163 addflag('confirm-exit', 'TerminalInteractiveShell.confirm_exit',
164 """Set to confirm when you try to exit IPython with an EOF (Control-D
165 in Unix, Control-Z/Enter in Windows). By typing 'exit', 'quit' or
166 '%%Exit', you can force a direct exit without any confirmation.""",
167 "Don't prompt the user when exiting."
168 )
169 addflag('deep-reload', 'InteractiveShell.deep_reload',
170 """Enable deep (recursive) reloading by default. IPython can use the
171 deep_reload module which reloads changes in modules recursively (it
172 replaces the reload() function, so you don't need to change anything to
173 use it). deep_reload() forces a full reload of modules whose code may
174 have changed, which the default reload() function does not. When
175 deep_reload is off, IPython will use the normal reload(), but
176 deep_reload will still be available as dreload(). This fea- ture is off
177 by default [which means that you have both normal reload() and
178 dreload()].""",
179 "Disable deep (recursive) reloading by default."
180 )
181 addflag('readline', 'InteractiveShell.readline_use',
182 "Enable readline for command line usage.",
183 "Disable readline for command line usage."
184 )
185 addflag('term-title', 'TerminalInteractiveShell.term_title',
186 "Enable auto setting the terminal title.",
187 "Disable auto setting the terminal title."
188 )
189 classic_config = Config()
190 classic_config.InteractiveShell.cache_size = 0
191 classic_config.PlainTextFormatter.pprint = False
192 classic_config.InteractiveShell.prompt_in1 = '>>> '
193 classic_config.InteractiveShell.prompt_in2 = '... '
194 classic_config.InteractiveShell.prompt_out = ''
195 classic_config.InteractiveShell.separate_in = ''
196 classic_config.InteractiveShell.separate_out = ''
197 classic_config.InteractiveShell.separate_out2 = ''
198 classic_config.InteractiveShell.colors = 'NoColor'
199 classic_config.InteractiveShell.xmode = 'Plain'
200
201 flags['classic']=(
202 classic_config,
203 "Gives IPython a similar feel to the classic Python prompt."
204 )
205 # # log doesn't make so much sense this way anymore
206 # paa('--log','-l',
207 # action='store_true', dest='InteractiveShell.logstart',
208 # help="Start logging to the default log file (./ipython_log.py).")
209 #
210 # # quick is harder to implement
211 flags['quick']=(
212 {'IPythonApp' : {'quick' : True}},
213 "Enable quick startup with no config files."
214 )
215
216 nosep_config = Config()
217 nosep_config.InteractiveShell.separate_in = ''
218 nosep_config.InteractiveShell.separate_out = ''
219 nosep_config.InteractiveShell.separate_out2 = ''
220
221 flags['nosep']=(nosep_config, "Eliminate all spacing between prompts.")
222
223 flags['i'] = (
224 {'IPythonApp' : {'force_interact' : True}},
225 "If running code from the command line, become interactive afterwards."
226 )
227 flags['pylab'] = (
228 {'IPythonApp' : {'pylab' : 'auto'}},
229 """Pre-load matplotlib and numpy for interactive use with
230 the default matplotlib backend."""
231 )
232
233 aliases = dict(base_aliases)
234
235 # it's possible we don't want short aliases for *all* of these:
236 aliases.update(dict(
237 autocall='InteractiveShell.autocall',
238 cache_size='InteractiveShell.cache_size',
239 colors='InteractiveShell.colors',
240 editor='TerminalInteractiveShell.editor',
241 logfile='InteractiveShell.logfile',
242 log_append='InteractiveShell.logappend',
243 pi1='InteractiveShell.prompt_in1',
244 pi2='InteractiveShell.prompt_in1',
245 po='InteractiveShell.prompt_out',
246 sl='TerminalInteractiveShell.screen_length',
247 si='InteractiveShell.separate_in',
248 so='InteractiveShell.separate_out',
249 so2='InteractiveShell.separate_out2',
250 xmode='InteractiveShell.xmode',
251 c='IPythonApp.code_to_run',
252 ext='IPythonApp.extra_extension',
253 gui='IPythonApp.gui',
254 pylab='IPythonApp.pylab',
255 ))
380 256
381 257 #-----------------------------------------------------------------------------
382 258 # Main classes and functions
383 259 #-----------------------------------------------------------------------------
384 260
385 class IPythonApp(Application):
261 class IPythonApp(BaseIPythonApplication):
386 262 name = u'ipython'
387 #: argparse formats better the 'usage' than the 'description' field
388 description = None
389 usage = usage.cl_usage
390 command_line_loader = IPAppConfigLoader
263 description = usage.cl_usage
264 # command_line_loader = IPAppConfigLoader
391 265 default_config_file_name = default_config_file_name
392 266 crash_handler_class = IPAppCrashHandler
393
394 def create_default_config(self):
395 super(IPythonApp, self).create_default_config()
396 # Eliminate multiple lookups
397 Global = self.default_config.Global
398
399 # Set all default values
400 Global.display_banner = True
267 flags = Dict(flags)
268 aliases = Dict(aliases)
269 classes = [TerminalInteractiveShell, ProfileDir, PlainTextFormatter]
270 # *do* autocreate requested profile
271 auto_create=Bool(True)
272 copy_config_files=Bool(True)
273 # configurables
274 ignore_old_config=Bool(False, config=True,
275 help="Suppress warning messages about legacy config files"
276 )
277 quick = Bool(False, config=True,
278 help="""Start IPython quickly by skipping the loading of config files."""
279 )
280 def _quick_changed(self, name, old, new):
281 if new:
282 self.load_config_file = lambda *a, **kw: None
283 self.ignore_old_config=True
284
285 gui = CaselessStrEnum(('qt','wx','gtk'), config=True,
286 help="Enable GUI event loop integration ('qt', 'wx', 'gtk')."
287 )
288 pylab = CaselessStrEnum(['tk', 'qt', 'wx', 'gtk', 'osx', 'auto'],
289 config=True,
290 help="""Pre-load matplotlib and numpy for interactive use,
291 selecting a particular matplotlib backend and loop integration.
292 """
293 )
294 display_banner = Bool(True, config=True,
295 help="Whether to display a banner upon starting IPython."
296 )
297 extensions = List(Unicode, config=True,
298 help="A list of dotted module names of IPython extensions to load."
299 )
300 extra_extension = Unicode('', config=True,
301 help="dotted module name of an IPython extension to load."
302 )
303 def _extra_extension_changed(self, name, old, new):
304 if new:
305 # add to self.extensions
306 self.extensions.append(new)
307
308 # if there is code of files to run from the cmd line, don't interact
309 # unless the --i flag (App.force_interact) is true.
310 force_interact = Bool(False, config=True,
311 help="""If a command or file is given via the command-line,
312 e.g. 'ipython foo.py"""
313 )
314 def _force_interact_changed(self, name, old, new):
315 if new:
316 self.interact = True
317
318 exec_files = List(Unicode, config=True,
319 help="""List of files to run at IPython startup."""
320 )
321 file_to_run = Unicode('', config=True,
322 help="""A file to be run""")
323 def _file_to_run_changed(self, name, old, new):
324 if new and not self.force_interact:
325 self.interact = False
326
327 exec_lines = List(Unicode, config=True,
328 help="""lines of code to run at IPython startup."""
329 )
330 code_to_run = Unicode('', config=True,
331 help="Execute the given command string."
332 )
333 _code_to_run_changed = _file_to_run_changed
334
335 # internal, not-configurable
336 interact=Bool(True)
337
338
339 def initialize(self, argv=None):
340 """Do actions after construct, but before starting the app."""
341 super(IPythonApp, self).initialize(argv)
342 if not self.ignore_old_config:
343 check_for_old_config(self.ipython_dir)
401 344
402 # If the -c flag is given or a file is given to run at the cmd line
403 # like "ipython foo.py", normally we exit without starting the main
404 # loop. The force_interact config variable allows a user to override
405 # this and interact. It is also set by the -i cmd line flag, just
406 # like Python.
407 Global.force_interact = False
408
409 # By default always interact by starting the IPython mainloop.
410 Global.interact = True
411
412 # No GUI integration by default
413 Global.gui = False
414 # Pylab off by default
415 Global.pylab = False
416
417 # Deprecated versions of gui support that used threading, we support
418 # them just for bacwards compatibility as an alternate spelling for
419 # '--gui X'
420 Global.qthread = False
421 Global.q4thread = False
422 Global.wthread = False
423 Global.gthread = False
424
425 def load_file_config(self):
426 if hasattr(self.command_line_config.Global, 'quick'):
427 if self.command_line_config.Global.quick:
428 self.file_config = Config()
429 return
430 super(IPythonApp, self).load_file_config()
431
432 def post_load_file_config(self):
433 if hasattr(self.command_line_config.Global, 'extra_extension'):
434 if not hasattr(self.file_config.Global, 'extensions'):
435 self.file_config.Global.extensions = []
436 self.file_config.Global.extensions.append(
437 self.command_line_config.Global.extra_extension)
438 del self.command_line_config.Global.extra_extension
439
440 def pre_construct(self):
441 config = self.master_config
442
443 if hasattr(config.Global, 'classic'):
444 if config.Global.classic:
445 config.InteractiveShell.cache_size = 0
446 config.PlainTextFormatter.pprint = False
447 config.InteractiveShell.prompt_in1 = '>>> '
448 config.InteractiveShell.prompt_in2 = '... '
449 config.InteractiveShell.prompt_out = ''
450 config.InteractiveShell.separate_in = \
451 config.InteractiveShell.separate_out = \
452 config.InteractiveShell.separate_out2 = ''
453 config.InteractiveShell.colors = 'NoColor'
454 config.InteractiveShell.xmode = 'Plain'
455
456 if hasattr(config.Global, 'nosep'):
457 if config.Global.nosep:
458 config.InteractiveShell.separate_in = \
459 config.InteractiveShell.separate_out = \
460 config.InteractiveShell.separate_out2 = ''
461
462 # if there is code of files to run from the cmd line, don't interact
463 # unless the -i flag (Global.force_interact) is true.
464 code_to_run = config.Global.get('code_to_run','')
465 file_to_run = False
466 if self.extra_args and self.extra_args[0]:
467 file_to_run = True
468 if file_to_run or code_to_run:
469 if not config.Global.force_interact:
470 config.Global.interact = False
471
472 def construct(self):
345 # print self.extra_args
346 if self.extra_args:
347 self.file_to_run = self.extra_args[0]
348 # create the shell
349 self.init_shell()
350 # and draw the banner
351 self.init_banner()
352 # Now a variety of things that happen after the banner is printed.
353 self.init_gui_pylab()
354 self.init_extensions()
355 self.init_code()
356
357 def init_shell(self):
358 """initialize the InteractiveShell instance"""
473 359 # I am a little hesitant to put these into InteractiveShell itself.
474 360 # But that might be the place for them
475 361 sys.path.insert(0, '')
476 362
477 363 # Create an InteractiveShell instance.
478 self.shell = TerminalInteractiveShell.instance(config=self.master_config)
479
480 def post_construct(self):
481 """Do actions after construct, but before starting the app."""
482 config = self.master_config
483
484 364 # shell.display_banner should always be False for the terminal
485 365 # based app, because we call shell.show_banner() by hand below
486 366 # so the banner shows *before* all extension loading stuff.
487 self.shell.display_banner = False
488 if config.Global.display_banner and \
489 config.Global.interact:
490 self.shell.show_banner()
367 self.shell = TerminalInteractiveShell.instance(config=self.config,
368 display_banner=False, profile_dir=self.profile_dir,
369 ipython_dir=self.ipython_dir)
491 370
371 def init_banner(self):
372 """optionally display the banner"""
373 if self.display_banner and self.interact:
374 self.shell.show_banner()
492 375 # Make sure there is a space below the banner.
493 376 if self.log_level <= logging.INFO: print
494 377
495 # Now a variety of things that happen after the banner is printed.
496 self._enable_gui_pylab()
497 self._load_extensions()
498 self._run_exec_lines()
499 self._run_exec_files()
500 self._run_cmd_line_code()
501 378
502 def _enable_gui_pylab(self):
379 def init_gui_pylab(self):
503 380 """Enable GUI event loop integration, taking pylab into account."""
504 Global = self.master_config.Global
505
506 # Select which gui to use
507 if Global.gui:
508 gui = Global.gui
509 # The following are deprecated, but there's likely to be a lot of use
510 # of this form out there, so we might as well support it for now. But
511 # the --gui option above takes precedence.
512 elif Global.wthread:
513 gui = inputhook.GUI_WX
514 elif Global.qthread:
515 gui = inputhook.GUI_QT
516 elif Global.gthread:
517 gui = inputhook.GUI_GTK
518 else:
519 gui = None
381 gui = self.gui
520 382
521 # Using --pylab will also require gui activation, though which toolkit
383 # Using `pylab` will also require gui activation, though which toolkit
522 384 # to use may be chosen automatically based on mpl configuration.
523 if Global.pylab:
385 if self.pylab:
524 386 activate = self.shell.enable_pylab
525 if Global.pylab == 'auto':
387 if self.pylab == 'auto':
526 388 gui = None
527 389 else:
528 gui = Global.pylab
390 gui = self.pylab
529 391 else:
530 392 # Enable only GUI integration, no pylab
531 393 activate = inputhook.enable_gui
532 394
533 if gui or Global.pylab:
395 if gui or self.pylab:
534 396 try:
535 397 self.log.info("Enabling GUI event loop integration, "
536 "toolkit=%s, pylab=%s" % (gui, Global.pylab) )
398 "toolkit=%s, pylab=%s" % (gui, self.pylab) )
537 399 activate(gui)
538 400 except:
539 401 self.log.warn("Error in enabling GUI event loop integration:")
540 402 self.shell.showtraceback()
541 403
542 def _load_extensions(self):
543 """Load all IPython extensions in Global.extensions.
404 def init_extensions(self):
405 """Load all IPython extensions in IPythonApp.extensions.
544 406
545 407 This uses the :meth:`ExtensionManager.load_extensions` to load all
546 the extensions listed in ``self.master_config.Global.extensions``.
408 the extensions listed in ``self.extensions``.
547 409 """
410 if not self.extensions:
411 return
548 412 try:
549 if hasattr(self.master_config.Global, 'extensions'):
550 self.log.debug("Loading IPython extensions...")
551 extensions = self.master_config.Global.extensions
552 for ext in extensions:
553 try:
554 self.log.info("Loading IPython extension: %s" % ext)
555 self.shell.extension_manager.load_extension(ext)
556 except:
557 self.log.warn("Error in loading extension: %s" % ext)
558 self.shell.showtraceback()
413 self.log.debug("Loading IPython extensions...")
414 extensions = self.extensions
415 for ext in extensions:
416 try:
417 self.log.info("Loading IPython extension: %s" % ext)
418 self.shell.extension_manager.load_extension(ext)
419 except:
420 self.log.warn("Error in loading extension: %s" % ext)
421 self.shell.showtraceback()
559 422 except:
560 423 self.log.warn("Unknown error in loading extensions:")
561 424 self.shell.showtraceback()
562 425
426 def init_code(self):
427 """run the pre-flight code, specified via exec_lines"""
428 self._run_exec_lines()
429 self._run_exec_files()
430 self._run_cmd_line_code()
431
563 432 def _run_exec_lines(self):
564 """Run lines of code in Global.exec_lines in the user's namespace."""
433 """Run lines of code in IPythonApp.exec_lines in the user's namespace."""
434 if not self.exec_lines:
435 return
565 436 try:
566 if hasattr(self.master_config.Global, 'exec_lines'):
567 self.log.debug("Running code from Global.exec_lines...")
568 exec_lines = self.master_config.Global.exec_lines
569 for line in exec_lines:
570 try:
571 self.log.info("Running code in user namespace: %s" %
572 line)
573 self.shell.run_cell(line, store_history=False)
574 except:
575 self.log.warn("Error in executing line in user "
576 "namespace: %s" % line)
577 self.shell.showtraceback()
437 self.log.debug("Running code from IPythonApp.exec_lines...")
438 for line in self.exec_lines:
439 try:
440 self.log.info("Running code in user namespace: %s" %
441 line)
442 self.shell.run_cell(line, store_history=False)
443 except:
444 self.log.warn("Error in executing line in user "
445 "namespace: %s" % line)
446 self.shell.showtraceback()
578 447 except:
579 self.log.warn("Unknown error in handling Global.exec_lines:")
448 self.log.warn("Unknown error in handling IPythonApp.exec_lines:")
580 449 self.shell.showtraceback()
581 450
582 451 def _exec_file(self, fname):
583 452 full_filename = filefind(fname, [u'.', self.ipython_dir])
584 453 if os.path.isfile(full_filename):
585 454 if full_filename.endswith(u'.py'):
586 455 self.log.info("Running file in user namespace: %s" %
587 456 full_filename)
588 457 # Ensure that __file__ is always defined to match Python behavior
589 458 self.shell.user_ns['__file__'] = fname
590 459 try:
591 460 self.shell.safe_execfile(full_filename, self.shell.user_ns)
592 461 finally:
593 462 del self.shell.user_ns['__file__']
594 463 elif full_filename.endswith('.ipy'):
595 464 self.log.info("Running file in user namespace: %s" %
596 465 full_filename)
597 466 self.shell.safe_execfile_ipy(full_filename)
598 467 else:
599 468 self.log.warn("File does not have a .py or .ipy extension: <%s>"
600 469 % full_filename)
470
601 471 def _run_exec_files(self):
472 """Run files from IPythonApp.exec_files"""
473 if not self.exec_files:
474 return
475
476 self.log.debug("Running files in IPythonApp.exec_files...")
602 477 try:
603 if hasattr(self.master_config.Global, 'exec_files'):
604 self.log.debug("Running files in Global.exec_files...")
605 exec_files = self.master_config.Global.exec_files
606 for fname in exec_files:
607 self._exec_file(fname)
478 for fname in self.exec_files:
479 self._exec_file(fname)
608 480 except:
609 self.log.warn("Unknown error in handling Global.exec_files:")
481 self.log.warn("Unknown error in handling IPythonApp.exec_files:")
610 482 self.shell.showtraceback()
611 483
612 484 def _run_cmd_line_code(self):
613 if hasattr(self.master_config.Global, 'code_to_run'):
614 line = self.master_config.Global.code_to_run
485 """Run code or file specified at the command-line"""
486 if self.code_to_run:
487 line = self.code_to_run
615 488 try:
616 self.log.info("Running code given at command line (-c): %s" %
489 self.log.info("Running code given at command line (c=): %s" %
617 490 line)
618 491 self.shell.run_cell(line, store_history=False)
619 492 except:
620 493 self.log.warn("Error in executing line in user namespace: %s" %
621 494 line)
622 495 self.shell.showtraceback()
623 return
496
624 497 # Like Python itself, ignore the second if the first of these is present
625 try:
626 fname = self.extra_args[0]
627 except:
628 pass
629 else:
498 elif self.file_to_run:
499 fname = self.file_to_run
630 500 try:
631 501 self._exec_file(fname)
632 502 except:
633 503 self.log.warn("Error in executing file in user namespace: %s" %
634 504 fname)
635 505 self.shell.showtraceback()
636 506
637 def start_app(self):
638 if not getattr(self.master_config.Global, 'ignore_old_config', False):
639 check_for_old_config(self.ipython_dir)
640 if self.master_config.Global.interact:
507
508 def start(self):
509 # perform any prexec steps:
510 if self.interact:
641 511 self.log.debug("Starting IPython's mainloop...")
642 512 self.shell.mainloop()
643 513 else:
644 self.log.debug("IPython not interactive, start_app is no-op...")
514 self.log.debug("IPython not interactive...")
645 515
646 516
647 517 def load_default_config(ipython_dir=None):
648 518 """Load the default config file from the default ipython_dir.
649 519
650 520 This is useful for embedded shells.
651 521 """
652 522 if ipython_dir is None:
653 523 ipython_dir = get_ipython_dir()
654 cl = PyFileConfigLoader(default_config_file_name, ipython_dir)
524 profile_dir = os.path.join(ipython_dir, 'profile_default')
525 cl = PyFileConfigLoader(default_config_file_name, profile_dir)
655 526 config = cl.load_config()
656 527 return config
657 528
658 529
659 530 def launch_new_instance():
660 531 """Create and run a full blown IPython instance"""
661 532 app = IPythonApp()
533 app.initialize()
534 # print app.config
535 # print app.profile_dir.location
662 536 app.start()
663 537
664 538
665 539 if __name__ == '__main__':
666 540 launch_new_instance()
@@ -1,442 +1,440
1 1 #!/usr/bin/env python
2 2 """Module for interactively running scripts.
3 3
4 4 This module implements classes for interactively running scripts written for
5 5 any system with a prompt which can be matched by a regexp suitable for
6 6 pexpect. It can be used to run as if they had been typed up interactively, an
7 7 arbitrary series of commands for the target system.
8 8
9 9 The module includes classes ready for IPython (with the default prompts),
10 10 plain Python and SAGE, but making a new one is trivial. To see how to use it,
11 11 simply run the module as a script:
12 12
13 13 ./irunner.py --help
14 14
15 15
16 16 This is an extension of Ken Schutte <kschutte-AT-csail.mit.edu>'s script
17 17 contributed on the ipython-user list:
18 18
19 19 http://scipy.net/pipermail/ipython-user/2006-May/001705.html
20 20
21 21
22 22 NOTES:
23 23
24 24 - This module requires pexpect, available in most linux distros, or which can
25 25 be downloaded from
26 26
27 27 http://pexpect.sourceforge.net
28 28
29 29 - Because pexpect only works under Unix or Windows-Cygwin, this has the same
30 30 limitations. This means that it will NOT work under native windows Python.
31 31 """
32 32
33 33 # Stdlib imports
34 34 import optparse
35 35 import os
36 36 import sys
37 37
38 38 # Third-party modules.
39 39 import pexpect
40 40
41 41 # Global usage strings, to avoid indentation issues when typing it below.
42 42 USAGE = """
43 43 Interactive script runner, type: %s
44 44
45 45 runner [opts] script_name
46 46 """
47 47
48 48 def pexpect_monkeypatch():
49 49 """Patch pexpect to prevent unhandled exceptions at VM teardown.
50 50
51 51 Calling this function will monkeypatch the pexpect.spawn class and modify
52 52 its __del__ method to make it more robust in the face of failures that can
53 53 occur if it is called when the Python VM is shutting down.
54 54
55 55 Since Python may fire __del__ methods arbitrarily late, it's possible for
56 56 them to execute during the teardown of the Python VM itself. At this
57 57 point, various builtin modules have been reset to None. Thus, the call to
58 58 self.close() will trigger an exception because it tries to call os.close(),
59 59 and os is now None.
60 60 """
61 61
62 62 if pexpect.__version__[:3] >= '2.2':
63 63 # No need to patch, fix is already the upstream version.
64 64 return
65 65
66 66 def __del__(self):
67 67 """This makes sure that no system resources are left open.
68 68 Python only garbage collects Python objects. OS file descriptors
69 69 are not Python objects, so they must be handled explicitly.
70 70 If the child file descriptor was opened outside of this class
71 71 (passed to the constructor) then this does not close it.
72 72 """
73 73 if not self.closed:
74 74 try:
75 75 self.close()
76 76 except AttributeError:
77 77 pass
78 78
79 79 pexpect.spawn.__del__ = __del__
80 80
81 81 pexpect_monkeypatch()
82 82
83 83 # The generic runner class
84 84 class InteractiveRunner(object):
85 85 """Class to run a sequence of commands through an interactive program."""
86 86
87 87 def __init__(self,program,prompts,args=None,out=sys.stdout,echo=True):
88 88 """Construct a runner.
89 89
90 90 Inputs:
91 91
92 92 - program: command to execute the given program.
93 93
94 94 - prompts: a list of patterns to match as valid prompts, in the
95 95 format used by pexpect. This basically means that it can be either
96 96 a string (to be compiled as a regular expression) or a list of such
97 97 (it must be a true list, as pexpect does type checks).
98 98
99 99 If more than one prompt is given, the first is treated as the main
100 100 program prompt and the others as 'continuation' prompts, like
101 101 python's. This means that blank lines in the input source are
102 102 ommitted when the first prompt is matched, but are NOT ommitted when
103 103 the continuation one matches, since this is how python signals the
104 104 end of multiline input interactively.
105 105
106 106 Optional inputs:
107 107
108 108 - args(None): optional list of strings to pass as arguments to the
109 109 child program.
110 110
111 111 - out(sys.stdout): if given, an output stream to be used when writing
112 112 output. The only requirement is that it must have a .write() method.
113 113
114 114 Public members not parameterized in the constructor:
115 115
116 116 - delaybeforesend(0): Newer versions of pexpect have a delay before
117 117 sending each new input. For our purposes here, it's typically best
118 118 to just set this to zero, but if you encounter reliability problems
119 119 or want an interactive run to pause briefly at each prompt, just
120 120 increase this value (it is measured in seconds). Note that this
121 121 variable is not honored at all by older versions of pexpect.
122 122 """
123 123
124 124 self.program = program
125 125 self.prompts = prompts
126 126 if args is None: args = []
127 127 self.args = args
128 128 self.out = out
129 129 self.echo = echo
130 130 # Other public members which we don't make as parameters, but which
131 131 # users may occasionally want to tweak
132 132 self.delaybeforesend = 0
133 133
134 134 # Create child process and hold on to it so we don't have to re-create
135 135 # for every single execution call
136 136 c = self.child = pexpect.spawn(self.program,self.args,timeout=None)
137 137 c.delaybeforesend = self.delaybeforesend
138 138 # pexpect hard-codes the terminal size as (24,80) (rows,columns).
139 139 # This causes problems because any line longer than 80 characters gets
140 140 # completely overwrapped on the printed outptut (even though
141 141 # internally the code runs fine). We reset this to 99 rows X 200
142 142 # columns (arbitrarily chosen), which should avoid problems in all
143 143 # reasonable cases.
144 144 c.setwinsize(99,200)
145 145
146 146 def close(self):
147 147 """close child process"""
148 148
149 149 self.child.close()
150 150
151 151 def run_file(self,fname,interact=False,get_output=False):
152 152 """Run the given file interactively.
153 153
154 154 Inputs:
155 155
156 156 -fname: name of the file to execute.
157 157
158 158 See the run_source docstring for the meaning of the optional
159 159 arguments."""
160 160
161 161 fobj = open(fname,'r')
162 162 try:
163 163 out = self.run_source(fobj,interact,get_output)
164 164 finally:
165 165 fobj.close()
166 166 if get_output:
167 167 return out
168 168
169 169 def run_source(self,source,interact=False,get_output=False):
170 170 """Run the given source code interactively.
171 171
172 172 Inputs:
173 173
174 174 - source: a string of code to be executed, or an open file object we
175 175 can iterate over.
176 176
177 177 Optional inputs:
178 178
179 179 - interact(False): if true, start to interact with the running
180 180 program at the end of the script. Otherwise, just exit.
181 181
182 182 - get_output(False): if true, capture the output of the child process
183 183 (filtering the input commands out) and return it as a string.
184 184
185 185 Returns:
186 186 A string containing the process output, but only if requested.
187 187 """
188 188
189 189 # if the source is a string, chop it up in lines so we can iterate
190 190 # over it just as if it were an open file.
191 191 if not isinstance(source,file):
192 192 source = source.splitlines(True)
193 193
194 194 if self.echo:
195 195 # normalize all strings we write to use the native OS line
196 196 # separators.
197 197 linesep = os.linesep
198 198 stdwrite = self.out.write
199 199 write = lambda s: stdwrite(s.replace('\r\n',linesep))
200 200 else:
201 201 # Quiet mode, all writes are no-ops
202 202 write = lambda s: None
203 203
204 204 c = self.child
205 205 prompts = c.compile_pattern_list(self.prompts)
206 206 prompt_idx = c.expect_list(prompts)
207 207
208 208 # Flag whether the script ends normally or not, to know whether we can
209 209 # do anything further with the underlying process.
210 210 end_normal = True
211 211
212 212 # If the output was requested, store it in a list for return at the end
213 213 if get_output:
214 214 output = []
215 215 store_output = output.append
216 216
217 217 for cmd in source:
218 218 # skip blank lines for all matches to the 'main' prompt, while the
219 219 # secondary prompts do not
220 220 if prompt_idx==0 and \
221 221 (cmd.isspace() or cmd.lstrip().startswith('#')):
222 222 write(cmd)
223 223 continue
224 224
225 225 # write('AFTER: '+c.after) # dbg
226 226 write(c.after)
227 227 c.send(cmd)
228 228 try:
229 229 prompt_idx = c.expect_list(prompts)
230 230 except pexpect.EOF:
231 231 # this will happen if the child dies unexpectedly
232 232 write(c.before)
233 233 end_normal = False
234 234 break
235 235
236 236 write(c.before)
237 237
238 238 # With an echoing process, the output we get in c.before contains
239 239 # the command sent, a newline, and then the actual process output
240 240 if get_output:
241 241 store_output(c.before[len(cmd+'\n'):])
242 242 #write('CMD: <<%s>>' % cmd) # dbg
243 243 #write('OUTPUT: <<%s>>' % output[-1]) # dbg
244 244
245 245 self.out.flush()
246 246 if end_normal:
247 247 if interact:
248 248 c.send('\n')
249 249 print '<< Starting interactive mode >>',
250 250 try:
251 251 c.interact()
252 252 except OSError:
253 253 # This is what fires when the child stops. Simply print a
254 254 # newline so the system prompt is aligned. The extra
255 255 # space is there to make sure it gets printed, otherwise
256 256 # OS buffering sometimes just suppresses it.
257 257 write(' \n')
258 258 self.out.flush()
259 259 else:
260 260 if interact:
261 261 e="Further interaction is not possible: child process is dead."
262 262 print >> sys.stderr, e
263 263
264 264 # Leave the child ready for more input later on, otherwise select just
265 265 # hangs on the second invocation.
266 266 if c.isalive():
267 267 c.send('\n')
268 268
269 269 # Return any requested output
270 270 if get_output:
271 271 return ''.join(output)
272 272
273 273 def main(self,argv=None):
274 274 """Run as a command-line script."""
275 275
276 276 parser = optparse.OptionParser(usage=USAGE % self.__class__.__name__)
277 277 newopt = parser.add_option
278 278 newopt('-i','--interact',action='store_true',default=False,
279 279 help='Interact with the program after the script is run.')
280 280
281 281 opts,args = parser.parse_args(argv)
282 282
283 283 if len(args) != 1:
284 284 print >> sys.stderr,"You must supply exactly one file to run."
285 285 sys.exit(1)
286 286
287 287 self.run_file(args[0],opts.interact)
288 288
289 289
290 290 # Specific runners for particular programs
291 291 class IPythonRunner(InteractiveRunner):
292 292 """Interactive IPython runner.
293 293
294 294 This initalizes IPython in 'nocolor' mode for simplicity. This lets us
295 295 avoid having to write a regexp that matches ANSI sequences, though pexpect
296 296 does support them. If anyone contributes patches for ANSI color support,
297 297 they will be welcome.
298 298
299 299 It also sets the prompts manually, since the prompt regexps for
300 300 pexpect need to be matched to the actual prompts, so user-customized
301 301 prompts would break this.
302 302 """
303 303
304 304 def __init__(self,program = 'ipython',args=None,out=sys.stdout,echo=True):
305 305 """New runner, optionally passing the ipython command to use."""
306 306
307 args0 = ['--colors','NoColor',
308 '-pi1','In [\\#]: ',
309 '-pi2',' .\\D.: ',
307 args0 = ['colors=NoColor',
310 308 '--no-term-title',
311 309 '--no-autoindent']
312 310 if args is None: args = args0
313 311 else: args = args0 + args
314 312 prompts = [r'In \[\d+\]: ',r' \.*: ']
315 313 InteractiveRunner.__init__(self,program,prompts,args,out,echo)
316 314
317 315
318 316 class PythonRunner(InteractiveRunner):
319 317 """Interactive Python runner."""
320 318
321 319 def __init__(self,program='python',args=None,out=sys.stdout,echo=True):
322 320 """New runner, optionally passing the python command to use."""
323 321
324 322 prompts = [r'>>> ',r'\.\.\. ']
325 323 InteractiveRunner.__init__(self,program,prompts,args,out,echo)
326 324
327 325
328 326 class SAGERunner(InteractiveRunner):
329 327 """Interactive SAGE runner.
330 328
331 329 WARNING: this runner only works if you manually configure your SAGE copy
332 330 to use 'colors NoColor' in the ipythonrc config file, since currently the
333 331 prompt matching regexp does not identify color sequences."""
334 332
335 333 def __init__(self,program='sage',args=None,out=sys.stdout,echo=True):
336 334 """New runner, optionally passing the sage command to use."""
337 335
338 336 prompts = ['sage: ',r'\s*\.\.\. ']
339 337 InteractiveRunner.__init__(self,program,prompts,args,out,echo)
340 338
341 339
342 340 class RunnerFactory(object):
343 341 """Code runner factory.
344 342
345 343 This class provides an IPython code runner, but enforces that only one
346 344 runner is ever instantiated. The runner is created based on the extension
347 345 of the first file to run, and it raises an exception if a runner is later
348 346 requested for a different extension type.
349 347
350 348 This ensures that we don't generate example files for doctest with a mix of
351 349 python and ipython syntax.
352 350 """
353 351
354 352 def __init__(self,out=sys.stdout):
355 353 """Instantiate a code runner."""
356 354
357 355 self.out = out
358 356 self.runner = None
359 357 self.runnerClass = None
360 358
361 359 def _makeRunner(self,runnerClass):
362 360 self.runnerClass = runnerClass
363 361 self.runner = runnerClass(out=self.out)
364 362 return self.runner
365 363
366 364 def __call__(self,fname):
367 365 """Return a runner for the given filename."""
368 366
369 367 if fname.endswith('.py'):
370 368 runnerClass = PythonRunner
371 369 elif fname.endswith('.ipy'):
372 370 runnerClass = IPythonRunner
373 371 else:
374 372 raise ValueError('Unknown file type for Runner: %r' % fname)
375 373
376 374 if self.runner is None:
377 375 return self._makeRunner(runnerClass)
378 376 else:
379 377 if runnerClass==self.runnerClass:
380 378 return self.runner
381 379 else:
382 380 e='A runner of type %r can not run file %r' % \
383 381 (self.runnerClass,fname)
384 382 raise ValueError(e)
385 383
386 384
387 385 # Global usage string, to avoid indentation issues if typed in a function def.
388 386 MAIN_USAGE = """
389 387 %prog [options] file_to_run
390 388
391 389 This is an interface to the various interactive runners available in this
392 390 module. If you want to pass specific options to one of the runners, you need
393 391 to first terminate the main options with a '--', and then provide the runner's
394 392 options. For example:
395 393
396 394 irunner.py --python -- --help
397 395
398 396 will pass --help to the python runner. Similarly,
399 397
400 398 irunner.py --ipython -- --interact script.ipy
401 399
402 400 will run the script.ipy file under the IPython runner, and then will start to
403 401 interact with IPython at the end of the script (instead of exiting).
404 402
405 403 The already implemented runners are listed below; adding one for a new program
406 404 is a trivial task, see the source for examples.
407 405
408 406 WARNING: the SAGE runner only works if you manually configure your SAGE copy
409 407 to use 'colors NoColor' in the ipythonrc config file, since currently the
410 408 prompt matching regexp does not identify color sequences.
411 409 """
412 410
413 411 def main():
414 412 """Run as a command-line script."""
415 413
416 414 parser = optparse.OptionParser(usage=MAIN_USAGE)
417 415 newopt = parser.add_option
418 416 parser.set_defaults(mode='ipython')
419 417 newopt('--ipython',action='store_const',dest='mode',const='ipython',
420 418 help='IPython interactive runner (default).')
421 419 newopt('--python',action='store_const',dest='mode',const='python',
422 420 help='Python interactive runner.')
423 421 newopt('--sage',action='store_const',dest='mode',const='sage',
424 422 help='SAGE interactive runner.')
425 423
426 424 opts,args = parser.parse_args()
427 425 runners = dict(ipython=IPythonRunner,
428 426 python=PythonRunner,
429 427 sage=SAGERunner)
430 428
431 429 try:
432 430 ext = os.path.splitext(args[0])[-1]
433 431 except IndexError:
434 432 ext = ''
435 433 modes = {'.ipy':'ipython',
436 434 '.py':'python',
437 435 '.sage':'sage'}
438 436 mode = modes.get(ext,opts.mode)
439 437 runners[mode]().main(args)
440 438
441 439 if __name__ == '__main__':
442 440 main()
@@ -1,280 +1,280
1 1 """Generic testing tools that do NOT depend on Twisted.
2 2
3 3 In particular, this module exposes a set of top-level assert* functions that
4 4 can be used in place of nose.tools.assert* in method generators (the ones in
5 5 nose can not, at least as of nose 0.10.4).
6 6
7 7 Note: our testing package contains testing.util, which does depend on Twisted
8 8 and provides utilities for tests that manage Deferreds. All testing support
9 9 tools that only depend on nose, IPython or the standard library should go here
10 10 instead.
11 11
12 12
13 13 Authors
14 14 -------
15 15 - Fernando Perez <Fernando.Perez@berkeley.edu>
16 16 """
17 17
18 18 from __future__ import absolute_import
19 19
20 20 #-----------------------------------------------------------------------------
21 21 # Copyright (C) 2009 The IPython Development Team
22 22 #
23 23 # Distributed under the terms of the BSD License. The full license is in
24 24 # the file COPYING, distributed as part of this software.
25 25 #-----------------------------------------------------------------------------
26 26
27 27 #-----------------------------------------------------------------------------
28 28 # Imports
29 29 #-----------------------------------------------------------------------------
30 30
31 31 import os
32 32 import re
33 33 import sys
34 34
35 35 try:
36 36 # These tools are used by parts of the runtime, so we make the nose
37 37 # dependency optional at this point. Nose is a hard dependency to run the
38 38 # test suite, but NOT to use ipython itself.
39 39 import nose.tools as nt
40 40 has_nose = True
41 41 except ImportError:
42 42 has_nose = False
43 43
44 44 from IPython.config.loader import Config
45 45 from IPython.utils.process import find_cmd, getoutputerror
46 46 from IPython.utils.text import list_strings
47 47 from IPython.utils.io import temp_pyfile
48 48
49 49 from . import decorators as dec
50 50 from . import skipdoctest
51 51
52 52 #-----------------------------------------------------------------------------
53 53 # Globals
54 54 #-----------------------------------------------------------------------------
55 55
56 56 # Make a bunch of nose.tools assert wrappers that can be used in test
57 57 # generators. This will expose an assert* function for each one in nose.tools.
58 58
59 59 _tpl = """
60 60 def %(name)s(*a,**kw):
61 61 return nt.%(name)s(*a,**kw)
62 62 """
63 63
64 64 if has_nose:
65 65 for _x in [a for a in dir(nt) if a.startswith('assert')]:
66 66 exec _tpl % dict(name=_x)
67 67
68 68 #-----------------------------------------------------------------------------
69 69 # Functions and classes
70 70 #-----------------------------------------------------------------------------
71 71
72 72 # The docstring for full_path doctests differently on win32 (different path
73 73 # separator) so just skip the doctest there. The example remains informative.
74 74 doctest_deco = skipdoctest.skip_doctest if sys.platform == 'win32' else dec.null_deco
75 75
76 76 @doctest_deco
77 77 def full_path(startPath,files):
78 78 """Make full paths for all the listed files, based on startPath.
79 79
80 80 Only the base part of startPath is kept, since this routine is typically
81 81 used with a script's __file__ variable as startPath. The base of startPath
82 82 is then prepended to all the listed files, forming the output list.
83 83
84 84 Parameters
85 85 ----------
86 86 startPath : string
87 87 Initial path to use as the base for the results. This path is split
88 88 using os.path.split() and only its first component is kept.
89 89
90 90 files : string or list
91 91 One or more files.
92 92
93 93 Examples
94 94 --------
95 95
96 96 >>> full_path('/foo/bar.py',['a.txt','b.txt'])
97 97 ['/foo/a.txt', '/foo/b.txt']
98 98
99 99 >>> full_path('/foo',['a.txt','b.txt'])
100 100 ['/a.txt', '/b.txt']
101 101
102 102 If a single file is given, the output is still a list:
103 103 >>> full_path('/foo','a.txt')
104 104 ['/a.txt']
105 105 """
106 106
107 107 files = list_strings(files)
108 108 base = os.path.split(startPath)[0]
109 109 return [ os.path.join(base,f) for f in files ]
110 110
111 111
112 112 def parse_test_output(txt):
113 113 """Parse the output of a test run and return errors, failures.
114 114
115 115 Parameters
116 116 ----------
117 117 txt : str
118 118 Text output of a test run, assumed to contain a line of one of the
119 119 following forms::
120 120 'FAILED (errors=1)'
121 121 'FAILED (failures=1)'
122 122 'FAILED (errors=1, failures=1)'
123 123
124 124 Returns
125 125 -------
126 126 nerr, nfail: number of errors and failures.
127 127 """
128 128
129 129 err_m = re.search(r'^FAILED \(errors=(\d+)\)', txt, re.MULTILINE)
130 130 if err_m:
131 131 nerr = int(err_m.group(1))
132 132 nfail = 0
133 133 return nerr, nfail
134 134
135 135 fail_m = re.search(r'^FAILED \(failures=(\d+)\)', txt, re.MULTILINE)
136 136 if fail_m:
137 137 nerr = 0
138 138 nfail = int(fail_m.group(1))
139 139 return nerr, nfail
140 140
141 141 both_m = re.search(r'^FAILED \(errors=(\d+), failures=(\d+)\)', txt,
142 142 re.MULTILINE)
143 143 if both_m:
144 144 nerr = int(both_m.group(1))
145 145 nfail = int(both_m.group(2))
146 146 return nerr, nfail
147 147
148 148 # If the input didn't match any of these forms, assume no error/failures
149 149 return 0, 0
150 150
151 151
152 152 # So nose doesn't think this is a test
153 153 parse_test_output.__test__ = False
154 154
155 155
156 156 def default_argv():
157 157 """Return a valid default argv for creating testing instances of ipython"""
158 158
159 159 return ['--quick', # so no config file is loaded
160 160 # Other defaults to minimize side effects on stdout
161 '--colors=NoColor', '--no-term-title','--no-banner',
162 '--autocall=0']
161 'colors=NoColor', '--no-term-title','--no-banner',
162 'autocall=0']
163 163
164 164
165 165 def default_config():
166 166 """Return a config object with good defaults for testing."""
167 167 config = Config()
168 168 config.TerminalInteractiveShell.colors = 'NoColor'
169 169 config.TerminalTerminalInteractiveShell.term_title = False,
170 170 config.TerminalInteractiveShell.autocall = 0
171 171 config.HistoryManager.hist_file = u'test_hist.sqlite'
172 172 config.HistoryManager.db_cache_size = 10000
173 173 return config
174 174
175 175
176 176 def ipexec(fname, options=None):
177 177 """Utility to call 'ipython filename'.
178 178
179 179 Starts IPython witha minimal and safe configuration to make startup as fast
180 180 as possible.
181 181
182 182 Note that this starts IPython in a subprocess!
183 183
184 184 Parameters
185 185 ----------
186 186 fname : str
187 187 Name of file to be executed (should have .py or .ipy extension).
188 188
189 189 options : optional, list
190 190 Extra command-line flags to be passed to IPython.
191 191
192 192 Returns
193 193 -------
194 194 (stdout, stderr) of ipython subprocess.
195 195 """
196 196 if options is None: options = []
197 197
198 198 # For these subprocess calls, eliminate all prompt printing so we only see
199 199 # output from script execution
200 prompt_opts = ['--prompt-in1=""', '--prompt-in2=""', '--prompt-out=""']
200 prompt_opts = ['pi1=""', 'pi2=""', 'po=""']
201 201 cmdargs = ' '.join(default_argv() + prompt_opts + options)
202 202
203 203 _ip = get_ipython()
204 204 test_dir = os.path.dirname(__file__)
205 205
206 206 ipython_cmd = find_cmd('ipython')
207 207 # Absolute path for filename
208 208 full_fname = os.path.join(test_dir, fname)
209 209 full_cmd = '%s %s %s' % (ipython_cmd, cmdargs, full_fname)
210 210 #print >> sys.stderr, 'FULL CMD:', full_cmd # dbg
211 211 return getoutputerror(full_cmd)
212 212
213 213
214 214 def ipexec_validate(fname, expected_out, expected_err='',
215 215 options=None):
216 216 """Utility to call 'ipython filename' and validate output/error.
217 217
218 218 This function raises an AssertionError if the validation fails.
219 219
220 220 Note that this starts IPython in a subprocess!
221 221
222 222 Parameters
223 223 ----------
224 224 fname : str
225 225 Name of the file to be executed (should have .py or .ipy extension).
226 226
227 227 expected_out : str
228 228 Expected stdout of the process.
229 229
230 230 expected_err : optional, str
231 231 Expected stderr of the process.
232 232
233 233 options : optional, list
234 234 Extra command-line flags to be passed to IPython.
235 235
236 236 Returns
237 237 -------
238 238 None
239 239 """
240 240
241 241 import nose.tools as nt
242 242
243 243 out, err = ipexec(fname)
244 244 #print 'OUT', out # dbg
245 245 #print 'ERR', err # dbg
246 246 # If there are any errors, we must check those befor stdout, as they may be
247 247 # more informative than simply having an empty stdout.
248 248 if err:
249 249 if expected_err:
250 250 nt.assert_equals(err.strip(), expected_err.strip())
251 251 else:
252 252 raise ValueError('Running file %r produced error: %r' %
253 253 (fname, err))
254 254 # If no errors or output on stderr was expected, match stdout
255 255 nt.assert_equals(out.strip(), expected_out.strip())
256 256
257 257
258 258 class TempFileMixin(object):
259 259 """Utility class to create temporary Python/IPython files.
260 260
261 261 Meant as a mixin class for test cases."""
262 262
263 263 def mktmp(self, src, ext='.py'):
264 264 """Make a valid python temp file."""
265 265 fname, f = temp_pyfile(src, ext)
266 266 self.tmpfile = f
267 267 self.fname = fname
268 268
269 269 def tearDown(self):
270 270 if hasattr(self, 'tmpfile'):
271 271 # If the tmpfile wasn't made because of skipped tests, like in
272 272 # win32, there's nothing to cleanup.
273 273 self.tmpfile.close()
274 274 try:
275 275 os.unlink(self.fname)
276 276 except:
277 277 # On Windows, even though we close the file, we still can't
278 278 # delete it. I have no clue why
279 279 pass
280 280
General Comments 0
You need to be logged in to leave comments. Login now