##// END OF EJS Templates
Merge pull request #2301 from takluyver/ast-transfomers...
Thomas Kluyver -
r8813:a7cc5832 merge
parent child Browse files
Show More
@@ -1,788 +1,788 b''
1 1 """ History related magics and functionality """
2 2 #-----------------------------------------------------------------------------
3 3 # Copyright (C) 2010-2011 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 try:
21 21 import sqlite3
22 22 except ImportError:
23 23 sqlite3 = None
24 24 import threading
25 25
26 26 # Our own packages
27 27 from IPython.config.configurable import Configurable
28 28 from IPython.external.decorator import decorator
29 29 from IPython.utils.path import locate_profile
30 30 from IPython.utils.traitlets import (
31 31 Any, Bool, Dict, Instance, Integer, List, Unicode, TraitError,
32 32 )
33 33 from IPython.utils.warn import warn
34 34
35 35 #-----------------------------------------------------------------------------
36 36 # Classes and functions
37 37 #-----------------------------------------------------------------------------
38 38
39 39 class DummyDB(object):
40 40 """Dummy DB that will act as a black hole for history.
41 41
42 42 Only used in the absence of sqlite"""
43 43 def execute(*args, **kwargs):
44 44 return []
45 45
46 46 def commit(self, *args, **kwargs):
47 47 pass
48 48
49 49 def __enter__(self, *args, **kwargs):
50 50 pass
51 51
52 52 def __exit__(self, *args, **kwargs):
53 53 pass
54 54
55 55
56 56 @decorator
57 57 def needs_sqlite(f, self, *a, **kw):
58 58 """return an empty list in the absence of sqlite"""
59 59 if sqlite3 is None or not self.enabled:
60 60 return []
61 61 else:
62 62 return f(self, *a, **kw)
63 63
64 64
65 65 if sqlite3 is not None:
66 66 DatabaseError = sqlite3.DatabaseError
67 67 else:
68 68 class DatabaseError(Exception):
69 69 "Dummy exception when sqlite could not be imported. Should never occur."
70 70
71 71 @decorator
72 72 def catch_corrupt_db(f, self, *a, **kw):
73 73 """A decorator which wraps HistoryAccessor method calls to catch errors from
74 74 a corrupt SQLite database, move the old database out of the way, and create
75 75 a new one.
76 76 """
77 77 try:
78 78 return f(self, *a, **kw)
79 79 except DatabaseError:
80 80 if os.path.isfile(self.hist_file):
81 81 # Try to move the file out of the way
82 82 base,ext = os.path.splitext(self.hist_file)
83 83 newpath = base + '-corrupt' + ext
84 84 os.rename(self.hist_file, newpath)
85 85 self.init_db()
86 86 print("ERROR! History file wasn't a valid SQLite database.",
87 87 "It was moved to %s" % newpath, "and a new file created.")
88 88 return []
89 89
90 90 else:
91 91 # The hist_file is probably :memory: or something else.
92 92 raise
93 93
94 94
95 95
96 96 class HistoryAccessor(Configurable):
97 97 """Access the history database without adding to it.
98 98
99 99 This is intended for use by standalone history tools. IPython shells use
100 100 HistoryManager, below, which is a subclass of this."""
101 101
102 102 # String holding the path to the history file
103 103 hist_file = Unicode(config=True,
104 104 help="""Path to file to use for SQLite history database.
105 105
106 106 By default, IPython will put the history database in the IPython
107 107 profile directory. If you would rather share one history among
108 108 profiles, you can set this value in each, so that they are consistent.
109 109
110 110 Due to an issue with fcntl, SQLite is known to misbehave on some NFS
111 111 mounts. If you see IPython hanging, try setting this to something on a
112 112 local disk, e.g::
113 113
114 114 ipython --HistoryManager.hist_file=/tmp/ipython_hist.sqlite
115 115
116 116 """)
117 117
118 118 enabled = Bool(True, config=True,
119 119 help="""enable the SQLite history
120 120
121 121 set enabled=False to disable the SQLite history,
122 122 in which case there will be no stored history, no SQLite connection,
123 123 and no background saving thread. This may be necessary in some
124 124 threaded environments where IPython is embedded.
125 125 """
126 126 )
127 127
128 128 connection_options = Dict(config=True,
129 129 help="""Options for configuring the SQLite connection
130 130
131 131 These options are passed as keyword args to sqlite3.connect
132 132 when establishing database conenctions.
133 133 """
134 134 )
135 135
136 136 # The SQLite database
137 137 db = Any()
138 138 def _db_changed(self, name, old, new):
139 139 """validate the db, since it can be an Instance of two different types"""
140 140 connection_types = (DummyDB,)
141 141 if sqlite3 is not None:
142 142 connection_types = (DummyDB, sqlite3.Connection)
143 143 if not isinstance(new, connection_types):
144 144 msg = "%s.db must be sqlite3 Connection or DummyDB, not %r" % \
145 145 (self.__class__.__name__, new)
146 146 raise TraitError(msg)
147 147
148 148 def __init__(self, profile='default', hist_file=u'', config=None, **traits):
149 149 """Create a new history accessor.
150 150
151 151 Parameters
152 152 ----------
153 153 profile : str
154 154 The name of the profile from which to open history.
155 155 hist_file : str
156 156 Path to an SQLite history database stored by IPython. If specified,
157 157 hist_file overrides profile.
158 158 config :
159 159 Config object. hist_file can also be set through this.
160 160 """
161 161 # We need a pointer back to the shell for various tasks.
162 162 super(HistoryAccessor, self).__init__(config=config, **traits)
163 163 # defer setting hist_file from kwarg until after init,
164 164 # otherwise the default kwarg value would clobber any value
165 165 # set by config
166 166 if hist_file:
167 167 self.hist_file = hist_file
168 168
169 169 if self.hist_file == u'':
170 170 # No one has set the hist_file, yet.
171 171 self.hist_file = self._get_hist_file_name(profile)
172 172
173 173 if sqlite3 is None and self.enabled:
174 warn("IPython History requires SQLite, your history will not be saved\n")
174 warn("IPython History requires SQLite, your history will not be saved")
175 175 self.enabled = False
176 176
177 177 self.init_db()
178 178
179 179 def _get_hist_file_name(self, profile='default'):
180 180 """Find the history file for the given profile name.
181 181
182 182 This is overridden by the HistoryManager subclass, to use the shell's
183 183 active profile.
184 184
185 185 Parameters
186 186 ----------
187 187 profile : str
188 188 The name of a profile which has a history file.
189 189 """
190 190 return os.path.join(locate_profile(profile), 'history.sqlite')
191 191
192 192 @catch_corrupt_db
193 193 def init_db(self):
194 194 """Connect to the database, and create tables if necessary."""
195 195 if not self.enabled:
196 196 self.db = DummyDB()
197 197 return
198 198
199 199 # use detect_types so that timestamps return datetime objects
200 200 kwargs = dict(detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
201 201 kwargs.update(self.connection_options)
202 202 self.db = sqlite3.connect(self.hist_file, **kwargs)
203 203 self.db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer
204 204 primary key autoincrement, start timestamp,
205 205 end timestamp, num_cmds integer, remark text)""")
206 206 self.db.execute("""CREATE TABLE IF NOT EXISTS history
207 207 (session integer, line integer, source text, source_raw text,
208 208 PRIMARY KEY (session, line))""")
209 209 # Output history is optional, but ensure the table's there so it can be
210 210 # enabled later.
211 211 self.db.execute("""CREATE TABLE IF NOT EXISTS output_history
212 212 (session integer, line integer, output text,
213 213 PRIMARY KEY (session, line))""")
214 214 self.db.commit()
215 215
216 216 def writeout_cache(self):
217 217 """Overridden by HistoryManager to dump the cache before certain
218 218 database lookups."""
219 219 pass
220 220
221 221 ## -------------------------------
222 222 ## Methods for retrieving history:
223 223 ## -------------------------------
224 224 def _run_sql(self, sql, params, raw=True, output=False):
225 225 """Prepares and runs an SQL query for the history database.
226 226
227 227 Parameters
228 228 ----------
229 229 sql : str
230 230 Any filtering expressions to go after SELECT ... FROM ...
231 231 params : tuple
232 232 Parameters passed to the SQL query (to replace "?")
233 233 raw, output : bool
234 234 See :meth:`get_range`
235 235
236 236 Returns
237 237 -------
238 238 Tuples as :meth:`get_range`
239 239 """
240 240 toget = 'source_raw' if raw else 'source'
241 241 sqlfrom = "history"
242 242 if output:
243 243 sqlfrom = "history LEFT JOIN output_history USING (session, line)"
244 244 toget = "history.%s, output_history.output" % toget
245 245 cur = self.db.execute("SELECT session, line, %s FROM %s " %\
246 246 (toget, sqlfrom) + sql, params)
247 247 if output: # Regroup into 3-tuples, and parse JSON
248 248 return ((ses, lin, (inp, out)) for ses, lin, inp, out in cur)
249 249 return cur
250 250
251 251 @needs_sqlite
252 252 @catch_corrupt_db
253 253 def get_session_info(self, session=0):
254 254 """get info about a session
255 255
256 256 Parameters
257 257 ----------
258 258
259 259 session : int
260 260 Session number to retrieve. The current session is 0, and negative
261 261 numbers count back from current session, so -1 is previous session.
262 262
263 263 Returns
264 264 -------
265 265
266 266 (session_id [int], start [datetime], end [datetime], num_cmds [int],
267 267 remark [unicode])
268 268
269 269 Sessions that are running or did not exit cleanly will have `end=None`
270 270 and `num_cmds=None`.
271 271
272 272 """
273 273
274 274 if session <= 0:
275 275 session += self.session_number
276 276
277 277 query = "SELECT * from sessions where session == ?"
278 278 return self.db.execute(query, (session,)).fetchone()
279 279
280 280 @catch_corrupt_db
281 281 def get_tail(self, n=10, raw=True, output=False, include_latest=False):
282 282 """Get the last n lines from the history database.
283 283
284 284 Parameters
285 285 ----------
286 286 n : int
287 287 The number of lines to get
288 288 raw, output : bool
289 289 See :meth:`get_range`
290 290 include_latest : bool
291 291 If False (default), n+1 lines are fetched, and the latest one
292 292 is discarded. This is intended to be used where the function
293 293 is called by a user command, which it should not return.
294 294
295 295 Returns
296 296 -------
297 297 Tuples as :meth:`get_range`
298 298 """
299 299 self.writeout_cache()
300 300 if not include_latest:
301 301 n += 1
302 302 cur = self._run_sql("ORDER BY session DESC, line DESC LIMIT ?",
303 303 (n,), raw=raw, output=output)
304 304 if not include_latest:
305 305 return reversed(list(cur)[1:])
306 306 return reversed(list(cur))
307 307
308 308 @catch_corrupt_db
309 309 def search(self, pattern="*", raw=True, search_raw=True,
310 310 output=False, n=None):
311 311 """Search the database using unix glob-style matching (wildcards
312 312 * and ?).
313 313
314 314 Parameters
315 315 ----------
316 316 pattern : str
317 317 The wildcarded pattern to match when searching
318 318 search_raw : bool
319 319 If True, search the raw input, otherwise, the parsed input
320 320 raw, output : bool
321 321 See :meth:`get_range`
322 322 n : None or int
323 323 If an integer is given, it defines the limit of
324 324 returned entries.
325 325
326 326 Returns
327 327 -------
328 328 Tuples as :meth:`get_range`
329 329 """
330 330 tosearch = "source_raw" if search_raw else "source"
331 331 if output:
332 332 tosearch = "history." + tosearch
333 333 self.writeout_cache()
334 334 sqlform = "WHERE %s GLOB ?" % tosearch
335 335 params = (pattern,)
336 336 if n is not None:
337 337 sqlform += " ORDER BY session DESC, line DESC LIMIT ?"
338 338 params += (n,)
339 339 cur = self._run_sql(sqlform, params, raw=raw, output=output)
340 340 if n is not None:
341 341 return reversed(list(cur))
342 342 return cur
343 343
344 344 @catch_corrupt_db
345 345 def get_range(self, session, start=1, stop=None, raw=True,output=False):
346 346 """Retrieve input by session.
347 347
348 348 Parameters
349 349 ----------
350 350 session : int
351 351 Session number to retrieve.
352 352 start : int
353 353 First line to retrieve.
354 354 stop : int
355 355 End of line range (excluded from output itself). If None, retrieve
356 356 to the end of the session.
357 357 raw : bool
358 358 If True, return untranslated input
359 359 output : bool
360 360 If True, attempt to include output. This will be 'real' Python
361 361 objects for the current session, or text reprs from previous
362 362 sessions if db_log_output was enabled at the time. Where no output
363 363 is found, None is used.
364 364
365 365 Returns
366 366 -------
367 367 An iterator over the desired lines. Each line is a 3-tuple, either
368 368 (session, line, input) if output is False, or
369 369 (session, line, (input, output)) if output is True.
370 370 """
371 371 if stop:
372 372 lineclause = "line >= ? AND line < ?"
373 373 params = (session, start, stop)
374 374 else:
375 375 lineclause = "line>=?"
376 376 params = (session, start)
377 377
378 378 return self._run_sql("WHERE session==? AND %s" % lineclause,
379 379 params, raw=raw, output=output)
380 380
381 381 def get_range_by_str(self, rangestr, raw=True, output=False):
382 382 """Get lines of history from a string of ranges, as used by magic
383 383 commands %hist, %save, %macro, etc.
384 384
385 385 Parameters
386 386 ----------
387 387 rangestr : str
388 388 A string specifying ranges, e.g. "5 ~2/1-4". See
389 389 :func:`magic_history` for full details.
390 390 raw, output : bool
391 391 As :meth:`get_range`
392 392
393 393 Returns
394 394 -------
395 395 Tuples as :meth:`get_range`
396 396 """
397 397 for sess, s, e in extract_hist_ranges(rangestr):
398 398 for line in self.get_range(sess, s, e, raw=raw, output=output):
399 399 yield line
400 400
401 401
402 402 class HistoryManager(HistoryAccessor):
403 403 """A class to organize all history-related functionality in one place.
404 404 """
405 405 # Public interface
406 406
407 407 # An instance of the IPython shell we are attached to
408 408 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
409 409 # Lists to hold processed and raw history. These start with a blank entry
410 410 # so that we can index them starting from 1
411 411 input_hist_parsed = List([""])
412 412 input_hist_raw = List([""])
413 413 # A list of directories visited during session
414 414 dir_hist = List()
415 415 def _dir_hist_default(self):
416 416 try:
417 417 return [os.getcwdu()]
418 418 except OSError:
419 419 return []
420 420
421 421 # A dict of output history, keyed with ints from the shell's
422 422 # execution count.
423 423 output_hist = Dict()
424 424 # The text/plain repr of outputs.
425 425 output_hist_reprs = Dict()
426 426
427 427 # The number of the current session in the history database
428 428 session_number = Integer()
429 429 # Should we log output to the database? (default no)
430 430 db_log_output = Bool(False, config=True)
431 431 # Write to database every x commands (higher values save disk access & power)
432 432 # Values of 1 or less effectively disable caching.
433 433 db_cache_size = Integer(0, config=True)
434 434 # The input and output caches
435 435 db_input_cache = List()
436 436 db_output_cache = List()
437 437
438 438 # History saving in separate thread
439 439 save_thread = Instance('IPython.core.history.HistorySavingThread')
440 440 try: # Event is a function returning an instance of _Event...
441 441 save_flag = Instance(threading._Event)
442 442 except AttributeError: # ...until Python 3.3, when it's a class.
443 443 save_flag = Instance(threading.Event)
444 444
445 445 # Private interface
446 446 # Variables used to store the three last inputs from the user. On each new
447 447 # history update, we populate the user's namespace with these, shifted as
448 448 # necessary.
449 449 _i00 = Unicode(u'')
450 450 _i = Unicode(u'')
451 451 _ii = Unicode(u'')
452 452 _iii = Unicode(u'')
453 453
454 454 # A regex matching all forms of the exit command, so that we don't store
455 455 # them in the history (it's annoying to rewind the first entry and land on
456 456 # an exit call).
457 457 _exit_re = re.compile(r"(exit|quit)(\s*\(.*\))?$")
458 458
459 459 def __init__(self, shell=None, config=None, **traits):
460 460 """Create a new history manager associated with a shell instance.
461 461 """
462 462 # We need a pointer back to the shell for various tasks.
463 463 super(HistoryManager, self).__init__(shell=shell, config=config,
464 464 **traits)
465 465 self.save_flag = threading.Event()
466 466 self.db_input_cache_lock = threading.Lock()
467 467 self.db_output_cache_lock = threading.Lock()
468 468 if self.enabled and self.hist_file != ':memory:':
469 469 self.save_thread = HistorySavingThread(self)
470 470 self.save_thread.start()
471 471
472 472 self.new_session()
473 473
474 474 def _get_hist_file_name(self, profile=None):
475 475 """Get default history file name based on the Shell's profile.
476 476
477 477 The profile parameter is ignored, but must exist for compatibility with
478 478 the parent class."""
479 479 profile_dir = self.shell.profile_dir.location
480 480 return os.path.join(profile_dir, 'history.sqlite')
481 481
482 482 @needs_sqlite
483 483 def new_session(self, conn=None):
484 484 """Get a new session number."""
485 485 if conn is None:
486 486 conn = self.db
487 487
488 488 with conn:
489 489 cur = conn.execute("""INSERT INTO sessions VALUES (NULL, ?, NULL,
490 490 NULL, "") """, (datetime.datetime.now(),))
491 491 self.session_number = cur.lastrowid
492 492
493 493 def end_session(self):
494 494 """Close the database session, filling in the end time and line count."""
495 495 self.writeout_cache()
496 496 with self.db:
497 497 self.db.execute("""UPDATE sessions SET end=?, num_cmds=? WHERE
498 498 session==?""", (datetime.datetime.now(),
499 499 len(self.input_hist_parsed)-1, self.session_number))
500 500 self.session_number = 0
501 501
502 502 def name_session(self, name):
503 503 """Give the current session a name in the history database."""
504 504 with self.db:
505 505 self.db.execute("UPDATE sessions SET remark=? WHERE session==?",
506 506 (name, self.session_number))
507 507
508 508 def reset(self, new_session=True):
509 509 """Clear the session history, releasing all object references, and
510 510 optionally open a new session."""
511 511 self.output_hist.clear()
512 512 # The directory history can't be completely empty
513 513 self.dir_hist[:] = [os.getcwdu()]
514 514
515 515 if new_session:
516 516 if self.session_number:
517 517 self.end_session()
518 518 self.input_hist_parsed[:] = [""]
519 519 self.input_hist_raw[:] = [""]
520 520 self.new_session()
521 521
522 522 # ------------------------------
523 523 # Methods for retrieving history
524 524 # ------------------------------
525 525 def _get_range_session(self, start=1, stop=None, raw=True, output=False):
526 526 """Get input and output history from the current session. Called by
527 527 get_range, and takes similar parameters."""
528 528 input_hist = self.input_hist_raw if raw else self.input_hist_parsed
529 529
530 530 n = len(input_hist)
531 531 if start < 0:
532 532 start += n
533 533 if not stop or (stop > n):
534 534 stop = n
535 535 elif stop < 0:
536 536 stop += n
537 537
538 538 for i in range(start, stop):
539 539 if output:
540 540 line = (input_hist[i], self.output_hist_reprs.get(i))
541 541 else:
542 542 line = input_hist[i]
543 543 yield (0, i, line)
544 544
545 545 def get_range(self, session=0, start=1, stop=None, raw=True,output=False):
546 546 """Retrieve input by session.
547 547
548 548 Parameters
549 549 ----------
550 550 session : int
551 551 Session number to retrieve. The current session is 0, and negative
552 552 numbers count back from current session, so -1 is previous session.
553 553 start : int
554 554 First line to retrieve.
555 555 stop : int
556 556 End of line range (excluded from output itself). If None, retrieve
557 557 to the end of the session.
558 558 raw : bool
559 559 If True, return untranslated input
560 560 output : bool
561 561 If True, attempt to include output. This will be 'real' Python
562 562 objects for the current session, or text reprs from previous
563 563 sessions if db_log_output was enabled at the time. Where no output
564 564 is found, None is used.
565 565
566 566 Returns
567 567 -------
568 568 An iterator over the desired lines. Each line is a 3-tuple, either
569 569 (session, line, input) if output is False, or
570 570 (session, line, (input, output)) if output is True.
571 571 """
572 572 if session <= 0:
573 573 session += self.session_number
574 574 if session==self.session_number: # Current session
575 575 return self._get_range_session(start, stop, raw, output)
576 576 return super(HistoryManager, self).get_range(session, start, stop, raw,
577 577 output)
578 578
579 579 ## ----------------------------
580 580 ## Methods for storing history:
581 581 ## ----------------------------
582 582 def store_inputs(self, line_num, source, source_raw=None):
583 583 """Store source and raw input in history and create input cache
584 584 variables _i*.
585 585
586 586 Parameters
587 587 ----------
588 588 line_num : int
589 589 The prompt number of this input.
590 590
591 591 source : str
592 592 Python input.
593 593
594 594 source_raw : str, optional
595 595 If given, this is the raw input without any IPython transformations
596 596 applied to it. If not given, ``source`` is used.
597 597 """
598 598 if source_raw is None:
599 599 source_raw = source
600 600 source = source.rstrip('\n')
601 601 source_raw = source_raw.rstrip('\n')
602 602
603 603 # do not store exit/quit commands
604 604 if self._exit_re.match(source_raw.strip()):
605 605 return
606 606
607 607 self.input_hist_parsed.append(source)
608 608 self.input_hist_raw.append(source_raw)
609 609
610 610 with self.db_input_cache_lock:
611 611 self.db_input_cache.append((line_num, source, source_raw))
612 612 # Trigger to flush cache and write to DB.
613 613 if len(self.db_input_cache) >= self.db_cache_size:
614 614 self.save_flag.set()
615 615
616 616 # update the auto _i variables
617 617 self._iii = self._ii
618 618 self._ii = self._i
619 619 self._i = self._i00
620 620 self._i00 = source_raw
621 621
622 622 # hackish access to user namespace to create _i1,_i2... dynamically
623 623 new_i = '_i%s' % line_num
624 624 to_main = {'_i': self._i,
625 625 '_ii': self._ii,
626 626 '_iii': self._iii,
627 627 new_i : self._i00 }
628 628
629 629 self.shell.push(to_main, interactive=False)
630 630
631 631 def store_output(self, line_num):
632 632 """If database output logging is enabled, this saves all the
633 633 outputs from the indicated prompt number to the database. It's
634 634 called by run_cell after code has been executed.
635 635
636 636 Parameters
637 637 ----------
638 638 line_num : int
639 639 The line number from which to save outputs
640 640 """
641 641 if (not self.db_log_output) or (line_num not in self.output_hist_reprs):
642 642 return
643 643 output = self.output_hist_reprs[line_num]
644 644
645 645 with self.db_output_cache_lock:
646 646 self.db_output_cache.append((line_num, output))
647 647 if self.db_cache_size <= 1:
648 648 self.save_flag.set()
649 649
650 650 def _writeout_input_cache(self, conn):
651 651 with conn:
652 652 for line in self.db_input_cache:
653 653 conn.execute("INSERT INTO history VALUES (?, ?, ?, ?)",
654 654 (self.session_number,)+line)
655 655
656 656 def _writeout_output_cache(self, conn):
657 657 with conn:
658 658 for line in self.db_output_cache:
659 659 conn.execute("INSERT INTO output_history VALUES (?, ?, ?)",
660 660 (self.session_number,)+line)
661 661
662 662 @needs_sqlite
663 663 def writeout_cache(self, conn=None):
664 664 """Write any entries in the cache to the database."""
665 665 if conn is None:
666 666 conn = self.db
667 667
668 668 with self.db_input_cache_lock:
669 669 try:
670 670 self._writeout_input_cache(conn)
671 671 except sqlite3.IntegrityError:
672 672 self.new_session(conn)
673 673 print("ERROR! Session/line number was not unique in",
674 674 "database. History logging moved to new session",
675 675 self.session_number)
676 676 try:
677 677 # Try writing to the new session. If this fails, don't
678 678 # recurse
679 679 self._writeout_input_cache(conn)
680 680 except sqlite3.IntegrityError:
681 681 pass
682 682 finally:
683 683 self.db_input_cache = []
684 684
685 685 with self.db_output_cache_lock:
686 686 try:
687 687 self._writeout_output_cache(conn)
688 688 except sqlite3.IntegrityError:
689 689 print("!! Session/line number for output was not unique",
690 690 "in database. Output will not be stored.")
691 691 finally:
692 692 self.db_output_cache = []
693 693
694 694
695 695 class HistorySavingThread(threading.Thread):
696 696 """This thread takes care of writing history to the database, so that
697 697 the UI isn't held up while that happens.
698 698
699 699 It waits for the HistoryManager's save_flag to be set, then writes out
700 700 the history cache. The main thread is responsible for setting the flag when
701 701 the cache size reaches a defined threshold."""
702 702 daemon = True
703 703 stop_now = False
704 704 enabled = True
705 705 def __init__(self, history_manager):
706 706 super(HistorySavingThread, self).__init__()
707 707 self.history_manager = history_manager
708 708 self.enabled = history_manager.enabled
709 709 atexit.register(self.stop)
710 710
711 711 @needs_sqlite
712 712 def run(self):
713 713 # We need a separate db connection per thread:
714 714 try:
715 715 self.db = sqlite3.connect(self.history_manager.hist_file,
716 716 **self.history_manager.connection_options
717 717 )
718 718 while True:
719 719 self.history_manager.save_flag.wait()
720 720 if self.stop_now:
721 721 return
722 722 self.history_manager.save_flag.clear()
723 723 self.history_manager.writeout_cache(self.db)
724 724 except Exception as e:
725 725 print(("The history saving thread hit an unexpected error (%s)."
726 726 "History will not be written to the database.") % repr(e))
727 727
728 728 def stop(self):
729 729 """This can be called from the main thread to safely stop this thread.
730 730
731 731 Note that it does not attempt to write out remaining history before
732 732 exiting. That should be done by calling the HistoryManager's
733 733 end_session method."""
734 734 self.stop_now = True
735 735 self.history_manager.save_flag.set()
736 736 self.join()
737 737
738 738
739 739 # To match, e.g. ~5/8-~2/3
740 740 range_re = re.compile(r"""
741 741 ((?P<startsess>~?\d+)/)?
742 742 (?P<start>\d+) # Only the start line num is compulsory
743 743 ((?P<sep>[\-:])
744 744 ((?P<endsess>~?\d+)/)?
745 745 (?P<end>\d+))?
746 746 $""", re.VERBOSE)
747 747
748 748
749 749 def extract_hist_ranges(ranges_str):
750 750 """Turn a string of history ranges into 3-tuples of (session, start, stop).
751 751
752 752 Examples
753 753 --------
754 754 list(extract_input_ranges("~8/5-~7/4 2"))
755 755 [(-8, 5, None), (-7, 1, 4), (0, 2, 3)]
756 756 """
757 757 for range_str in ranges_str.split():
758 758 rmatch = range_re.match(range_str)
759 759 if not rmatch:
760 760 continue
761 761 start = int(rmatch.group("start"))
762 762 end = rmatch.group("end")
763 763 end = int(end) if end else start+1 # If no end specified, get (a, a+1)
764 764 if rmatch.group("sep") == "-": # 1-3 == 1:4 --> [1, 2, 3]
765 765 end += 1
766 766 startsess = rmatch.group("startsess") or "0"
767 767 endsess = rmatch.group("endsess") or startsess
768 768 startsess = int(startsess.replace("~","-"))
769 769 endsess = int(endsess.replace("~","-"))
770 770 assert endsess >= startsess
771 771
772 772 if endsess == startsess:
773 773 yield (startsess, start, end)
774 774 continue
775 775 # Multiple sessions in one range:
776 776 yield (startsess, start, None)
777 777 for sess in range(startsess+1, endsess):
778 778 yield (sess, 1, None)
779 779 yield (endsess, 1, end)
780 780
781 781
782 782 def _format_lineno(session, line):
783 783 """Helper function to format line numbers properly."""
784 784 if session == 0:
785 785 return str(line)
786 786 return "%s#%s" % (session, line)
787 787
788 788
@@ -1,3010 +1,3044 b''
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 from __future__ import print_function
20 20
21 21 import __builtin__ as builtin_mod
22 22 import __future__
23 23 import abc
24 24 import ast
25 25 import atexit
26 26 import os
27 27 import re
28 28 import runpy
29 29 import sys
30 30 import tempfile
31 31 import types
32 32 import urllib
33 33 from io import open as io_open
34 34
35 35 from IPython.config.configurable import SingletonConfigurable
36 36 from IPython.core import debugger, oinspect
37 37 from IPython.core import magic
38 38 from IPython.core import page
39 39 from IPython.core import prefilter
40 40 from IPython.core import shadowns
41 41 from IPython.core import ultratb
42 42 from IPython.core.alias import AliasManager, AliasError
43 43 from IPython.core.autocall import ExitAutocall
44 44 from IPython.core.builtin_trap import BuiltinTrap
45 45 from IPython.core.compilerop import CachingCompiler
46 46 from IPython.core.display_trap import DisplayTrap
47 47 from IPython.core.displayhook import DisplayHook
48 48 from IPython.core.displaypub import DisplayPublisher
49 49 from IPython.core.error import UsageError
50 50 from IPython.core.extensions import ExtensionManager
51 51 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
52 52 from IPython.core.formatters import DisplayFormatter
53 53 from IPython.core.history import HistoryManager
54 54 from IPython.core.inputsplitter import IPythonInputSplitter, ESC_MAGIC, ESC_MAGIC2
55 55 from IPython.core.logger import Logger
56 56 from IPython.core.macro import Macro
57 57 from IPython.core.payload import PayloadManager
58 58 from IPython.core.prefilter import PrefilterManager
59 59 from IPython.core.profiledir import ProfileDir
60 60 from IPython.core.pylabtools import pylab_activate
61 61 from IPython.core.prompts import PromptManager
62 62 from IPython.lib.latextools import LaTeXTool
63 63 from IPython.utils import PyColorize
64 64 from IPython.utils import io
65 65 from IPython.utils import py3compat
66 66 from IPython.utils import openpy
67 67 from IPython.utils.decorators import undoc
68 68 from IPython.utils.doctestreload import doctest_reload
69 69 from IPython.utils.io import ask_yes_no
70 70 from IPython.utils.ipstruct import Struct
71 71 from IPython.utils.path import get_home_dir, get_ipython_dir, get_py_filename, unquote_filename
72 72 from IPython.utils.pickleshare import PickleShareDB
73 73 from IPython.utils.process import system, getoutput
74 74 from IPython.utils.strdispatch import StrDispatch
75 75 from IPython.utils.syspathcontext import prepended_to_syspath
76 76 from IPython.utils.text import (format_screen, LSString, SList,
77 77 DollarFormatter)
78 78 from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum,
79 79 List, Unicode, Instance, Type)
80 80 from IPython.utils.warn import warn, error
81 81 import IPython.core.hooks
82 82
83 83 #-----------------------------------------------------------------------------
84 84 # Globals
85 85 #-----------------------------------------------------------------------------
86 86
87 87 # compiled regexps for autoindent management
88 88 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
89 89
90 90 #-----------------------------------------------------------------------------
91 91 # Utilities
92 92 #-----------------------------------------------------------------------------
93 93
94 94 @undoc
95 95 def softspace(file, newvalue):
96 96 """Copied from code.py, to remove the dependency"""
97 97
98 98 oldvalue = 0
99 99 try:
100 100 oldvalue = file.softspace
101 101 except AttributeError:
102 102 pass
103 103 try:
104 104 file.softspace = newvalue
105 105 except (AttributeError, TypeError):
106 106 # "attribute-less object" or "read-only attributes"
107 107 pass
108 108 return oldvalue
109 109
110 110 @undoc
111 111 def no_op(*a, **kw): pass
112 112
113 113 @undoc
114 114 class NoOpContext(object):
115 115 def __enter__(self): pass
116 116 def __exit__(self, type, value, traceback): pass
117 117 no_op_context = NoOpContext()
118 118
119 119 class SpaceInInput(Exception): pass
120 120
121 121 @undoc
122 122 class Bunch: pass
123 123
124 124
125 125 def get_default_colors():
126 126 if sys.platform=='darwin':
127 127 return "LightBG"
128 128 elif os.name=='nt':
129 129 return 'Linux'
130 130 else:
131 131 return 'Linux'
132 132
133 133
134 134 class SeparateUnicode(Unicode):
135 135 """A Unicode subclass to validate separate_in, separate_out, etc.
136 136
137 137 This is a Unicode based trait that converts '0'->'' and '\\n'->'\n'.
138 138 """
139 139
140 140 def validate(self, obj, value):
141 141 if value == '0': value = ''
142 142 value = value.replace('\\n','\n')
143 143 return super(SeparateUnicode, self).validate(obj, value)
144 144
145 145
146 146 class ReadlineNoRecord(object):
147 147 """Context manager to execute some code, then reload readline history
148 148 so that interactive input to the code doesn't appear when pressing up."""
149 149 def __init__(self, shell):
150 150 self.shell = shell
151 151 self._nested_level = 0
152 152
153 153 def __enter__(self):
154 154 if self._nested_level == 0:
155 155 try:
156 156 self.orig_length = self.current_length()
157 157 self.readline_tail = self.get_readline_tail()
158 158 except (AttributeError, IndexError): # Can fail with pyreadline
159 159 self.orig_length, self.readline_tail = 999999, []
160 160 self._nested_level += 1
161 161
162 162 def __exit__(self, type, value, traceback):
163 163 self._nested_level -= 1
164 164 if self._nested_level == 0:
165 165 # Try clipping the end if it's got longer
166 166 try:
167 167 e = self.current_length() - self.orig_length
168 168 if e > 0:
169 169 for _ in range(e):
170 170 self.shell.readline.remove_history_item(self.orig_length)
171 171
172 172 # If it still doesn't match, just reload readline history.
173 173 if self.current_length() != self.orig_length \
174 174 or self.get_readline_tail() != self.readline_tail:
175 175 self.shell.refill_readline_hist()
176 176 except (AttributeError, IndexError):
177 177 pass
178 178 # Returning False will cause exceptions to propagate
179 179 return False
180 180
181 181 def current_length(self):
182 182 return self.shell.readline.get_current_history_length()
183 183
184 184 def get_readline_tail(self, n=10):
185 185 """Get the last n items in readline history."""
186 186 end = self.shell.readline.get_current_history_length() + 1
187 187 start = max(end-n, 1)
188 188 ghi = self.shell.readline.get_history_item
189 189 return [ghi(x) for x in range(start, end)]
190 190
191 191 #-----------------------------------------------------------------------------
192 192 # Main IPython class
193 193 #-----------------------------------------------------------------------------
194 194
195 195 class InteractiveShell(SingletonConfigurable):
196 196 """An enhanced, interactive shell for Python."""
197 197
198 198 _instance = None
199
200 ast_transformers = List([], config=True, help=
201 """
202 A list of ast.NodeTransformer subclass instances, which will be applied
203 to user input before code is run.
204 """
205 )
199 206
200 207 autocall = Enum((0,1,2), default_value=0, config=True, help=
201 208 """
202 209 Make IPython automatically call any callable object even if you didn't
203 210 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
204 211 automatically. The value can be '0' to disable the feature, '1' for
205 212 'smart' autocall, where it is not applied if there are no more
206 213 arguments on the line, and '2' for 'full' autocall, where all callable
207 214 objects are automatically called (even if no arguments are present).
208 215 """
209 216 )
210 217 # TODO: remove all autoindent logic and put into frontends.
211 218 # We can't do this yet because even runlines uses the autoindent.
212 219 autoindent = CBool(True, config=True, help=
213 220 """
214 221 Autoindent IPython code entered interactively.
215 222 """
216 223 )
217 224 automagic = CBool(True, config=True, help=
218 225 """
219 226 Enable magic commands to be called without the leading %.
220 227 """
221 228 )
222 229 cache_size = Integer(1000, config=True, help=
223 230 """
224 231 Set the size of the output cache. The default is 1000, you can
225 232 change it permanently in your config file. Setting it to 0 completely
226 233 disables the caching system, and the minimum value accepted is 20 (if
227 234 you provide a value less than 20, it is reset to 0 and a warning is
228 235 issued). This limit is defined because otherwise you'll spend more
229 236 time re-flushing a too small cache than working
230 237 """
231 238 )
232 239 color_info = CBool(True, config=True, help=
233 240 """
234 241 Use colors for displaying information about objects. Because this
235 242 information is passed through a pager (like 'less'), and some pagers
236 243 get confused with color codes, this capability can be turned off.
237 244 """
238 245 )
239 246 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
240 247 default_value=get_default_colors(), config=True,
241 248 help="Set the color scheme (NoColor, Linux, or LightBG)."
242 249 )
243 250 colors_force = CBool(False, help=
244 251 """
245 252 Force use of ANSI color codes, regardless of OS and readline
246 253 availability.
247 254 """
248 255 # FIXME: This is essentially a hack to allow ZMQShell to show colors
249 256 # without readline on Win32. When the ZMQ formatting system is
250 257 # refactored, this should be removed.
251 258 )
252 259 debug = CBool(False, config=True)
253 260 deep_reload = CBool(False, config=True, help=
254 261 """
255 262 Enable deep (recursive) reloading by default. IPython can use the
256 263 deep_reload module which reloads changes in modules recursively (it
257 264 replaces the reload() function, so you don't need to change anything to
258 265 use it). deep_reload() forces a full reload of modules whose code may
259 266 have changed, which the default reload() function does not. When
260 267 deep_reload is off, IPython will use the normal reload(), but
261 268 deep_reload will still be available as dreload().
262 269 """
263 270 )
264 271 disable_failing_post_execute = CBool(False, config=True,
265 272 help="Don't call post-execute functions that have failed in the past."
266 273 )
267 274 display_formatter = Instance(DisplayFormatter)
268 275 displayhook_class = Type(DisplayHook)
269 276 display_pub_class = Type(DisplayPublisher)
270 277 data_pub_class = None
271 278
272 279 exit_now = CBool(False)
273 280 exiter = Instance(ExitAutocall)
274 281 def _exiter_default(self):
275 282 return ExitAutocall(self)
276 283 # Monotonically increasing execution counter
277 284 execution_count = Integer(1)
278 285 filename = Unicode("<ipython console>")
279 286 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
280 287
281 288 # Input splitter, to split entire cells of input into either individual
282 289 # interactive statements or whole blocks.
283 290 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
284 291 (), {})
285 292 logstart = CBool(False, config=True, help=
286 293 """
287 294 Start logging to the default log file.
288 295 """
289 296 )
290 297 logfile = Unicode('', config=True, help=
291 298 """
292 299 The name of the logfile to use.
293 300 """
294 301 )
295 302 logappend = Unicode('', config=True, help=
296 303 """
297 304 Start logging to the given file in append mode.
298 305 """
299 306 )
300 307 object_info_string_level = Enum((0,1,2), default_value=0,
301 308 config=True)
302 309 pdb = CBool(False, config=True, help=
303 310 """
304 311 Automatically call the pdb debugger after every exception.
305 312 """
306 313 )
307 314 multiline_history = CBool(sys.platform != 'win32', config=True,
308 315 help="Save multi-line entries as one entry in readline history"
309 316 )
310 317
311 318 # deprecated prompt traits:
312 319
313 320 prompt_in1 = Unicode('In [\\#]: ', config=True,
314 321 help="Deprecated, use PromptManager.in_template")
315 322 prompt_in2 = Unicode(' .\\D.: ', config=True,
316 323 help="Deprecated, use PromptManager.in2_template")
317 324 prompt_out = Unicode('Out[\\#]: ', config=True,
318 325 help="Deprecated, use PromptManager.out_template")
319 326 prompts_pad_left = CBool(True, config=True,
320 327 help="Deprecated, use PromptManager.justify")
321 328
322 329 def _prompt_trait_changed(self, name, old, new):
323 330 table = {
324 331 'prompt_in1' : 'in_template',
325 332 'prompt_in2' : 'in2_template',
326 333 'prompt_out' : 'out_template',
327 334 'prompts_pad_left' : 'justify',
328 335 }
329 warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}\n".format(
336 warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}".format(
330 337 name=name, newname=table[name])
331 338 )
332 339 # protect against weird cases where self.config may not exist:
333 340 if self.config is not None:
334 341 # propagate to corresponding PromptManager trait
335 342 setattr(self.config.PromptManager, table[name], new)
336 343
337 344 _prompt_in1_changed = _prompt_trait_changed
338 345 _prompt_in2_changed = _prompt_trait_changed
339 346 _prompt_out_changed = _prompt_trait_changed
340 347 _prompt_pad_left_changed = _prompt_trait_changed
341 348
342 349 show_rewritten_input = CBool(True, config=True,
343 350 help="Show rewritten input, e.g. for autocall."
344 351 )
345 352
346 353 quiet = CBool(False, config=True)
347 354
348 355 history_length = Integer(10000, config=True)
349 356
350 357 # The readline stuff will eventually be moved to the terminal subclass
351 358 # but for now, we can't do that as readline is welded in everywhere.
352 359 readline_use = CBool(True, config=True)
353 360 readline_remove_delims = Unicode('-/~', config=True)
354 361 # don't use \M- bindings by default, because they
355 362 # conflict with 8-bit encodings. See gh-58,gh-88
356 363 readline_parse_and_bind = List([
357 364 'tab: complete',
358 365 '"\C-l": clear-screen',
359 366 'set show-all-if-ambiguous on',
360 367 '"\C-o": tab-insert',
361 368 '"\C-r": reverse-search-history',
362 369 '"\C-s": forward-search-history',
363 370 '"\C-p": history-search-backward',
364 371 '"\C-n": history-search-forward',
365 372 '"\e[A": history-search-backward',
366 373 '"\e[B": history-search-forward',
367 374 '"\C-k": kill-line',
368 375 '"\C-u": unix-line-discard',
369 376 ], allow_none=False, config=True)
370 377
371 378 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
372 379 default_value='last_expr', config=True,
373 380 help="""
374 381 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
375 382 run interactively (displaying output from expressions).""")
376 383
377 384 # TODO: this part of prompt management should be moved to the frontends.
378 385 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
379 386 separate_in = SeparateUnicode('\n', config=True)
380 387 separate_out = SeparateUnicode('', config=True)
381 388 separate_out2 = SeparateUnicode('', config=True)
382 389 wildcards_case_sensitive = CBool(True, config=True)
383 390 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
384 391 default_value='Context', config=True)
385 392
386 393 # Subcomponents of InteractiveShell
387 394 alias_manager = Instance('IPython.core.alias.AliasManager')
388 395 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
389 396 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
390 397 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
391 398 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
392 399 payload_manager = Instance('IPython.core.payload.PayloadManager')
393 400 history_manager = Instance('IPython.core.history.HistoryManager')
394 401 magics_manager = Instance('IPython.core.magic.MagicsManager')
395 402
396 403 profile_dir = Instance('IPython.core.application.ProfileDir')
397 404 @property
398 405 def profile(self):
399 406 if self.profile_dir is not None:
400 407 name = os.path.basename(self.profile_dir.location)
401 408 return name.replace('profile_','')
402 409
403 410
404 411 # Private interface
405 412 _post_execute = Instance(dict)
406 413
407 414 # Tracks any GUI loop loaded for pylab
408 415 pylab_gui_select = None
409 416
410 417 def __init__(self, config=None, ipython_dir=None, profile_dir=None,
411 418 user_module=None, user_ns=None,
412 419 custom_exceptions=((), None)):
413 420
414 421 # This is where traits with a config_key argument are updated
415 422 # from the values on config.
416 423 super(InteractiveShell, self).__init__(config=config)
417 424 self.configurables = [self]
418 425
419 426 # These are relatively independent and stateless
420 427 self.init_ipython_dir(ipython_dir)
421 428 self.init_profile_dir(profile_dir)
422 429 self.init_instance_attrs()
423 430 self.init_environment()
424 431
425 432 # Check if we're in a virtualenv, and set up sys.path.
426 433 self.init_virtualenv()
427 434
428 435 # Create namespaces (user_ns, user_global_ns, etc.)
429 436 self.init_create_namespaces(user_module, user_ns)
430 437 # This has to be done after init_create_namespaces because it uses
431 438 # something in self.user_ns, but before init_sys_modules, which
432 439 # is the first thing to modify sys.
433 440 # TODO: When we override sys.stdout and sys.stderr before this class
434 441 # is created, we are saving the overridden ones here. Not sure if this
435 442 # is what we want to do.
436 443 self.save_sys_module_state()
437 444 self.init_sys_modules()
438 445
439 446 # While we're trying to have each part of the code directly access what
440 447 # it needs without keeping redundant references to objects, we have too
441 448 # much legacy code that expects ip.db to exist.
442 449 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
443 450
444 451 self.init_history()
445 452 self.init_encoding()
446 453 self.init_prefilter()
447 454
448 455 self.init_syntax_highlighting()
449 456 self.init_hooks()
450 457 self.init_pushd_popd_magic()
451 458 # self.init_traceback_handlers use to be here, but we moved it below
452 459 # because it and init_io have to come after init_readline.
453 460 self.init_user_ns()
454 461 self.init_logger()
455 462 self.init_alias()
456 463 self.init_builtins()
457 464
458 465 # The following was in post_config_initialization
459 466 self.init_inspector()
460 467 # init_readline() must come before init_io(), because init_io uses
461 468 # readline related things.
462 469 self.init_readline()
463 470 # We save this here in case user code replaces raw_input, but it needs
464 471 # to be after init_readline(), because PyPy's readline works by replacing
465 472 # raw_input.
466 473 if py3compat.PY3:
467 474 self.raw_input_original = input
468 475 else:
469 476 self.raw_input_original = raw_input
470 477 # init_completer must come after init_readline, because it needs to
471 478 # know whether readline is present or not system-wide to configure the
472 479 # completers, since the completion machinery can now operate
473 480 # independently of readline (e.g. over the network)
474 481 self.init_completer()
475 482 # TODO: init_io() needs to happen before init_traceback handlers
476 483 # because the traceback handlers hardcode the stdout/stderr streams.
477 484 # This logic in in debugger.Pdb and should eventually be changed.
478 485 self.init_io()
479 486 self.init_traceback_handlers(custom_exceptions)
480 487 self.init_prompts()
481 488 self.init_display_formatter()
482 489 self.init_display_pub()
483 490 self.init_data_pub()
484 491 self.init_displayhook()
485 492 self.init_reload_doctest()
486 493 self.init_latextool()
487 494 self.init_magics()
488 495 self.init_logstart()
489 496 self.init_pdb()
490 497 self.init_extension_manager()
491 498 self.init_payload()
492 499 self.hooks.late_startup_hook()
493 500 atexit.register(self.atexit_operations)
494 501
495 502 def get_ipython(self):
496 503 """Return the currently running IPython instance."""
497 504 return self
498 505
499 506 #-------------------------------------------------------------------------
500 507 # Trait changed handlers
501 508 #-------------------------------------------------------------------------
502 509
503 510 def _ipython_dir_changed(self, name, new):
504 511 if not os.path.isdir(new):
505 512 os.makedirs(new, mode = 0o777)
506 513
507 514 def set_autoindent(self,value=None):
508 515 """Set the autoindent flag, checking for readline support.
509 516
510 517 If called with no arguments, it acts as a toggle."""
511 518
512 519 if value != 0 and not self.has_readline:
513 520 if os.name == 'posix':
514 521 warn("The auto-indent feature requires the readline library")
515 522 self.autoindent = 0
516 523 return
517 524 if value is None:
518 525 self.autoindent = not self.autoindent
519 526 else:
520 527 self.autoindent = value
521 528
522 529 #-------------------------------------------------------------------------
523 530 # init_* methods called by __init__
524 531 #-------------------------------------------------------------------------
525 532
526 533 def init_ipython_dir(self, ipython_dir):
527 534 if ipython_dir is not None:
528 535 self.ipython_dir = ipython_dir
529 536 return
530 537
531 538 self.ipython_dir = get_ipython_dir()
532 539
533 540 def init_profile_dir(self, profile_dir):
534 541 if profile_dir is not None:
535 542 self.profile_dir = profile_dir
536 543 return
537 544 self.profile_dir =\
538 545 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
539 546
540 547 def init_instance_attrs(self):
541 548 self.more = False
542 549
543 550 # command compiler
544 551 self.compile = CachingCompiler()
545 552
546 553 # Make an empty namespace, which extension writers can rely on both
547 554 # existing and NEVER being used by ipython itself. This gives them a
548 555 # convenient location for storing additional information and state
549 556 # their extensions may require, without fear of collisions with other
550 557 # ipython names that may develop later.
551 558 self.meta = Struct()
552 559
553 560 # Temporary files used for various purposes. Deleted at exit.
554 561 self.tempfiles = []
555 562
556 563 # Keep track of readline usage (later set by init_readline)
557 564 self.has_readline = False
558 565
559 566 # keep track of where we started running (mainly for crash post-mortem)
560 567 # This is not being used anywhere currently.
561 568 self.starting_dir = os.getcwdu()
562 569
563 570 # Indentation management
564 571 self.indent_current_nsp = 0
565 572
566 573 # Dict to track post-execution functions that have been registered
567 574 self._post_execute = {}
568 575
569 576 def init_environment(self):
570 577 """Any changes we need to make to the user's environment."""
571 578 pass
572 579
573 580 def init_encoding(self):
574 581 # Get system encoding at startup time. Certain terminals (like Emacs
575 582 # under Win32 have it set to None, and we need to have a known valid
576 583 # encoding to use in the raw_input() method
577 584 try:
578 585 self.stdin_encoding = sys.stdin.encoding or 'ascii'
579 586 except AttributeError:
580 587 self.stdin_encoding = 'ascii'
581 588
582 589 def init_syntax_highlighting(self):
583 590 # Python source parser/formatter for syntax highlighting
584 591 pyformat = PyColorize.Parser().format
585 592 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
586 593
587 594 def init_pushd_popd_magic(self):
588 595 # for pushd/popd management
589 596 self.home_dir = get_home_dir()
590 597
591 598 self.dir_stack = []
592 599
593 600 def init_logger(self):
594 601 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
595 602 logmode='rotate')
596 603
597 604 def init_logstart(self):
598 605 """Initialize logging in case it was requested at the command line.
599 606 """
600 607 if self.logappend:
601 608 self.magic('logstart %s append' % self.logappend)
602 609 elif self.logfile:
603 610 self.magic('logstart %s' % self.logfile)
604 611 elif self.logstart:
605 612 self.magic('logstart')
606 613
607 614 def init_builtins(self):
608 615 # A single, static flag that we set to True. Its presence indicates
609 616 # that an IPython shell has been created, and we make no attempts at
610 617 # removing on exit or representing the existence of more than one
611 618 # IPython at a time.
612 619 builtin_mod.__dict__['__IPYTHON__'] = True
613 620
614 621 # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to
615 622 # manage on enter/exit, but with all our shells it's virtually
616 623 # impossible to get all the cases right. We're leaving the name in for
617 624 # those who adapted their codes to check for this flag, but will
618 625 # eventually remove it after a few more releases.
619 626 builtin_mod.__dict__['__IPYTHON__active'] = \
620 627 'Deprecated, check for __IPYTHON__'
621 628
622 629 self.builtin_trap = BuiltinTrap(shell=self)
623 630
624 631 def init_inspector(self):
625 632 # Object inspector
626 633 self.inspector = oinspect.Inspector(oinspect.InspectColors,
627 634 PyColorize.ANSICodeColors,
628 635 'NoColor',
629 636 self.object_info_string_level)
630 637
631 638 def init_io(self):
632 639 # This will just use sys.stdout and sys.stderr. If you want to
633 640 # override sys.stdout and sys.stderr themselves, you need to do that
634 641 # *before* instantiating this class, because io holds onto
635 642 # references to the underlying streams.
636 643 if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline:
637 644 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
638 645 else:
639 646 io.stdout = io.IOStream(sys.stdout)
640 647 io.stderr = io.IOStream(sys.stderr)
641 648
642 649 def init_prompts(self):
643 650 self.prompt_manager = PromptManager(shell=self, config=self.config)
644 651 self.configurables.append(self.prompt_manager)
645 652 # Set system prompts, so that scripts can decide if they are running
646 653 # interactively.
647 654 sys.ps1 = 'In : '
648 655 sys.ps2 = '...: '
649 656 sys.ps3 = 'Out: '
650 657
651 658 def init_display_formatter(self):
652 659 self.display_formatter = DisplayFormatter(config=self.config)
653 660 self.configurables.append(self.display_formatter)
654 661
655 662 def init_display_pub(self):
656 663 self.display_pub = self.display_pub_class(config=self.config)
657 664 self.configurables.append(self.display_pub)
658 665
659 666 def init_data_pub(self):
660 667 if not self.data_pub_class:
661 668 self.data_pub = None
662 669 return
663 670 self.data_pub = self.data_pub_class(config=self.config)
664 671 self.configurables.append(self.data_pub)
665 672
666 673 def init_displayhook(self):
667 674 # Initialize displayhook, set in/out prompts and printing system
668 675 self.displayhook = self.displayhook_class(
669 676 config=self.config,
670 677 shell=self,
671 678 cache_size=self.cache_size,
672 679 )
673 680 self.configurables.append(self.displayhook)
674 681 # This is a context manager that installs/revmoes the displayhook at
675 682 # the appropriate time.
676 683 self.display_trap = DisplayTrap(hook=self.displayhook)
677 684
678 685 def init_reload_doctest(self):
679 686 # Do a proper resetting of doctest, including the necessary displayhook
680 687 # monkeypatching
681 688 try:
682 689 doctest_reload()
683 690 except ImportError:
684 691 warn("doctest module does not exist.")
685 692
686 693 def init_latextool(self):
687 694 """Configure LaTeXTool."""
688 695 cfg = LaTeXTool.instance(config=self.config)
689 696 if cfg not in self.configurables:
690 697 self.configurables.append(cfg)
691 698
692 699 def init_virtualenv(self):
693 700 """Add a virtualenv to sys.path so the user can import modules from it.
694 701 This isn't perfect: it doesn't use the Python interpreter with which the
695 702 virtualenv was built, and it ignores the --no-site-packages option. A
696 703 warning will appear suggesting the user installs IPython in the
697 704 virtualenv, but for many cases, it probably works well enough.
698 705
699 706 Adapted from code snippets online.
700 707
701 708 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
702 709 """
703 710 if 'VIRTUAL_ENV' not in os.environ:
704 711 # Not in a virtualenv
705 712 return
706 713
707 714 if sys.executable.startswith(os.environ['VIRTUAL_ENV']):
708 715 # Running properly in the virtualenv, don't need to do anything
709 716 return
710 717
711 718 warn("Attempting to work in a virtualenv. If you encounter problems, please "
712 "install IPython inside the virtualenv.\n")
719 "install IPython inside the virtualenv.")
713 720 if sys.platform == "win32":
714 721 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
715 722 else:
716 723 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
717 724 'python%d.%d' % sys.version_info[:2], 'site-packages')
718 725
719 726 import site
720 727 sys.path.insert(0, virtual_env)
721 728 site.addsitedir(virtual_env)
722 729
723 730 #-------------------------------------------------------------------------
724 731 # Things related to injections into the sys module
725 732 #-------------------------------------------------------------------------
726 733
727 734 def save_sys_module_state(self):
728 735 """Save the state of hooks in the sys module.
729 736
730 737 This has to be called after self.user_module is created.
731 738 """
732 739 self._orig_sys_module_state = {}
733 740 self._orig_sys_module_state['stdin'] = sys.stdin
734 741 self._orig_sys_module_state['stdout'] = sys.stdout
735 742 self._orig_sys_module_state['stderr'] = sys.stderr
736 743 self._orig_sys_module_state['excepthook'] = sys.excepthook
737 744 self._orig_sys_modules_main_name = self.user_module.__name__
738 745 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
739 746
740 747 def restore_sys_module_state(self):
741 748 """Restore the state of the sys module."""
742 749 try:
743 750 for k, v in self._orig_sys_module_state.iteritems():
744 751 setattr(sys, k, v)
745 752 except AttributeError:
746 753 pass
747 754 # Reset what what done in self.init_sys_modules
748 755 if self._orig_sys_modules_main_mod is not None:
749 756 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
750 757
751 758 #-------------------------------------------------------------------------
752 759 # Things related to hooks
753 760 #-------------------------------------------------------------------------
754 761
755 762 def init_hooks(self):
756 763 # hooks holds pointers used for user-side customizations
757 764 self.hooks = Struct()
758 765
759 766 self.strdispatchers = {}
760 767
761 768 # Set all default hooks, defined in the IPython.hooks module.
762 769 hooks = IPython.core.hooks
763 770 for hook_name in hooks.__all__:
764 771 # default hooks have priority 100, i.e. low; user hooks should have
765 772 # 0-100 priority
766 773 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
767 774
768 775 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
769 776 """set_hook(name,hook) -> sets an internal IPython hook.
770 777
771 778 IPython exposes some of its internal API as user-modifiable hooks. By
772 779 adding your function to one of these hooks, you can modify IPython's
773 780 behavior to call at runtime your own routines."""
774 781
775 782 # At some point in the future, this should validate the hook before it
776 783 # accepts it. Probably at least check that the hook takes the number
777 784 # of args it's supposed to.
778 785
779 786 f = types.MethodType(hook,self)
780 787
781 788 # check if the hook is for strdispatcher first
782 789 if str_key is not None:
783 790 sdp = self.strdispatchers.get(name, StrDispatch())
784 791 sdp.add_s(str_key, f, priority )
785 792 self.strdispatchers[name] = sdp
786 793 return
787 794 if re_key is not None:
788 795 sdp = self.strdispatchers.get(name, StrDispatch())
789 796 sdp.add_re(re.compile(re_key), f, priority )
790 797 self.strdispatchers[name] = sdp
791 798 return
792 799
793 800 dp = getattr(self.hooks, name, None)
794 801 if name not in IPython.core.hooks.__all__:
795 802 print("Warning! Hook '%s' is not one of %s" % \
796 803 (name, IPython.core.hooks.__all__ ))
797 804 if not dp:
798 805 dp = IPython.core.hooks.CommandChainDispatcher()
799 806
800 807 try:
801 808 dp.add(f,priority)
802 809 except AttributeError:
803 810 # it was not commandchain, plain old func - replace
804 811 dp = f
805 812
806 813 setattr(self.hooks,name, dp)
807 814
808 815 def register_post_execute(self, func):
809 816 """Register a function for calling after code execution.
810 817 """
811 818 if not callable(func):
812 819 raise ValueError('argument %s must be callable' % func)
813 820 self._post_execute[func] = True
814 821
815 822 #-------------------------------------------------------------------------
816 823 # Things related to the "main" module
817 824 #-------------------------------------------------------------------------
818 825
819 826 def new_main_mod(self,ns=None):
820 827 """Return a new 'main' module object for user code execution.
821 828 """
822 829 main_mod = self._user_main_module
823 830 init_fakemod_dict(main_mod,ns)
824 831 return main_mod
825 832
826 833 def cache_main_mod(self,ns,fname):
827 834 """Cache a main module's namespace.
828 835
829 836 When scripts are executed via %run, we must keep a reference to the
830 837 namespace of their __main__ module (a FakeModule instance) around so
831 838 that Python doesn't clear it, rendering objects defined therein
832 839 useless.
833 840
834 841 This method keeps said reference in a private dict, keyed by the
835 842 absolute path of the module object (which corresponds to the script
836 843 path). This way, for multiple executions of the same script we only
837 844 keep one copy of the namespace (the last one), thus preventing memory
838 845 leaks from old references while allowing the objects from the last
839 846 execution to be accessible.
840 847
841 848 Note: we can not allow the actual FakeModule instances to be deleted,
842 849 because of how Python tears down modules (it hard-sets all their
843 850 references to None without regard for reference counts). This method
844 851 must therefore make a *copy* of the given namespace, to allow the
845 852 original module's __dict__ to be cleared and reused.
846 853
847 854
848 855 Parameters
849 856 ----------
850 857 ns : a namespace (a dict, typically)
851 858
852 859 fname : str
853 860 Filename associated with the namespace.
854 861
855 862 Examples
856 863 --------
857 864
858 865 In [10]: import IPython
859 866
860 867 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
861 868
862 869 In [12]: IPython.__file__ in _ip._main_ns_cache
863 870 Out[12]: True
864 871 """
865 872 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
866 873
867 874 def clear_main_mod_cache(self):
868 875 """Clear the cache of main modules.
869 876
870 877 Mainly for use by utilities like %reset.
871 878
872 879 Examples
873 880 --------
874 881
875 882 In [15]: import IPython
876 883
877 884 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
878 885
879 886 In [17]: len(_ip._main_ns_cache) > 0
880 887 Out[17]: True
881 888
882 889 In [18]: _ip.clear_main_mod_cache()
883 890
884 891 In [19]: len(_ip._main_ns_cache) == 0
885 892 Out[19]: True
886 893 """
887 894 self._main_ns_cache.clear()
888 895
889 896 #-------------------------------------------------------------------------
890 897 # Things related to debugging
891 898 #-------------------------------------------------------------------------
892 899
893 900 def init_pdb(self):
894 901 # Set calling of pdb on exceptions
895 902 # self.call_pdb is a property
896 903 self.call_pdb = self.pdb
897 904
898 905 def _get_call_pdb(self):
899 906 return self._call_pdb
900 907
901 908 def _set_call_pdb(self,val):
902 909
903 910 if val not in (0,1,False,True):
904 911 raise ValueError('new call_pdb value must be boolean')
905 912
906 913 # store value in instance
907 914 self._call_pdb = val
908 915
909 916 # notify the actual exception handlers
910 917 self.InteractiveTB.call_pdb = val
911 918
912 919 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
913 920 'Control auto-activation of pdb at exceptions')
914 921
915 922 def debugger(self,force=False):
916 923 """Call the pydb/pdb debugger.
917 924
918 925 Keywords:
919 926
920 927 - force(False): by default, this routine checks the instance call_pdb
921 928 flag and does not actually invoke the debugger if the flag is false.
922 929 The 'force' option forces the debugger to activate even if the flag
923 930 is false.
924 931 """
925 932
926 933 if not (force or self.call_pdb):
927 934 return
928 935
929 936 if not hasattr(sys,'last_traceback'):
930 937 error('No traceback has been produced, nothing to debug.')
931 938 return
932 939
933 940 # use pydb if available
934 941 if debugger.has_pydb:
935 942 from pydb import pm
936 943 else:
937 944 # fallback to our internal debugger
938 945 pm = lambda : self.InteractiveTB.debugger(force=True)
939 946
940 947 with self.readline_no_record:
941 948 pm()
942 949
943 950 #-------------------------------------------------------------------------
944 951 # Things related to IPython's various namespaces
945 952 #-------------------------------------------------------------------------
946 953 default_user_namespaces = True
947 954
948 955 def init_create_namespaces(self, user_module=None, user_ns=None):
949 956 # Create the namespace where the user will operate. user_ns is
950 957 # normally the only one used, and it is passed to the exec calls as
951 958 # the locals argument. But we do carry a user_global_ns namespace
952 959 # given as the exec 'globals' argument, This is useful in embedding
953 960 # situations where the ipython shell opens in a context where the
954 961 # distinction between locals and globals is meaningful. For
955 962 # non-embedded contexts, it is just the same object as the user_ns dict.
956 963
957 964 # FIXME. For some strange reason, __builtins__ is showing up at user
958 965 # level as a dict instead of a module. This is a manual fix, but I
959 966 # should really track down where the problem is coming from. Alex
960 967 # Schmolck reported this problem first.
961 968
962 969 # A useful post by Alex Martelli on this topic:
963 970 # Re: inconsistent value from __builtins__
964 971 # Von: Alex Martelli <aleaxit@yahoo.com>
965 972 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
966 973 # Gruppen: comp.lang.python
967 974
968 975 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
969 976 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
970 977 # > <type 'dict'>
971 978 # > >>> print type(__builtins__)
972 979 # > <type 'module'>
973 980 # > Is this difference in return value intentional?
974 981
975 982 # Well, it's documented that '__builtins__' can be either a dictionary
976 983 # or a module, and it's been that way for a long time. Whether it's
977 984 # intentional (or sensible), I don't know. In any case, the idea is
978 985 # that if you need to access the built-in namespace directly, you
979 986 # should start with "import __builtin__" (note, no 's') which will
980 987 # definitely give you a module. Yeah, it's somewhat confusing:-(.
981 988
982 989 # These routines return a properly built module and dict as needed by
983 990 # the rest of the code, and can also be used by extension writers to
984 991 # generate properly initialized namespaces.
985 992 if (user_ns is not None) or (user_module is not None):
986 993 self.default_user_namespaces = False
987 994 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
988 995
989 996 # A record of hidden variables we have added to the user namespace, so
990 997 # we can list later only variables defined in actual interactive use.
991 998 self.user_ns_hidden = set()
992 999
993 1000 # Now that FakeModule produces a real module, we've run into a nasty
994 1001 # problem: after script execution (via %run), the module where the user
995 1002 # code ran is deleted. Now that this object is a true module (needed
996 1003 # so docetst and other tools work correctly), the Python module
997 1004 # teardown mechanism runs over it, and sets to None every variable
998 1005 # present in that module. Top-level references to objects from the
999 1006 # script survive, because the user_ns is updated with them. However,
1000 1007 # calling functions defined in the script that use other things from
1001 1008 # the script will fail, because the function's closure had references
1002 1009 # to the original objects, which are now all None. So we must protect
1003 1010 # these modules from deletion by keeping a cache.
1004 1011 #
1005 1012 # To avoid keeping stale modules around (we only need the one from the
1006 1013 # last run), we use a dict keyed with the full path to the script, so
1007 1014 # only the last version of the module is held in the cache. Note,
1008 1015 # however, that we must cache the module *namespace contents* (their
1009 1016 # __dict__). Because if we try to cache the actual modules, old ones
1010 1017 # (uncached) could be destroyed while still holding references (such as
1011 1018 # those held by GUI objects that tend to be long-lived)>
1012 1019 #
1013 1020 # The %reset command will flush this cache. See the cache_main_mod()
1014 1021 # and clear_main_mod_cache() methods for details on use.
1015 1022
1016 1023 # This is the cache used for 'main' namespaces
1017 1024 self._main_ns_cache = {}
1018 1025 # And this is the single instance of FakeModule whose __dict__ we keep
1019 1026 # copying and clearing for reuse on each %run
1020 1027 self._user_main_module = FakeModule()
1021 1028
1022 1029 # A table holding all the namespaces IPython deals with, so that
1023 1030 # introspection facilities can search easily.
1024 1031 self.ns_table = {'user_global':self.user_module.__dict__,
1025 1032 'user_local':self.user_ns,
1026 1033 'builtin':builtin_mod.__dict__
1027 1034 }
1028 1035
1029 1036 @property
1030 1037 def user_global_ns(self):
1031 1038 return self.user_module.__dict__
1032 1039
1033 1040 def prepare_user_module(self, user_module=None, user_ns=None):
1034 1041 """Prepare the module and namespace in which user code will be run.
1035 1042
1036 1043 When IPython is started normally, both parameters are None: a new module
1037 1044 is created automatically, and its __dict__ used as the namespace.
1038 1045
1039 1046 If only user_module is provided, its __dict__ is used as the namespace.
1040 1047 If only user_ns is provided, a dummy module is created, and user_ns
1041 1048 becomes the global namespace. If both are provided (as they may be
1042 1049 when embedding), user_ns is the local namespace, and user_module
1043 1050 provides the global namespace.
1044 1051
1045 1052 Parameters
1046 1053 ----------
1047 1054 user_module : module, optional
1048 1055 The current user module in which IPython is being run. If None,
1049 1056 a clean module will be created.
1050 1057 user_ns : dict, optional
1051 1058 A namespace in which to run interactive commands.
1052 1059
1053 1060 Returns
1054 1061 -------
1055 1062 A tuple of user_module and user_ns, each properly initialised.
1056 1063 """
1057 1064 if user_module is None and user_ns is not None:
1058 1065 user_ns.setdefault("__name__", "__main__")
1059 1066 class DummyMod(object):
1060 1067 "A dummy module used for IPython's interactive namespace."
1061 1068 pass
1062 1069 user_module = DummyMod()
1063 1070 user_module.__dict__ = user_ns
1064 1071
1065 1072 if user_module is None:
1066 1073 user_module = types.ModuleType("__main__",
1067 1074 doc="Automatically created module for IPython interactive environment")
1068 1075
1069 1076 # We must ensure that __builtin__ (without the final 's') is always
1070 1077 # available and pointing to the __builtin__ *module*. For more details:
1071 1078 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1072 1079 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1073 1080 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1074 1081
1075 1082 if user_ns is None:
1076 1083 user_ns = user_module.__dict__
1077 1084
1078 1085 return user_module, user_ns
1079 1086
1080 1087 def init_sys_modules(self):
1081 1088 # We need to insert into sys.modules something that looks like a
1082 1089 # module but which accesses the IPython namespace, for shelve and
1083 1090 # pickle to work interactively. Normally they rely on getting
1084 1091 # everything out of __main__, but for embedding purposes each IPython
1085 1092 # instance has its own private namespace, so we can't go shoving
1086 1093 # everything into __main__.
1087 1094
1088 1095 # note, however, that we should only do this for non-embedded
1089 1096 # ipythons, which really mimic the __main__.__dict__ with their own
1090 1097 # namespace. Embedded instances, on the other hand, should not do
1091 1098 # this because they need to manage the user local/global namespaces
1092 1099 # only, but they live within a 'normal' __main__ (meaning, they
1093 1100 # shouldn't overtake the execution environment of the script they're
1094 1101 # embedded in).
1095 1102
1096 1103 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1097 1104 main_name = self.user_module.__name__
1098 1105 sys.modules[main_name] = self.user_module
1099 1106
1100 1107 def init_user_ns(self):
1101 1108 """Initialize all user-visible namespaces to their minimum defaults.
1102 1109
1103 1110 Certain history lists are also initialized here, as they effectively
1104 1111 act as user namespaces.
1105 1112
1106 1113 Notes
1107 1114 -----
1108 1115 All data structures here are only filled in, they are NOT reset by this
1109 1116 method. If they were not empty before, data will simply be added to
1110 1117 therm.
1111 1118 """
1112 1119 # This function works in two parts: first we put a few things in
1113 1120 # user_ns, and we sync that contents into user_ns_hidden so that these
1114 1121 # initial variables aren't shown by %who. After the sync, we add the
1115 1122 # rest of what we *do* want the user to see with %who even on a new
1116 1123 # session (probably nothing, so theye really only see their own stuff)
1117 1124
1118 1125 # The user dict must *always* have a __builtin__ reference to the
1119 1126 # Python standard __builtin__ namespace, which must be imported.
1120 1127 # This is so that certain operations in prompt evaluation can be
1121 1128 # reliably executed with builtins. Note that we can NOT use
1122 1129 # __builtins__ (note the 's'), because that can either be a dict or a
1123 1130 # module, and can even mutate at runtime, depending on the context
1124 1131 # (Python makes no guarantees on it). In contrast, __builtin__ is
1125 1132 # always a module object, though it must be explicitly imported.
1126 1133
1127 1134 # For more details:
1128 1135 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1129 1136 ns = dict()
1130 1137
1131 1138 # Put 'help' in the user namespace
1132 1139 try:
1133 1140 from site import _Helper
1134 1141 ns['help'] = _Helper()
1135 1142 except ImportError:
1136 1143 warn('help() not available - check site.py')
1137 1144
1138 1145 # make global variables for user access to the histories
1139 1146 ns['_ih'] = self.history_manager.input_hist_parsed
1140 1147 ns['_oh'] = self.history_manager.output_hist
1141 1148 ns['_dh'] = self.history_manager.dir_hist
1142 1149
1143 1150 ns['_sh'] = shadowns
1144 1151
1145 1152 # user aliases to input and output histories. These shouldn't show up
1146 1153 # in %who, as they can have very large reprs.
1147 1154 ns['In'] = self.history_manager.input_hist_parsed
1148 1155 ns['Out'] = self.history_manager.output_hist
1149 1156
1150 1157 # Store myself as the public api!!!
1151 1158 ns['get_ipython'] = self.get_ipython
1152 1159
1153 1160 ns['exit'] = self.exiter
1154 1161 ns['quit'] = self.exiter
1155 1162
1156 1163 # Sync what we've added so far to user_ns_hidden so these aren't seen
1157 1164 # by %who
1158 1165 self.user_ns_hidden.update(ns)
1159 1166
1160 1167 # Anything put into ns now would show up in %who. Think twice before
1161 1168 # putting anything here, as we really want %who to show the user their
1162 1169 # stuff, not our variables.
1163 1170
1164 1171 # Finally, update the real user's namespace
1165 1172 self.user_ns.update(ns)
1166 1173
1167 1174 @property
1168 1175 def all_ns_refs(self):
1169 1176 """Get a list of references to all the namespace dictionaries in which
1170 1177 IPython might store a user-created object.
1171 1178
1172 1179 Note that this does not include the displayhook, which also caches
1173 1180 objects from the output."""
1174 1181 return [self.user_ns, self.user_global_ns,
1175 1182 self._user_main_module.__dict__] + self._main_ns_cache.values()
1176 1183
1177 1184 def reset(self, new_session=True):
1178 1185 """Clear all internal namespaces, and attempt to release references to
1179 1186 user objects.
1180 1187
1181 1188 If new_session is True, a new history session will be opened.
1182 1189 """
1183 1190 # Clear histories
1184 1191 self.history_manager.reset(new_session)
1185 1192 # Reset counter used to index all histories
1186 1193 if new_session:
1187 1194 self.execution_count = 1
1188 1195
1189 1196 # Flush cached output items
1190 1197 if self.displayhook.do_full_cache:
1191 1198 self.displayhook.flush()
1192 1199
1193 1200 # The main execution namespaces must be cleared very carefully,
1194 1201 # skipping the deletion of the builtin-related keys, because doing so
1195 1202 # would cause errors in many object's __del__ methods.
1196 1203 if self.user_ns is not self.user_global_ns:
1197 1204 self.user_ns.clear()
1198 1205 ns = self.user_global_ns
1199 1206 drop_keys = set(ns.keys())
1200 1207 drop_keys.discard('__builtin__')
1201 1208 drop_keys.discard('__builtins__')
1202 1209 drop_keys.discard('__name__')
1203 1210 for k in drop_keys:
1204 1211 del ns[k]
1205 1212
1206 1213 self.user_ns_hidden.clear()
1207 1214
1208 1215 # Restore the user namespaces to minimal usability
1209 1216 self.init_user_ns()
1210 1217
1211 1218 # Restore the default and user aliases
1212 1219 self.alias_manager.clear_aliases()
1213 1220 self.alias_manager.init_aliases()
1214 1221
1215 1222 # Flush the private list of module references kept for script
1216 1223 # execution protection
1217 1224 self.clear_main_mod_cache()
1218 1225
1219 1226 # Clear out the namespace from the last %run
1220 1227 self.new_main_mod()
1221 1228
1222 1229 def del_var(self, varname, by_name=False):
1223 1230 """Delete a variable from the various namespaces, so that, as
1224 1231 far as possible, we're not keeping any hidden references to it.
1225 1232
1226 1233 Parameters
1227 1234 ----------
1228 1235 varname : str
1229 1236 The name of the variable to delete.
1230 1237 by_name : bool
1231 1238 If True, delete variables with the given name in each
1232 1239 namespace. If False (default), find the variable in the user
1233 1240 namespace, and delete references to it.
1234 1241 """
1235 1242 if varname in ('__builtin__', '__builtins__'):
1236 1243 raise ValueError("Refusing to delete %s" % varname)
1237 1244
1238 1245 ns_refs = self.all_ns_refs
1239 1246
1240 1247 if by_name: # Delete by name
1241 1248 for ns in ns_refs:
1242 1249 try:
1243 1250 del ns[varname]
1244 1251 except KeyError:
1245 1252 pass
1246 1253 else: # Delete by object
1247 1254 try:
1248 1255 obj = self.user_ns[varname]
1249 1256 except KeyError:
1250 1257 raise NameError("name '%s' is not defined" % varname)
1251 1258 # Also check in output history
1252 1259 ns_refs.append(self.history_manager.output_hist)
1253 1260 for ns in ns_refs:
1254 1261 to_delete = [n for n, o in ns.iteritems() if o is obj]
1255 1262 for name in to_delete:
1256 1263 del ns[name]
1257 1264
1258 1265 # displayhook keeps extra references, but not in a dictionary
1259 1266 for name in ('_', '__', '___'):
1260 1267 if getattr(self.displayhook, name) is obj:
1261 1268 setattr(self.displayhook, name, None)
1262 1269
1263 1270 def reset_selective(self, regex=None):
1264 1271 """Clear selective variables from internal namespaces based on a
1265 1272 specified regular expression.
1266 1273
1267 1274 Parameters
1268 1275 ----------
1269 1276 regex : string or compiled pattern, optional
1270 1277 A regular expression pattern that will be used in searching
1271 1278 variable names in the users namespaces.
1272 1279 """
1273 1280 if regex is not None:
1274 1281 try:
1275 1282 m = re.compile(regex)
1276 1283 except TypeError:
1277 1284 raise TypeError('regex must be a string or compiled pattern')
1278 1285 # Search for keys in each namespace that match the given regex
1279 1286 # If a match is found, delete the key/value pair.
1280 1287 for ns in self.all_ns_refs:
1281 1288 for var in ns:
1282 1289 if m.search(var):
1283 1290 del ns[var]
1284 1291
1285 1292 def push(self, variables, interactive=True):
1286 1293 """Inject a group of variables into the IPython user namespace.
1287 1294
1288 1295 Parameters
1289 1296 ----------
1290 1297 variables : dict, str or list/tuple of str
1291 1298 The variables to inject into the user's namespace. If a dict, a
1292 1299 simple update is done. If a str, the string is assumed to have
1293 1300 variable names separated by spaces. A list/tuple of str can also
1294 1301 be used to give the variable names. If just the variable names are
1295 1302 give (list/tuple/str) then the variable values looked up in the
1296 1303 callers frame.
1297 1304 interactive : bool
1298 1305 If True (default), the variables will be listed with the ``who``
1299 1306 magic.
1300 1307 """
1301 1308 vdict = None
1302 1309
1303 1310 # We need a dict of name/value pairs to do namespace updates.
1304 1311 if isinstance(variables, dict):
1305 1312 vdict = variables
1306 1313 elif isinstance(variables, (basestring, list, tuple)):
1307 1314 if isinstance(variables, basestring):
1308 1315 vlist = variables.split()
1309 1316 else:
1310 1317 vlist = variables
1311 1318 vdict = {}
1312 1319 cf = sys._getframe(1)
1313 1320 for name in vlist:
1314 1321 try:
1315 1322 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1316 1323 except:
1317 1324 print('Could not get variable %s from %s' %
1318 1325 (name,cf.f_code.co_name))
1319 1326 else:
1320 1327 raise ValueError('variables must be a dict/str/list/tuple')
1321 1328
1322 1329 # Propagate variables to user namespace
1323 1330 self.user_ns.update(vdict)
1324 1331
1325 1332 # And configure interactive visibility
1326 1333 user_ns_hidden = self.user_ns_hidden
1327 1334 if interactive:
1328 1335 user_ns_hidden.difference_update(vdict)
1329 1336 else:
1330 1337 user_ns_hidden.update(vdict)
1331 1338
1332 1339 def drop_by_id(self, variables):
1333 1340 """Remove a dict of variables from the user namespace, if they are the
1334 1341 same as the values in the dictionary.
1335 1342
1336 1343 This is intended for use by extensions: variables that they've added can
1337 1344 be taken back out if they are unloaded, without removing any that the
1338 1345 user has overwritten.
1339 1346
1340 1347 Parameters
1341 1348 ----------
1342 1349 variables : dict
1343 1350 A dictionary mapping object names (as strings) to the objects.
1344 1351 """
1345 1352 for name, obj in variables.iteritems():
1346 1353 if name in self.user_ns and self.user_ns[name] is obj:
1347 1354 del self.user_ns[name]
1348 1355 self.user_ns_hidden.discard(name)
1349 1356
1350 1357 #-------------------------------------------------------------------------
1351 1358 # Things related to object introspection
1352 1359 #-------------------------------------------------------------------------
1353 1360
1354 1361 def _ofind(self, oname, namespaces=None):
1355 1362 """Find an object in the available namespaces.
1356 1363
1357 1364 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1358 1365
1359 1366 Has special code to detect magic functions.
1360 1367 """
1361 1368 oname = oname.strip()
1362 1369 #print '1- oname: <%r>' % oname # dbg
1363 1370 if not oname.startswith(ESC_MAGIC) and \
1364 1371 not oname.startswith(ESC_MAGIC2) and \
1365 1372 not py3compat.isidentifier(oname, dotted=True):
1366 1373 return dict(found=False)
1367 1374
1368 1375 alias_ns = None
1369 1376 if namespaces is None:
1370 1377 # Namespaces to search in:
1371 1378 # Put them in a list. The order is important so that we
1372 1379 # find things in the same order that Python finds them.
1373 1380 namespaces = [ ('Interactive', self.user_ns),
1374 1381 ('Interactive (global)', self.user_global_ns),
1375 1382 ('Python builtin', builtin_mod.__dict__),
1376 1383 ('Alias', self.alias_manager.alias_table),
1377 1384 ]
1378 1385 alias_ns = self.alias_manager.alias_table
1379 1386
1380 1387 # initialize results to 'null'
1381 1388 found = False; obj = None; ospace = None; ds = None;
1382 1389 ismagic = False; isalias = False; parent = None
1383 1390
1384 1391 # We need to special-case 'print', which as of python2.6 registers as a
1385 1392 # function but should only be treated as one if print_function was
1386 1393 # loaded with a future import. In this case, just bail.
1387 1394 if (oname == 'print' and not py3compat.PY3 and not \
1388 1395 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1389 1396 return {'found':found, 'obj':obj, 'namespace':ospace,
1390 1397 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1391 1398
1392 1399 # Look for the given name by splitting it in parts. If the head is
1393 1400 # found, then we look for all the remaining parts as members, and only
1394 1401 # declare success if we can find them all.
1395 1402 oname_parts = oname.split('.')
1396 1403 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1397 1404 for nsname,ns in namespaces:
1398 1405 try:
1399 1406 obj = ns[oname_head]
1400 1407 except KeyError:
1401 1408 continue
1402 1409 else:
1403 1410 #print 'oname_rest:', oname_rest # dbg
1404 1411 for part in oname_rest:
1405 1412 try:
1406 1413 parent = obj
1407 1414 obj = getattr(obj,part)
1408 1415 except:
1409 1416 # Blanket except b/c some badly implemented objects
1410 1417 # allow __getattr__ to raise exceptions other than
1411 1418 # AttributeError, which then crashes IPython.
1412 1419 break
1413 1420 else:
1414 1421 # If we finish the for loop (no break), we got all members
1415 1422 found = True
1416 1423 ospace = nsname
1417 1424 if ns == alias_ns:
1418 1425 isalias = True
1419 1426 break # namespace loop
1420 1427
1421 1428 # Try to see if it's magic
1422 1429 if not found:
1423 1430 obj = None
1424 1431 if oname.startswith(ESC_MAGIC2):
1425 1432 oname = oname.lstrip(ESC_MAGIC2)
1426 1433 obj = self.find_cell_magic(oname)
1427 1434 elif oname.startswith(ESC_MAGIC):
1428 1435 oname = oname.lstrip(ESC_MAGIC)
1429 1436 obj = self.find_line_magic(oname)
1430 1437 else:
1431 1438 # search without prefix, so run? will find %run?
1432 1439 obj = self.find_line_magic(oname)
1433 1440 if obj is None:
1434 1441 obj = self.find_cell_magic(oname)
1435 1442 if obj is not None:
1436 1443 found = True
1437 1444 ospace = 'IPython internal'
1438 1445 ismagic = True
1439 1446
1440 1447 # Last try: special-case some literals like '', [], {}, etc:
1441 1448 if not found and oname_head in ["''",'""','[]','{}','()']:
1442 1449 obj = eval(oname_head)
1443 1450 found = True
1444 1451 ospace = 'Interactive'
1445 1452
1446 1453 return {'found':found, 'obj':obj, 'namespace':ospace,
1447 1454 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1448 1455
1449 1456 def _ofind_property(self, oname, info):
1450 1457 """Second part of object finding, to look for property details."""
1451 1458 if info.found:
1452 1459 # Get the docstring of the class property if it exists.
1453 1460 path = oname.split('.')
1454 1461 root = '.'.join(path[:-1])
1455 1462 if info.parent is not None:
1456 1463 try:
1457 1464 target = getattr(info.parent, '__class__')
1458 1465 # The object belongs to a class instance.
1459 1466 try:
1460 1467 target = getattr(target, path[-1])
1461 1468 # The class defines the object.
1462 1469 if isinstance(target, property):
1463 1470 oname = root + '.__class__.' + path[-1]
1464 1471 info = Struct(self._ofind(oname))
1465 1472 except AttributeError: pass
1466 1473 except AttributeError: pass
1467 1474
1468 1475 # We return either the new info or the unmodified input if the object
1469 1476 # hadn't been found
1470 1477 return info
1471 1478
1472 1479 def _object_find(self, oname, namespaces=None):
1473 1480 """Find an object and return a struct with info about it."""
1474 1481 inf = Struct(self._ofind(oname, namespaces))
1475 1482 return Struct(self._ofind_property(oname, inf))
1476 1483
1477 1484 def _inspect(self, meth, oname, namespaces=None, **kw):
1478 1485 """Generic interface to the inspector system.
1479 1486
1480 1487 This function is meant to be called by pdef, pdoc & friends."""
1481 1488 info = self._object_find(oname, namespaces)
1482 1489 if info.found:
1483 1490 pmethod = getattr(self.inspector, meth)
1484 1491 formatter = format_screen if info.ismagic else None
1485 1492 if meth == 'pdoc':
1486 1493 pmethod(info.obj, oname, formatter)
1487 1494 elif meth == 'pinfo':
1488 1495 pmethod(info.obj, oname, formatter, info, **kw)
1489 1496 else:
1490 1497 pmethod(info.obj, oname)
1491 1498 else:
1492 1499 print('Object `%s` not found.' % oname)
1493 1500 return 'not found' # so callers can take other action
1494 1501
1495 1502 def object_inspect(self, oname, detail_level=0):
1496 1503 with self.builtin_trap:
1497 1504 info = self._object_find(oname)
1498 1505 if info.found:
1499 1506 return self.inspector.info(info.obj, oname, info=info,
1500 1507 detail_level=detail_level
1501 1508 )
1502 1509 else:
1503 1510 return oinspect.object_info(name=oname, found=False)
1504 1511
1505 1512 #-------------------------------------------------------------------------
1506 1513 # Things related to history management
1507 1514 #-------------------------------------------------------------------------
1508 1515
1509 1516 def init_history(self):
1510 1517 """Sets up the command history, and starts regular autosaves."""
1511 1518 self.history_manager = HistoryManager(shell=self, config=self.config)
1512 1519 self.configurables.append(self.history_manager)
1513 1520
1514 1521 #-------------------------------------------------------------------------
1515 1522 # Things related to exception handling and tracebacks (not debugging)
1516 1523 #-------------------------------------------------------------------------
1517 1524
1518 1525 def init_traceback_handlers(self, custom_exceptions):
1519 1526 # Syntax error handler.
1520 1527 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1521 1528
1522 1529 # The interactive one is initialized with an offset, meaning we always
1523 1530 # want to remove the topmost item in the traceback, which is our own
1524 1531 # internal code. Valid modes: ['Plain','Context','Verbose']
1525 1532 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1526 1533 color_scheme='NoColor',
1527 1534 tb_offset = 1,
1528 1535 check_cache=self.compile.check_cache)
1529 1536
1530 1537 # The instance will store a pointer to the system-wide exception hook,
1531 1538 # so that runtime code (such as magics) can access it. This is because
1532 1539 # during the read-eval loop, it may get temporarily overwritten.
1533 1540 self.sys_excepthook = sys.excepthook
1534 1541
1535 1542 # and add any custom exception handlers the user may have specified
1536 1543 self.set_custom_exc(*custom_exceptions)
1537 1544
1538 1545 # Set the exception mode
1539 1546 self.InteractiveTB.set_mode(mode=self.xmode)
1540 1547
1541 1548 def set_custom_exc(self, exc_tuple, handler):
1542 1549 """set_custom_exc(exc_tuple,handler)
1543 1550
1544 1551 Set a custom exception handler, which will be called if any of the
1545 1552 exceptions in exc_tuple occur in the mainloop (specifically, in the
1546 1553 run_code() method).
1547 1554
1548 1555 Parameters
1549 1556 ----------
1550 1557
1551 1558 exc_tuple : tuple of exception classes
1552 1559 A *tuple* of exception classes, for which to call the defined
1553 1560 handler. It is very important that you use a tuple, and NOT A
1554 1561 LIST here, because of the way Python's except statement works. If
1555 1562 you only want to trap a single exception, use a singleton tuple::
1556 1563
1557 1564 exc_tuple == (MyCustomException,)
1558 1565
1559 1566 handler : callable
1560 1567 handler must have the following signature::
1561 1568
1562 1569 def my_handler(self, etype, value, tb, tb_offset=None):
1563 1570 ...
1564 1571 return structured_traceback
1565 1572
1566 1573 Your handler must return a structured traceback (a list of strings),
1567 1574 or None.
1568 1575
1569 1576 This will be made into an instance method (via types.MethodType)
1570 1577 of IPython itself, and it will be called if any of the exceptions
1571 1578 listed in the exc_tuple are caught. If the handler is None, an
1572 1579 internal basic one is used, which just prints basic info.
1573 1580
1574 1581 To protect IPython from crashes, if your handler ever raises an
1575 1582 exception or returns an invalid result, it will be immediately
1576 1583 disabled.
1577 1584
1578 1585 WARNING: by putting in your own exception handler into IPython's main
1579 1586 execution loop, you run a very good chance of nasty crashes. This
1580 1587 facility should only be used if you really know what you are doing."""
1581 1588
1582 1589 assert type(exc_tuple)==type(()) , \
1583 1590 "The custom exceptions must be given AS A TUPLE."
1584 1591
1585 1592 def dummy_handler(self,etype,value,tb,tb_offset=None):
1586 1593 print('*** Simple custom exception handler ***')
1587 1594 print('Exception type :',etype)
1588 1595 print('Exception value:',value)
1589 1596 print('Traceback :',tb)
1590 1597 #print 'Source code :','\n'.join(self.buffer)
1591 1598
1592 1599 def validate_stb(stb):
1593 1600 """validate structured traceback return type
1594 1601
1595 1602 return type of CustomTB *should* be a list of strings, but allow
1596 1603 single strings or None, which are harmless.
1597 1604
1598 1605 This function will *always* return a list of strings,
1599 1606 and will raise a TypeError if stb is inappropriate.
1600 1607 """
1601 1608 msg = "CustomTB must return list of strings, not %r" % stb
1602 1609 if stb is None:
1603 1610 return []
1604 1611 elif isinstance(stb, basestring):
1605 1612 return [stb]
1606 1613 elif not isinstance(stb, list):
1607 1614 raise TypeError(msg)
1608 1615 # it's a list
1609 1616 for line in stb:
1610 1617 # check every element
1611 1618 if not isinstance(line, basestring):
1612 1619 raise TypeError(msg)
1613 1620 return stb
1614 1621
1615 1622 if handler is None:
1616 1623 wrapped = dummy_handler
1617 1624 else:
1618 1625 def wrapped(self,etype,value,tb,tb_offset=None):
1619 1626 """wrap CustomTB handler, to protect IPython from user code
1620 1627
1621 1628 This makes it harder (but not impossible) for custom exception
1622 1629 handlers to crash IPython.
1623 1630 """
1624 1631 try:
1625 1632 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1626 1633 return validate_stb(stb)
1627 1634 except:
1628 1635 # clear custom handler immediately
1629 1636 self.set_custom_exc((), None)
1630 1637 print("Custom TB Handler failed, unregistering", file=io.stderr)
1631 1638 # show the exception in handler first
1632 1639 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1633 1640 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1634 1641 print("The original exception:", file=io.stdout)
1635 1642 stb = self.InteractiveTB.structured_traceback(
1636 1643 (etype,value,tb), tb_offset=tb_offset
1637 1644 )
1638 1645 return stb
1639 1646
1640 1647 self.CustomTB = types.MethodType(wrapped,self)
1641 1648 self.custom_exceptions = exc_tuple
1642 1649
1643 1650 def excepthook(self, etype, value, tb):
1644 1651 """One more defense for GUI apps that call sys.excepthook.
1645 1652
1646 1653 GUI frameworks like wxPython trap exceptions and call
1647 1654 sys.excepthook themselves. I guess this is a feature that
1648 1655 enables them to keep running after exceptions that would
1649 1656 otherwise kill their mainloop. This is a bother for IPython
1650 1657 which excepts to catch all of the program exceptions with a try:
1651 1658 except: statement.
1652 1659
1653 1660 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1654 1661 any app directly invokes sys.excepthook, it will look to the user like
1655 1662 IPython crashed. In order to work around this, we can disable the
1656 1663 CrashHandler and replace it with this excepthook instead, which prints a
1657 1664 regular traceback using our InteractiveTB. In this fashion, apps which
1658 1665 call sys.excepthook will generate a regular-looking exception from
1659 1666 IPython, and the CrashHandler will only be triggered by real IPython
1660 1667 crashes.
1661 1668
1662 1669 This hook should be used sparingly, only in places which are not likely
1663 1670 to be true IPython errors.
1664 1671 """
1665 1672 self.showtraceback((etype,value,tb),tb_offset=0)
1666 1673
1667 1674 def _get_exc_info(self, exc_tuple=None):
1668 1675 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1669 1676
1670 1677 Ensures sys.last_type,value,traceback hold the exc_info we found,
1671 1678 from whichever source.
1672 1679
1673 1680 raises ValueError if none of these contain any information
1674 1681 """
1675 1682 if exc_tuple is None:
1676 1683 etype, value, tb = sys.exc_info()
1677 1684 else:
1678 1685 etype, value, tb = exc_tuple
1679 1686
1680 1687 if etype is None:
1681 1688 if hasattr(sys, 'last_type'):
1682 1689 etype, value, tb = sys.last_type, sys.last_value, \
1683 1690 sys.last_traceback
1684 1691
1685 1692 if etype is None:
1686 1693 raise ValueError("No exception to find")
1687 1694
1688 1695 # Now store the exception info in sys.last_type etc.
1689 1696 # WARNING: these variables are somewhat deprecated and not
1690 1697 # necessarily safe to use in a threaded environment, but tools
1691 1698 # like pdb depend on their existence, so let's set them. If we
1692 1699 # find problems in the field, we'll need to revisit their use.
1693 1700 sys.last_type = etype
1694 1701 sys.last_value = value
1695 1702 sys.last_traceback = tb
1696 1703
1697 1704 return etype, value, tb
1698 1705
1699 1706
1700 1707 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1701 1708 exception_only=False):
1702 1709 """Display the exception that just occurred.
1703 1710
1704 1711 If nothing is known about the exception, this is the method which
1705 1712 should be used throughout the code for presenting user tracebacks,
1706 1713 rather than directly invoking the InteractiveTB object.
1707 1714
1708 1715 A specific showsyntaxerror() also exists, but this method can take
1709 1716 care of calling it if needed, so unless you are explicitly catching a
1710 1717 SyntaxError exception, don't try to analyze the stack manually and
1711 1718 simply call this method."""
1712 1719
1713 1720 try:
1714 1721 try:
1715 1722 etype, value, tb = self._get_exc_info(exc_tuple)
1716 1723 except ValueError:
1717 1724 self.write_err('No traceback available to show.\n')
1718 1725 return
1719 1726
1720 1727 if issubclass(etype, SyntaxError):
1721 1728 # Though this won't be called by syntax errors in the input
1722 1729 # line, there may be SyntaxError cases with imported code.
1723 1730 self.showsyntaxerror(filename)
1724 1731 elif etype is UsageError:
1725 1732 self.write_err("UsageError: %s" % value)
1726 1733 else:
1727 1734 if exception_only:
1728 1735 stb = ['An exception has occurred, use %tb to see '
1729 1736 'the full traceback.\n']
1730 1737 stb.extend(self.InteractiveTB.get_exception_only(etype,
1731 1738 value))
1732 1739 else:
1733 1740 try:
1734 1741 # Exception classes can customise their traceback - we
1735 1742 # use this in IPython.parallel for exceptions occurring
1736 1743 # in the engines. This should return a list of strings.
1737 1744 stb = value._render_traceback_()
1738 1745 except Exception:
1739 1746 stb = self.InteractiveTB.structured_traceback(etype,
1740 1747 value, tb, tb_offset=tb_offset)
1741 1748
1742 1749 self._showtraceback(etype, value, stb)
1743 1750 if self.call_pdb:
1744 1751 # drop into debugger
1745 1752 self.debugger(force=True)
1746 1753 return
1747 1754
1748 1755 # Actually show the traceback
1749 1756 self._showtraceback(etype, value, stb)
1750 1757
1751 1758 except KeyboardInterrupt:
1752 1759 self.write_err("\nKeyboardInterrupt\n")
1753 1760
1754 1761 def _showtraceback(self, etype, evalue, stb):
1755 1762 """Actually show a traceback.
1756 1763
1757 1764 Subclasses may override this method to put the traceback on a different
1758 1765 place, like a side channel.
1759 1766 """
1760 1767 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1761 1768
1762 1769 def showsyntaxerror(self, filename=None):
1763 1770 """Display the syntax error that just occurred.
1764 1771
1765 1772 This doesn't display a stack trace because there isn't one.
1766 1773
1767 1774 If a filename is given, it is stuffed in the exception instead
1768 1775 of what was there before (because Python's parser always uses
1769 1776 "<string>" when reading from a string).
1770 1777 """
1771 1778 etype, value, last_traceback = self._get_exc_info()
1772 1779
1773 1780 if filename and issubclass(etype, SyntaxError):
1774 1781 try:
1775 1782 value.filename = filename
1776 1783 except:
1777 1784 # Not the format we expect; leave it alone
1778 1785 pass
1779 1786
1780 1787 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1781 1788 self._showtraceback(etype, value, stb)
1782 1789
1783 1790 # This is overridden in TerminalInteractiveShell to show a message about
1784 1791 # the %paste magic.
1785 1792 def showindentationerror(self):
1786 1793 """Called by run_cell when there's an IndentationError in code entered
1787 1794 at the prompt.
1788 1795
1789 1796 This is overridden in TerminalInteractiveShell to show a message about
1790 1797 the %paste magic."""
1791 1798 self.showsyntaxerror()
1792 1799
1793 1800 #-------------------------------------------------------------------------
1794 1801 # Things related to readline
1795 1802 #-------------------------------------------------------------------------
1796 1803
1797 1804 def init_readline(self):
1798 1805 """Command history completion/saving/reloading."""
1799 1806
1800 1807 if self.readline_use:
1801 1808 import IPython.utils.rlineimpl as readline
1802 1809
1803 1810 self.rl_next_input = None
1804 1811 self.rl_do_indent = False
1805 1812
1806 1813 if not self.readline_use or not readline.have_readline:
1807 1814 self.has_readline = False
1808 1815 self.readline = None
1809 1816 # Set a number of methods that depend on readline to be no-op
1810 1817 self.readline_no_record = no_op_context
1811 1818 self.set_readline_completer = no_op
1812 1819 self.set_custom_completer = no_op
1813 1820 if self.readline_use:
1814 1821 warn('Readline services not available or not loaded.')
1815 1822 else:
1816 1823 self.has_readline = True
1817 1824 self.readline = readline
1818 1825 sys.modules['readline'] = readline
1819 1826
1820 1827 # Platform-specific configuration
1821 1828 if os.name == 'nt':
1822 1829 # FIXME - check with Frederick to see if we can harmonize
1823 1830 # naming conventions with pyreadline to avoid this
1824 1831 # platform-dependent check
1825 1832 self.readline_startup_hook = readline.set_pre_input_hook
1826 1833 else:
1827 1834 self.readline_startup_hook = readline.set_startup_hook
1828 1835
1829 1836 # Load user's initrc file (readline config)
1830 1837 # Or if libedit is used, load editrc.
1831 1838 inputrc_name = os.environ.get('INPUTRC')
1832 1839 if inputrc_name is None:
1833 1840 inputrc_name = '.inputrc'
1834 1841 if readline.uses_libedit:
1835 1842 inputrc_name = '.editrc'
1836 1843 inputrc_name = os.path.join(self.home_dir, inputrc_name)
1837 1844 if os.path.isfile(inputrc_name):
1838 1845 try:
1839 1846 readline.read_init_file(inputrc_name)
1840 1847 except:
1841 1848 warn('Problems reading readline initialization file <%s>'
1842 1849 % inputrc_name)
1843 1850
1844 1851 # Configure readline according to user's prefs
1845 1852 # This is only done if GNU readline is being used. If libedit
1846 1853 # is being used (as on Leopard) the readline config is
1847 1854 # not run as the syntax for libedit is different.
1848 1855 if not readline.uses_libedit:
1849 1856 for rlcommand in self.readline_parse_and_bind:
1850 1857 #print "loading rl:",rlcommand # dbg
1851 1858 readline.parse_and_bind(rlcommand)
1852 1859
1853 1860 # Remove some chars from the delimiters list. If we encounter
1854 1861 # unicode chars, discard them.
1855 1862 delims = readline.get_completer_delims()
1856 1863 if not py3compat.PY3:
1857 1864 delims = delims.encode("ascii", "ignore")
1858 1865 for d in self.readline_remove_delims:
1859 1866 delims = delims.replace(d, "")
1860 1867 delims = delims.replace(ESC_MAGIC, '')
1861 1868 readline.set_completer_delims(delims)
1862 1869 # otherwise we end up with a monster history after a while:
1863 1870 readline.set_history_length(self.history_length)
1864 1871
1865 1872 self.refill_readline_hist()
1866 1873 self.readline_no_record = ReadlineNoRecord(self)
1867 1874
1868 1875 # Configure auto-indent for all platforms
1869 1876 self.set_autoindent(self.autoindent)
1870 1877
1871 1878 def refill_readline_hist(self):
1872 1879 # Load the last 1000 lines from history
1873 1880 self.readline.clear_history()
1874 1881 stdin_encoding = sys.stdin.encoding or "utf-8"
1875 1882 last_cell = u""
1876 1883 for _, _, cell in self.history_manager.get_tail(1000,
1877 1884 include_latest=True):
1878 1885 # Ignore blank lines and consecutive duplicates
1879 1886 cell = cell.rstrip()
1880 1887 if cell and (cell != last_cell):
1881 1888 if self.multiline_history:
1882 1889 self.readline.add_history(py3compat.unicode_to_str(cell,
1883 1890 stdin_encoding))
1884 1891 else:
1885 1892 for line in cell.splitlines():
1886 1893 self.readline.add_history(py3compat.unicode_to_str(line,
1887 1894 stdin_encoding))
1888 1895 last_cell = cell
1889 1896
1890 1897 def set_next_input(self, s):
1891 1898 """ Sets the 'default' input string for the next command line.
1892 1899
1893 1900 Requires readline.
1894 1901
1895 1902 Example:
1896 1903
1897 1904 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1898 1905 [D:\ipython]|2> Hello Word_ # cursor is here
1899 1906 """
1900 1907 self.rl_next_input = py3compat.cast_bytes_py2(s)
1901 1908
1902 1909 # Maybe move this to the terminal subclass?
1903 1910 def pre_readline(self):
1904 1911 """readline hook to be used at the start of each line.
1905 1912
1906 1913 Currently it handles auto-indent only."""
1907 1914
1908 1915 if self.rl_do_indent:
1909 1916 self.readline.insert_text(self._indent_current_str())
1910 1917 if self.rl_next_input is not None:
1911 1918 self.readline.insert_text(self.rl_next_input)
1912 1919 self.rl_next_input = None
1913 1920
1914 1921 def _indent_current_str(self):
1915 1922 """return the current level of indentation as a string"""
1916 1923 return self.input_splitter.indent_spaces * ' '
1917 1924
1918 1925 #-------------------------------------------------------------------------
1919 1926 # Things related to text completion
1920 1927 #-------------------------------------------------------------------------
1921 1928
1922 1929 def init_completer(self):
1923 1930 """Initialize the completion machinery.
1924 1931
1925 1932 This creates completion machinery that can be used by client code,
1926 1933 either interactively in-process (typically triggered by the readline
1927 1934 library), programatically (such as in test suites) or out-of-prcess
1928 1935 (typically over the network by remote frontends).
1929 1936 """
1930 1937 from IPython.core.completer import IPCompleter
1931 1938 from IPython.core.completerlib import (module_completer,
1932 1939 magic_run_completer, cd_completer, reset_completer)
1933 1940
1934 1941 self.Completer = IPCompleter(shell=self,
1935 1942 namespace=self.user_ns,
1936 1943 global_namespace=self.user_global_ns,
1937 1944 alias_table=self.alias_manager.alias_table,
1938 1945 use_readline=self.has_readline,
1939 1946 config=self.config,
1940 1947 )
1941 1948 self.configurables.append(self.Completer)
1942 1949
1943 1950 # Add custom completers to the basic ones built into IPCompleter
1944 1951 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1945 1952 self.strdispatchers['complete_command'] = sdisp
1946 1953 self.Completer.custom_completers = sdisp
1947 1954
1948 1955 self.set_hook('complete_command', module_completer, str_key = 'import')
1949 1956 self.set_hook('complete_command', module_completer, str_key = 'from')
1950 1957 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1951 1958 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1952 1959 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1953 1960
1954 1961 # Only configure readline if we truly are using readline. IPython can
1955 1962 # do tab-completion over the network, in GUIs, etc, where readline
1956 1963 # itself may be absent
1957 1964 if self.has_readline:
1958 1965 self.set_readline_completer()
1959 1966
1960 1967 def complete(self, text, line=None, cursor_pos=None):
1961 1968 """Return the completed text and a list of completions.
1962 1969
1963 1970 Parameters
1964 1971 ----------
1965 1972
1966 1973 text : string
1967 1974 A string of text to be completed on. It can be given as empty and
1968 1975 instead a line/position pair are given. In this case, the
1969 1976 completer itself will split the line like readline does.
1970 1977
1971 1978 line : string, optional
1972 1979 The complete line that text is part of.
1973 1980
1974 1981 cursor_pos : int, optional
1975 1982 The position of the cursor on the input line.
1976 1983
1977 1984 Returns
1978 1985 -------
1979 1986 text : string
1980 1987 The actual text that was completed.
1981 1988
1982 1989 matches : list
1983 1990 A sorted list with all possible completions.
1984 1991
1985 1992 The optional arguments allow the completion to take more context into
1986 1993 account, and are part of the low-level completion API.
1987 1994
1988 1995 This is a wrapper around the completion mechanism, similar to what
1989 1996 readline does at the command line when the TAB key is hit. By
1990 1997 exposing it as a method, it can be used by other non-readline
1991 1998 environments (such as GUIs) for text completion.
1992 1999
1993 2000 Simple usage example:
1994 2001
1995 2002 In [1]: x = 'hello'
1996 2003
1997 2004 In [2]: _ip.complete('x.l')
1998 2005 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1999 2006 """
2000 2007
2001 2008 # Inject names into __builtin__ so we can complete on the added names.
2002 2009 with self.builtin_trap:
2003 2010 return self.Completer.complete(text, line, cursor_pos)
2004 2011
2005 2012 def set_custom_completer(self, completer, pos=0):
2006 2013 """Adds a new custom completer function.
2007 2014
2008 2015 The position argument (defaults to 0) is the index in the completers
2009 2016 list where you want the completer to be inserted."""
2010 2017
2011 2018 newcomp = types.MethodType(completer,self.Completer)
2012 2019 self.Completer.matchers.insert(pos,newcomp)
2013 2020
2014 2021 def set_readline_completer(self):
2015 2022 """Reset readline's completer to be our own."""
2016 2023 self.readline.set_completer(self.Completer.rlcomplete)
2017 2024
2018 2025 def set_completer_frame(self, frame=None):
2019 2026 """Set the frame of the completer."""
2020 2027 if frame:
2021 2028 self.Completer.namespace = frame.f_locals
2022 2029 self.Completer.global_namespace = frame.f_globals
2023 2030 else:
2024 2031 self.Completer.namespace = self.user_ns
2025 2032 self.Completer.global_namespace = self.user_global_ns
2026 2033
2027 2034 #-------------------------------------------------------------------------
2028 2035 # Things related to magics
2029 2036 #-------------------------------------------------------------------------
2030 2037
2031 2038 def init_magics(self):
2032 2039 from IPython.core import magics as m
2033 2040 self.magics_manager = magic.MagicsManager(shell=self,
2034 2041 confg=self.config,
2035 2042 user_magics=m.UserMagics(self))
2036 2043 self.configurables.append(self.magics_manager)
2037 2044
2038 2045 # Expose as public API from the magics manager
2039 2046 self.register_magics = self.magics_manager.register
2040 2047 self.register_magic_function = self.magics_manager.register_function
2041 2048 self.define_magic = self.magics_manager.define_magic
2042 2049
2043 2050 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2044 2051 m.ConfigMagics, m.DeprecatedMagics, m.DisplayMagics, m.ExecutionMagics,
2045 2052 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2046 2053 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2047 2054 )
2048 2055
2049 2056 # Register Magic Aliases
2050 2057 mman = self.magics_manager
2051 2058 mman.register_alias('ed', 'edit')
2052 2059 mman.register_alias('hist', 'history')
2053 2060 mman.register_alias('rep', 'recall')
2054 2061
2055 2062 # FIXME: Move the color initialization to the DisplayHook, which
2056 2063 # should be split into a prompt manager and displayhook. We probably
2057 2064 # even need a centralize colors management object.
2058 2065 self.magic('colors %s' % self.colors)
2059 2066
2060 2067 def run_line_magic(self, magic_name, line):
2061 2068 """Execute the given line magic.
2062 2069
2063 2070 Parameters
2064 2071 ----------
2065 2072 magic_name : str
2066 2073 Name of the desired magic function, without '%' prefix.
2067 2074
2068 2075 line : str
2069 2076 The rest of the input line as a single string.
2070 2077 """
2071 2078 fn = self.find_line_magic(magic_name)
2072 2079 if fn is None:
2073 2080 cm = self.find_cell_magic(magic_name)
2074 2081 etpl = "Line magic function `%%%s` not found%s."
2075 2082 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2076 2083 'did you mean that instead?)' % magic_name )
2077 2084 error(etpl % (magic_name, extra))
2078 2085 else:
2079 2086 # Note: this is the distance in the stack to the user's frame.
2080 2087 # This will need to be updated if the internal calling logic gets
2081 2088 # refactored, or else we'll be expanding the wrong variables.
2082 2089 stack_depth = 2
2083 2090 magic_arg_s = self.var_expand(line, stack_depth)
2084 2091 # Put magic args in a list so we can call with f(*a) syntax
2085 2092 args = [magic_arg_s]
2086 2093 kwargs = {}
2087 2094 # Grab local namespace if we need it:
2088 2095 if getattr(fn, "needs_local_scope", False):
2089 2096 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2090 2097 with self.builtin_trap:
2091 2098 result = fn(*args,**kwargs)
2092 2099 return result
2093 2100
2094 2101 def run_cell_magic(self, magic_name, line, cell):
2095 2102 """Execute the given cell magic.
2096 2103
2097 2104 Parameters
2098 2105 ----------
2099 2106 magic_name : str
2100 2107 Name of the desired magic function, without '%' prefix.
2101 2108
2102 2109 line : str
2103 2110 The rest of the first input line as a single string.
2104 2111
2105 2112 cell : str
2106 2113 The body of the cell as a (possibly multiline) string.
2107 2114 """
2108 2115 fn = self.find_cell_magic(magic_name)
2109 2116 if fn is None:
2110 2117 lm = self.find_line_magic(magic_name)
2111 2118 etpl = "Cell magic function `%%%%%s` not found%s."
2112 2119 extra = '' if lm is None else (' (But line magic `%%%s` exists, '
2113 2120 'did you mean that instead?)' % magic_name )
2114 2121 error(etpl % (magic_name, extra))
2115 2122 else:
2116 2123 # Note: this is the distance in the stack to the user's frame.
2117 2124 # This will need to be updated if the internal calling logic gets
2118 2125 # refactored, or else we'll be expanding the wrong variables.
2119 2126 stack_depth = 2
2120 2127 magic_arg_s = self.var_expand(line, stack_depth)
2121 2128 with self.builtin_trap:
2122 2129 result = fn(magic_arg_s, cell)
2123 2130 return result
2124 2131
2125 2132 def find_line_magic(self, magic_name):
2126 2133 """Find and return a line magic by name.
2127 2134
2128 2135 Returns None if the magic isn't found."""
2129 2136 return self.magics_manager.magics['line'].get(magic_name)
2130 2137
2131 2138 def find_cell_magic(self, magic_name):
2132 2139 """Find and return a cell magic by name.
2133 2140
2134 2141 Returns None if the magic isn't found."""
2135 2142 return self.magics_manager.magics['cell'].get(magic_name)
2136 2143
2137 2144 def find_magic(self, magic_name, magic_kind='line'):
2138 2145 """Find and return a magic of the given type by name.
2139 2146
2140 2147 Returns None if the magic isn't found."""
2141 2148 return self.magics_manager.magics[magic_kind].get(magic_name)
2142 2149
2143 2150 def magic(self, arg_s):
2144 2151 """DEPRECATED. Use run_line_magic() instead.
2145 2152
2146 2153 Call a magic function by name.
2147 2154
2148 2155 Input: a string containing the name of the magic function to call and
2149 2156 any additional arguments to be passed to the magic.
2150 2157
2151 2158 magic('name -opt foo bar') is equivalent to typing at the ipython
2152 2159 prompt:
2153 2160
2154 2161 In[1]: %name -opt foo bar
2155 2162
2156 2163 To call a magic without arguments, simply use magic('name').
2157 2164
2158 2165 This provides a proper Python function to call IPython's magics in any
2159 2166 valid Python code you can type at the interpreter, including loops and
2160 2167 compound statements.
2161 2168 """
2162 2169 # TODO: should we issue a loud deprecation warning here?
2163 2170 magic_name, _, magic_arg_s = arg_s.partition(' ')
2164 2171 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2165 2172 return self.run_line_magic(magic_name, magic_arg_s)
2166 2173
2167 2174 #-------------------------------------------------------------------------
2168 2175 # Things related to macros
2169 2176 #-------------------------------------------------------------------------
2170 2177
2171 2178 def define_macro(self, name, themacro):
2172 2179 """Define a new macro
2173 2180
2174 2181 Parameters
2175 2182 ----------
2176 2183 name : str
2177 2184 The name of the macro.
2178 2185 themacro : str or Macro
2179 2186 The action to do upon invoking the macro. If a string, a new
2180 2187 Macro object is created by passing the string to it.
2181 2188 """
2182 2189
2183 2190 from IPython.core import macro
2184 2191
2185 2192 if isinstance(themacro, basestring):
2186 2193 themacro = macro.Macro(themacro)
2187 2194 if not isinstance(themacro, macro.Macro):
2188 2195 raise ValueError('A macro must be a string or a Macro instance.')
2189 2196 self.user_ns[name] = themacro
2190 2197
2191 2198 #-------------------------------------------------------------------------
2192 2199 # Things related to the running of system commands
2193 2200 #-------------------------------------------------------------------------
2194 2201
2195 2202 def system_piped(self, cmd):
2196 2203 """Call the given cmd in a subprocess, piping stdout/err
2197 2204
2198 2205 Parameters
2199 2206 ----------
2200 2207 cmd : str
2201 2208 Command to execute (can not end in '&', as background processes are
2202 2209 not supported. Should not be a command that expects input
2203 2210 other than simple text.
2204 2211 """
2205 2212 if cmd.rstrip().endswith('&'):
2206 2213 # this is *far* from a rigorous test
2207 2214 # We do not support backgrounding processes because we either use
2208 2215 # pexpect or pipes to read from. Users can always just call
2209 2216 # os.system() or use ip.system=ip.system_raw
2210 2217 # if they really want a background process.
2211 2218 raise OSError("Background processes not supported.")
2212 2219
2213 2220 # we explicitly do NOT return the subprocess status code, because
2214 2221 # a non-None value would trigger :func:`sys.displayhook` calls.
2215 2222 # Instead, we store the exit_code in user_ns.
2216 2223 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2217 2224
2218 2225 def system_raw(self, cmd):
2219 2226 """Call the given cmd in a subprocess using os.system
2220 2227
2221 2228 Parameters
2222 2229 ----------
2223 2230 cmd : str
2224 2231 Command to execute.
2225 2232 """
2226 2233 cmd = self.var_expand(cmd, depth=1)
2227 2234 # protect os.system from UNC paths on Windows, which it can't handle:
2228 2235 if sys.platform == 'win32':
2229 2236 from IPython.utils._process_win32 import AvoidUNCPath
2230 2237 with AvoidUNCPath() as path:
2231 2238 if path is not None:
2232 2239 cmd = '"pushd %s &&"%s' % (path, cmd)
2233 2240 cmd = py3compat.unicode_to_str(cmd)
2234 2241 ec = os.system(cmd)
2235 2242 else:
2236 2243 cmd = py3compat.unicode_to_str(cmd)
2237 2244 ec = os.system(cmd)
2238 2245
2239 2246 # We explicitly do NOT return the subprocess status code, because
2240 2247 # a non-None value would trigger :func:`sys.displayhook` calls.
2241 2248 # Instead, we store the exit_code in user_ns.
2242 2249 self.user_ns['_exit_code'] = ec
2243 2250
2244 2251 # use piped system by default, because it is better behaved
2245 2252 system = system_piped
2246 2253
2247 2254 def getoutput(self, cmd, split=True, depth=0):
2248 2255 """Get output (possibly including stderr) from a subprocess.
2249 2256
2250 2257 Parameters
2251 2258 ----------
2252 2259 cmd : str
2253 2260 Command to execute (can not end in '&', as background processes are
2254 2261 not supported.
2255 2262 split : bool, optional
2256 2263 If True, split the output into an IPython SList. Otherwise, an
2257 2264 IPython LSString is returned. These are objects similar to normal
2258 2265 lists and strings, with a few convenience attributes for easier
2259 2266 manipulation of line-based output. You can use '?' on them for
2260 2267 details.
2261 2268 depth : int, optional
2262 2269 How many frames above the caller are the local variables which should
2263 2270 be expanded in the command string? The default (0) assumes that the
2264 2271 expansion variables are in the stack frame calling this function.
2265 2272 """
2266 2273 if cmd.rstrip().endswith('&'):
2267 2274 # this is *far* from a rigorous test
2268 2275 raise OSError("Background processes not supported.")
2269 2276 out = getoutput(self.var_expand(cmd, depth=depth+1))
2270 2277 if split:
2271 2278 out = SList(out.splitlines())
2272 2279 else:
2273 2280 out = LSString(out)
2274 2281 return out
2275 2282
2276 2283 #-------------------------------------------------------------------------
2277 2284 # Things related to aliases
2278 2285 #-------------------------------------------------------------------------
2279 2286
2280 2287 def init_alias(self):
2281 2288 self.alias_manager = AliasManager(shell=self, config=self.config)
2282 2289 self.configurables.append(self.alias_manager)
2283 2290 self.ns_table['alias'] = self.alias_manager.alias_table,
2284 2291
2285 2292 #-------------------------------------------------------------------------
2286 2293 # Things related to extensions
2287 2294 #-------------------------------------------------------------------------
2288 2295
2289 2296 def init_extension_manager(self):
2290 2297 self.extension_manager = ExtensionManager(shell=self, config=self.config)
2291 2298 self.configurables.append(self.extension_manager)
2292 2299
2293 2300 #-------------------------------------------------------------------------
2294 2301 # Things related to payloads
2295 2302 #-------------------------------------------------------------------------
2296 2303
2297 2304 def init_payload(self):
2298 2305 self.payload_manager = PayloadManager(config=self.config)
2299 2306 self.configurables.append(self.payload_manager)
2300 2307
2301 2308 #-------------------------------------------------------------------------
2302 2309 # Things related to the prefilter
2303 2310 #-------------------------------------------------------------------------
2304 2311
2305 2312 def init_prefilter(self):
2306 2313 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
2307 2314 self.configurables.append(self.prefilter_manager)
2308 2315 # Ultimately this will be refactored in the new interpreter code, but
2309 2316 # for now, we should expose the main prefilter method (there's legacy
2310 2317 # code out there that may rely on this).
2311 2318 self.prefilter = self.prefilter_manager.prefilter_lines
2312 2319
2313 2320 def auto_rewrite_input(self, cmd):
2314 2321 """Print to the screen the rewritten form of the user's command.
2315 2322
2316 2323 This shows visual feedback by rewriting input lines that cause
2317 2324 automatic calling to kick in, like::
2318 2325
2319 2326 /f x
2320 2327
2321 2328 into::
2322 2329
2323 2330 ------> f(x)
2324 2331
2325 2332 after the user's input prompt. This helps the user understand that the
2326 2333 input line was transformed automatically by IPython.
2327 2334 """
2328 2335 if not self.show_rewritten_input:
2329 2336 return
2330 2337
2331 2338 rw = self.prompt_manager.render('rewrite') + cmd
2332 2339
2333 2340 try:
2334 2341 # plain ascii works better w/ pyreadline, on some machines, so
2335 2342 # we use it and only print uncolored rewrite if we have unicode
2336 2343 rw = str(rw)
2337 2344 print(rw, file=io.stdout)
2338 2345 except UnicodeEncodeError:
2339 2346 print("------> " + cmd)
2340 2347
2341 2348 #-------------------------------------------------------------------------
2342 2349 # Things related to extracting values/expressions from kernel and user_ns
2343 2350 #-------------------------------------------------------------------------
2344 2351
2345 2352 def _simple_error(self):
2346 2353 etype, value = sys.exc_info()[:2]
2347 2354 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
2348 2355
2349 2356 def user_variables(self, names):
2350 2357 """Get a list of variable names from the user's namespace.
2351 2358
2352 2359 Parameters
2353 2360 ----------
2354 2361 names : list of strings
2355 2362 A list of names of variables to be read from the user namespace.
2356 2363
2357 2364 Returns
2358 2365 -------
2359 2366 A dict, keyed by the input names and with the repr() of each value.
2360 2367 """
2361 2368 out = {}
2362 2369 user_ns = self.user_ns
2363 2370 for varname in names:
2364 2371 try:
2365 2372 value = repr(user_ns[varname])
2366 2373 except:
2367 2374 value = self._simple_error()
2368 2375 out[varname] = value
2369 2376 return out
2370 2377
2371 2378 def user_expressions(self, expressions):
2372 2379 """Evaluate a dict of expressions in the user's namespace.
2373 2380
2374 2381 Parameters
2375 2382 ----------
2376 2383 expressions : dict
2377 2384 A dict with string keys and string values. The expression values
2378 2385 should be valid Python expressions, each of which will be evaluated
2379 2386 in the user namespace.
2380 2387
2381 2388 Returns
2382 2389 -------
2383 2390 A dict, keyed like the input expressions dict, with the repr() of each
2384 2391 value.
2385 2392 """
2386 2393 out = {}
2387 2394 user_ns = self.user_ns
2388 2395 global_ns = self.user_global_ns
2389 2396 for key, expr in expressions.iteritems():
2390 2397 try:
2391 2398 value = repr(eval(expr, global_ns, user_ns))
2392 2399 except:
2393 2400 value = self._simple_error()
2394 2401 out[key] = value
2395 2402 return out
2396 2403
2397 2404 #-------------------------------------------------------------------------
2398 2405 # Things related to the running of code
2399 2406 #-------------------------------------------------------------------------
2400 2407
2401 2408 def ex(self, cmd):
2402 2409 """Execute a normal python statement in user namespace."""
2403 2410 with self.builtin_trap:
2404 2411 exec cmd in self.user_global_ns, self.user_ns
2405 2412
2406 2413 def ev(self, expr):
2407 2414 """Evaluate python expression expr in user namespace.
2408 2415
2409 2416 Returns the result of evaluation
2410 2417 """
2411 2418 with self.builtin_trap:
2412 2419 return eval(expr, self.user_global_ns, self.user_ns)
2413 2420
2414 2421 def safe_execfile(self, fname, *where, **kw):
2415 2422 """A safe version of the builtin execfile().
2416 2423
2417 2424 This version will never throw an exception, but instead print
2418 2425 helpful error messages to the screen. This only works on pure
2419 2426 Python files with the .py extension.
2420 2427
2421 2428 Parameters
2422 2429 ----------
2423 2430 fname : string
2424 2431 The name of the file to be executed.
2425 2432 where : tuple
2426 2433 One or two namespaces, passed to execfile() as (globals,locals).
2427 2434 If only one is given, it is passed as both.
2428 2435 exit_ignore : bool (False)
2429 2436 If True, then silence SystemExit for non-zero status (it is always
2430 2437 silenced for zero status, as it is so common).
2431 2438 raise_exceptions : bool (False)
2432 2439 If True raise exceptions everywhere. Meant for testing.
2433 2440
2434 2441 """
2435 2442 kw.setdefault('exit_ignore', False)
2436 2443 kw.setdefault('raise_exceptions', False)
2437 2444
2438 2445 fname = os.path.abspath(os.path.expanduser(fname))
2439 2446
2440 2447 # Make sure we can open the file
2441 2448 try:
2442 2449 with open(fname) as thefile:
2443 2450 pass
2444 2451 except:
2445 2452 warn('Could not open file <%s> for safe execution.' % fname)
2446 2453 return
2447 2454
2448 2455 # Find things also in current directory. This is needed to mimic the
2449 2456 # behavior of running a script from the system command line, where
2450 2457 # Python inserts the script's directory into sys.path
2451 2458 dname = os.path.dirname(fname)
2452 2459
2453 2460 with prepended_to_syspath(dname):
2454 2461 try:
2455 2462 py3compat.execfile(fname,*where)
2456 2463 except SystemExit as status:
2457 2464 # If the call was made with 0 or None exit status (sys.exit(0)
2458 2465 # or sys.exit() ), don't bother showing a traceback, as both of
2459 2466 # these are considered normal by the OS:
2460 2467 # > python -c'import sys;sys.exit(0)'; echo $?
2461 2468 # 0
2462 2469 # > python -c'import sys;sys.exit()'; echo $?
2463 2470 # 0
2464 2471 # For other exit status, we show the exception unless
2465 2472 # explicitly silenced, but only in short form.
2466 2473 if kw['raise_exceptions']:
2467 2474 raise
2468 2475 if status.code not in (0, None) and not kw['exit_ignore']:
2469 2476 self.showtraceback(exception_only=True)
2470 2477 except:
2471 2478 if kw['raise_exceptions']:
2472 2479 raise
2473 2480 self.showtraceback()
2474 2481
2475 2482 def safe_execfile_ipy(self, fname):
2476 2483 """Like safe_execfile, but for .ipy files with IPython syntax.
2477 2484
2478 2485 Parameters
2479 2486 ----------
2480 2487 fname : str
2481 2488 The name of the file to execute. The filename must have a
2482 2489 .ipy extension.
2483 2490 """
2484 2491 fname = os.path.abspath(os.path.expanduser(fname))
2485 2492
2486 2493 # Make sure we can open the file
2487 2494 try:
2488 2495 with open(fname) as thefile:
2489 2496 pass
2490 2497 except:
2491 2498 warn('Could not open file <%s> for safe execution.' % fname)
2492 2499 return
2493 2500
2494 2501 # Find things also in current directory. This is needed to mimic the
2495 2502 # behavior of running a script from the system command line, where
2496 2503 # Python inserts the script's directory into sys.path
2497 2504 dname = os.path.dirname(fname)
2498 2505
2499 2506 with prepended_to_syspath(dname):
2500 2507 try:
2501 2508 with open(fname) as thefile:
2502 2509 # self.run_cell currently captures all exceptions
2503 2510 # raised in user code. It would be nice if there were
2504 2511 # versions of runlines, execfile that did raise, so
2505 2512 # we could catch the errors.
2506 2513 self.run_cell(thefile.read(), store_history=False)
2507 2514 except:
2508 2515 self.showtraceback()
2509 2516 warn('Unknown failure executing file: <%s>' % fname)
2510 2517
2511 2518 def safe_run_module(self, mod_name, where):
2512 2519 """A safe version of runpy.run_module().
2513 2520
2514 2521 This version will never throw an exception, but instead print
2515 2522 helpful error messages to the screen.
2516 2523
2517 2524 Parameters
2518 2525 ----------
2519 2526 mod_name : string
2520 2527 The name of the module to be executed.
2521 2528 where : dict
2522 2529 The globals namespace.
2523 2530 """
2524 2531 try:
2525 2532 where.update(
2526 2533 runpy.run_module(str(mod_name), run_name="__main__",
2527 2534 alter_sys=True)
2528 2535 )
2529 2536 except:
2530 2537 self.showtraceback()
2531 2538 warn('Unknown failure executing module: <%s>' % mod_name)
2532 2539
2533 2540 def _run_cached_cell_magic(self, magic_name, line):
2534 2541 """Special method to call a cell magic with the data stored in self.
2535 2542 """
2536 2543 cell = self._current_cell_magic_body
2537 2544 self._current_cell_magic_body = None
2538 2545 return self.run_cell_magic(magic_name, line, cell)
2539 2546
2540 2547 def run_cell(self, raw_cell, store_history=False, silent=False):
2541 2548 """Run a complete IPython cell.
2542 2549
2543 2550 Parameters
2544 2551 ----------
2545 2552 raw_cell : str
2546 2553 The code (including IPython code such as %magic functions) to run.
2547 2554 store_history : bool
2548 2555 If True, the raw and translated cell will be stored in IPython's
2549 2556 history. For user code calling back into IPython's machinery, this
2550 2557 should be set to False.
2551 2558 silent : bool
2552 2559 If True, avoid side-effects, such as implicit displayhooks and
2553 2560 and logging. silent=True forces store_history=False.
2554 2561 """
2555 2562 if (not raw_cell) or raw_cell.isspace():
2556 2563 return
2557 2564
2558 2565 if silent:
2559 2566 store_history = False
2560 2567
2561 2568 self.input_splitter.push(raw_cell)
2562 2569
2563 2570 # Check for cell magics, which leave state behind. This interface is
2564 2571 # ugly, we need to do something cleaner later... Now the logic is
2565 2572 # simply that the input_splitter remembers if there was a cell magic,
2566 2573 # and in that case we grab the cell body.
2567 2574 if self.input_splitter.cell_magic_parts:
2568 2575 self._current_cell_magic_body = \
2569 2576 ''.join(self.input_splitter.cell_magic_parts)
2570 2577 cell = self.input_splitter.source_reset()
2571 2578
2572 2579 with self.builtin_trap:
2573 2580 prefilter_failed = False
2574 2581 if len(cell.splitlines()) == 1:
2575 2582 try:
2576 2583 # use prefilter_lines to handle trailing newlines
2577 2584 # restore trailing newline for ast.parse
2578 2585 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2579 2586 except AliasError as e:
2580 2587 error(e)
2581 2588 prefilter_failed = True
2582 2589 except Exception:
2583 2590 # don't allow prefilter errors to crash IPython
2584 2591 self.showtraceback()
2585 2592 prefilter_failed = True
2586 2593
2587 2594 # Store raw and processed history
2588 2595 if store_history:
2589 2596 self.history_manager.store_inputs(self.execution_count,
2590 2597 cell, raw_cell)
2591 2598 if not silent:
2592 2599 self.logger.log(cell, raw_cell)
2593 2600
2594 2601 if not prefilter_failed:
2595 2602 # don't run if prefilter failed
2596 2603 cell_name = self.compile.cache(cell, self.execution_count)
2597 2604
2598 2605 with self.display_trap:
2599 2606 try:
2600 2607 code_ast = self.compile.ast_parse(cell,
2601 2608 filename=cell_name)
2602 2609 except IndentationError:
2603 2610 self.showindentationerror()
2604 2611 if store_history:
2605 2612 self.execution_count += 1
2606 2613 return None
2607 2614 except (OverflowError, SyntaxError, ValueError, TypeError,
2608 2615 MemoryError):
2609 2616 self.showsyntaxerror()
2610 2617 if store_history:
2611 2618 self.execution_count += 1
2612 2619 return None
2613 2620
2621 code_ast = self.transform_ast(code_ast)
2622
2614 2623 interactivity = "none" if silent else self.ast_node_interactivity
2615 2624 self.run_ast_nodes(code_ast.body, cell_name,
2616 2625 interactivity=interactivity)
2617 2626
2618 2627 # Execute any registered post-execution functions.
2619 2628 # unless we are silent
2620 2629 post_exec = [] if silent else self._post_execute.iteritems()
2621 2630
2622 2631 for func, status in post_exec:
2623 2632 if self.disable_failing_post_execute and not status:
2624 2633 continue
2625 2634 try:
2626 2635 func()
2627 2636 except KeyboardInterrupt:
2628 2637 print("\nKeyboardInterrupt", file=io.stderr)
2629 2638 except Exception:
2630 2639 # register as failing:
2631 2640 self._post_execute[func] = False
2632 2641 self.showtraceback()
2633 2642 print('\n'.join([
2634 2643 "post-execution function %r produced an error." % func,
2635 2644 "If this problem persists, you can disable failing post-exec functions with:",
2636 2645 "",
2637 2646 " get_ipython().disable_failing_post_execute = True"
2638 2647 ]), file=io.stderr)
2639 2648
2640 2649 if store_history:
2641 2650 # Write output to the database. Does nothing unless
2642 2651 # history output logging is enabled.
2643 2652 self.history_manager.store_output(self.execution_count)
2644 2653 # Each cell is a *single* input, regardless of how many lines it has
2645 2654 self.execution_count += 1
2655
2656 def transform_ast(self, node):
2657 """Apply the AST transformations from self.ast_transformers
2658
2659 Parameters
2660 ----------
2661 node : ast.Node
2662 The root node to be transformed. Typically called with the ast.Module
2663 produced by parsing user input.
2664
2665 Returns
2666 -------
2667 An ast.Node corresponding to the node it was called with. Note that it
2668 may also modify the passed object, so don't rely on references to the
2669 original AST.
2670 """
2671 for transformer in self.ast_transformers:
2672 try:
2673 node = transformer.visit(node)
2674 except Exception:
2675 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2676 self.ast_transformers.remove(transformer)
2677
2678 return ast.fix_missing_locations(node)
2679
2646 2680
2647 2681 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'):
2648 2682 """Run a sequence of AST nodes. The execution mode depends on the
2649 2683 interactivity parameter.
2650 2684
2651 2685 Parameters
2652 2686 ----------
2653 2687 nodelist : list
2654 2688 A sequence of AST nodes to run.
2655 2689 cell_name : str
2656 2690 Will be passed to the compiler as the filename of the cell. Typically
2657 2691 the value returned by ip.compile.cache(cell).
2658 2692 interactivity : str
2659 2693 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2660 2694 run interactively (displaying output from expressions). 'last_expr'
2661 2695 will run the last node interactively only if it is an expression (i.e.
2662 2696 expressions in loops or other blocks are not displayed. Other values
2663 2697 for this parameter will raise a ValueError.
2664 2698 """
2665 2699 if not nodelist:
2666 2700 return
2667 2701
2668 2702 if interactivity == 'last_expr':
2669 2703 if isinstance(nodelist[-1], ast.Expr):
2670 2704 interactivity = "last"
2671 2705 else:
2672 2706 interactivity = "none"
2673 2707
2674 2708 if interactivity == 'none':
2675 2709 to_run_exec, to_run_interactive = nodelist, []
2676 2710 elif interactivity == 'last':
2677 2711 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2678 2712 elif interactivity == 'all':
2679 2713 to_run_exec, to_run_interactive = [], nodelist
2680 2714 else:
2681 2715 raise ValueError("Interactivity was %r" % interactivity)
2682 2716
2683 2717 exec_count = self.execution_count
2684 2718
2685 2719 try:
2686 2720 for i, node in enumerate(to_run_exec):
2687 2721 mod = ast.Module([node])
2688 2722 code = self.compile(mod, cell_name, "exec")
2689 2723 if self.run_code(code):
2690 2724 return True
2691 2725
2692 2726 for i, node in enumerate(to_run_interactive):
2693 2727 mod = ast.Interactive([node])
2694 2728 code = self.compile(mod, cell_name, "single")
2695 2729 if self.run_code(code):
2696 2730 return True
2697 2731
2698 2732 # Flush softspace
2699 2733 if softspace(sys.stdout, 0):
2700 2734 print()
2701 2735
2702 2736 except:
2703 2737 # It's possible to have exceptions raised here, typically by
2704 2738 # compilation of odd code (such as a naked 'return' outside a
2705 2739 # function) that did parse but isn't valid. Typically the exception
2706 2740 # is a SyntaxError, but it's safest just to catch anything and show
2707 2741 # the user a traceback.
2708 2742
2709 2743 # We do only one try/except outside the loop to minimize the impact
2710 2744 # on runtime, and also because if any node in the node list is
2711 2745 # broken, we should stop execution completely.
2712 2746 self.showtraceback()
2713 2747
2714 2748 return False
2715 2749
2716 2750 def run_code(self, code_obj):
2717 2751 """Execute a code object.
2718 2752
2719 2753 When an exception occurs, self.showtraceback() is called to display a
2720 2754 traceback.
2721 2755
2722 2756 Parameters
2723 2757 ----------
2724 2758 code_obj : code object
2725 2759 A compiled code object, to be executed
2726 2760
2727 2761 Returns
2728 2762 -------
2729 2763 False : successful execution.
2730 2764 True : an error occurred.
2731 2765 """
2732 2766
2733 2767 # Set our own excepthook in case the user code tries to call it
2734 2768 # directly, so that the IPython crash handler doesn't get triggered
2735 2769 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2736 2770
2737 2771 # we save the original sys.excepthook in the instance, in case config
2738 2772 # code (such as magics) needs access to it.
2739 2773 self.sys_excepthook = old_excepthook
2740 2774 outflag = 1 # happens in more places, so it's easier as default
2741 2775 try:
2742 2776 try:
2743 2777 self.hooks.pre_run_code_hook()
2744 2778 #rprint('Running code', repr(code_obj)) # dbg
2745 2779 exec code_obj in self.user_global_ns, self.user_ns
2746 2780 finally:
2747 2781 # Reset our crash handler in place
2748 2782 sys.excepthook = old_excepthook
2749 2783 except SystemExit:
2750 2784 self.showtraceback(exception_only=True)
2751 2785 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2752 2786 except self.custom_exceptions:
2753 2787 etype,value,tb = sys.exc_info()
2754 2788 self.CustomTB(etype,value,tb)
2755 2789 except:
2756 2790 self.showtraceback()
2757 2791 else:
2758 2792 outflag = 0
2759 2793 return outflag
2760 2794
2761 2795 # For backwards compatibility
2762 2796 runcode = run_code
2763 2797
2764 2798 #-------------------------------------------------------------------------
2765 2799 # Things related to GUI support and pylab
2766 2800 #-------------------------------------------------------------------------
2767 2801
2768 2802 def enable_gui(self, gui=None):
2769 2803 raise NotImplementedError('Implement enable_gui in a subclass')
2770 2804
2771 2805 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
2772 2806 """Activate pylab support at runtime.
2773 2807
2774 2808 This turns on support for matplotlib, preloads into the interactive
2775 2809 namespace all of numpy and pylab, and configures IPython to correctly
2776 2810 interact with the GUI event loop. The GUI backend to be used can be
2777 2811 optionally selected with the optional :param:`gui` argument.
2778 2812
2779 2813 Parameters
2780 2814 ----------
2781 2815 gui : optional, string
2782 2816
2783 2817 If given, dictates the choice of matplotlib GUI backend to use
2784 2818 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2785 2819 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2786 2820 matplotlib (as dictated by the matplotlib build-time options plus the
2787 2821 user's matplotlibrc configuration file). Note that not all backends
2788 2822 make sense in all contexts, for example a terminal ipython can't
2789 2823 display figures inline.
2790 2824 """
2791 2825 from IPython.core.pylabtools import mpl_runner
2792 2826 # We want to prevent the loading of pylab to pollute the user's
2793 2827 # namespace as shown by the %who* magics, so we execute the activation
2794 2828 # code in an empty namespace, and we update *both* user_ns and
2795 2829 # user_ns_hidden with this information.
2796 2830 ns = {}
2797 2831 try:
2798 2832 gui = pylab_activate(ns, gui, import_all, self, welcome_message=welcome_message)
2799 2833 except KeyError:
2800 2834 error("Backend %r not supported" % gui)
2801 2835 return
2802 2836 self.user_ns.update(ns)
2803 2837 self.user_ns_hidden.update(ns)
2804 2838 # Now we must activate the gui pylab wants to use, and fix %run to take
2805 2839 # plot updates into account
2806 2840 self.enable_gui(gui)
2807 2841 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2808 2842 mpl_runner(self.safe_execfile)
2809 2843
2810 2844 #-------------------------------------------------------------------------
2811 2845 # Utilities
2812 2846 #-------------------------------------------------------------------------
2813 2847
2814 2848 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
2815 2849 """Expand python variables in a string.
2816 2850
2817 2851 The depth argument indicates how many frames above the caller should
2818 2852 be walked to look for the local namespace where to expand variables.
2819 2853
2820 2854 The global namespace for expansion is always the user's interactive
2821 2855 namespace.
2822 2856 """
2823 2857 ns = self.user_ns.copy()
2824 2858 ns.update(sys._getframe(depth+1).f_locals)
2825 2859 try:
2826 2860 # We have to use .vformat() here, because 'self' is a valid and common
2827 2861 # name, and expanding **ns for .format() would make it collide with
2828 2862 # the 'self' argument of the method.
2829 2863 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
2830 2864 except Exception:
2831 2865 # if formatter couldn't format, just let it go untransformed
2832 2866 pass
2833 2867 return cmd
2834 2868
2835 2869 def mktempfile(self, data=None, prefix='ipython_edit_'):
2836 2870 """Make a new tempfile and return its filename.
2837 2871
2838 2872 This makes a call to tempfile.mktemp, but it registers the created
2839 2873 filename internally so ipython cleans it up at exit time.
2840 2874
2841 2875 Optional inputs:
2842 2876
2843 2877 - data(None): if data is given, it gets written out to the temp file
2844 2878 immediately, and the file is closed again."""
2845 2879
2846 2880 filename = tempfile.mktemp('.py', prefix)
2847 2881 self.tempfiles.append(filename)
2848 2882
2849 2883 if data:
2850 2884 tmp_file = open(filename,'w')
2851 2885 tmp_file.write(data)
2852 2886 tmp_file.close()
2853 2887 return filename
2854 2888
2855 2889 # TODO: This should be removed when Term is refactored.
2856 2890 def write(self,data):
2857 2891 """Write a string to the default output"""
2858 2892 io.stdout.write(data)
2859 2893
2860 2894 # TODO: This should be removed when Term is refactored.
2861 2895 def write_err(self,data):
2862 2896 """Write a string to the default error output"""
2863 2897 io.stderr.write(data)
2864 2898
2865 2899 def ask_yes_no(self, prompt, default=None):
2866 2900 if self.quiet:
2867 2901 return True
2868 2902 return ask_yes_no(prompt,default)
2869 2903
2870 2904 def show_usage(self):
2871 2905 """Show a usage message"""
2872 2906 page.page(IPython.core.usage.interactive_usage)
2873 2907
2874 2908 def extract_input_lines(self, range_str, raw=False):
2875 2909 """Return as a string a set of input history slices.
2876 2910
2877 2911 Parameters
2878 2912 ----------
2879 2913 range_str : string
2880 2914 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
2881 2915 since this function is for use by magic functions which get their
2882 2916 arguments as strings. The number before the / is the session
2883 2917 number: ~n goes n back from the current session.
2884 2918
2885 2919 Optional Parameters:
2886 2920 - raw(False): by default, the processed input is used. If this is
2887 2921 true, the raw input history is used instead.
2888 2922
2889 2923 Note that slices can be called with two notations:
2890 2924
2891 2925 N:M -> standard python form, means including items N...(M-1).
2892 2926
2893 2927 N-M -> include items N..M (closed endpoint)."""
2894 2928 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
2895 2929 return "\n".join(x for _, _, x in lines)
2896 2930
2897 2931 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True):
2898 2932 """Get a code string from history, file, url, or a string or macro.
2899 2933
2900 2934 This is mainly used by magic functions.
2901 2935
2902 2936 Parameters
2903 2937 ----------
2904 2938
2905 2939 target : str
2906 2940
2907 2941 A string specifying code to retrieve. This will be tried respectively
2908 2942 as: ranges of input history (see %history for syntax), url,
2909 2943 correspnding .py file, filename, or an expression evaluating to a
2910 2944 string or Macro in the user namespace.
2911 2945
2912 2946 raw : bool
2913 2947 If true (default), retrieve raw history. Has no effect on the other
2914 2948 retrieval mechanisms.
2915 2949
2916 2950 py_only : bool (default False)
2917 2951 Only try to fetch python code, do not try alternative methods to decode file
2918 2952 if unicode fails.
2919 2953
2920 2954 Returns
2921 2955 -------
2922 2956 A string of code.
2923 2957
2924 2958 ValueError is raised if nothing is found, and TypeError if it evaluates
2925 2959 to an object of another type. In each case, .args[0] is a printable
2926 2960 message.
2927 2961 """
2928 2962 code = self.extract_input_lines(target, raw=raw) # Grab history
2929 2963 if code:
2930 2964 return code
2931 2965 utarget = unquote_filename(target)
2932 2966 try:
2933 2967 if utarget.startswith(('http://', 'https://')):
2934 2968 return openpy.read_py_url(utarget, skip_encoding_cookie=skip_encoding_cookie)
2935 2969 except UnicodeDecodeError:
2936 2970 if not py_only :
2937 2971 response = urllib.urlopen(target)
2938 2972 return response.read().decode('latin1')
2939 2973 raise ValueError(("'%s' seem to be unreadable.") % utarget)
2940 2974
2941 2975 potential_target = [target]
2942 2976 try :
2943 2977 potential_target.insert(0,get_py_filename(target))
2944 2978 except IOError:
2945 2979 pass
2946 2980
2947 2981 for tgt in potential_target :
2948 2982 if os.path.isfile(tgt): # Read file
2949 2983 try :
2950 2984 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
2951 2985 except UnicodeDecodeError :
2952 2986 if not py_only :
2953 2987 with io_open(tgt,'r', encoding='latin1') as f :
2954 2988 return f.read()
2955 2989 raise ValueError(("'%s' seem to be unreadable.") % target)
2956 2990
2957 2991 try: # User namespace
2958 2992 codeobj = eval(target, self.user_ns)
2959 2993 except Exception:
2960 2994 raise ValueError(("'%s' was not found in history, as a file, url, "
2961 2995 "nor in the user namespace.") % target)
2962 2996 if isinstance(codeobj, basestring):
2963 2997 return codeobj
2964 2998 elif isinstance(codeobj, Macro):
2965 2999 return codeobj.value
2966 3000
2967 3001 raise TypeError("%s is neither a string nor a macro." % target,
2968 3002 codeobj)
2969 3003
2970 3004 #-------------------------------------------------------------------------
2971 3005 # Things related to IPython exiting
2972 3006 #-------------------------------------------------------------------------
2973 3007 def atexit_operations(self):
2974 3008 """This will be executed at the time of exit.
2975 3009
2976 3010 Cleanup operations and saving of persistent data that is done
2977 3011 unconditionally by IPython should be performed here.
2978 3012
2979 3013 For things that may depend on startup flags or platform specifics (such
2980 3014 as having readline or not), register a separate atexit function in the
2981 3015 code that has the appropriate information, rather than trying to
2982 3016 clutter
2983 3017 """
2984 3018 # Close the history session (this stores the end time and line count)
2985 3019 # this must be *before* the tempfile cleanup, in case of temporary
2986 3020 # history db
2987 3021 self.history_manager.end_session()
2988 3022
2989 3023 # Cleanup all tempfiles left around
2990 3024 for tfile in self.tempfiles:
2991 3025 try:
2992 3026 os.unlink(tfile)
2993 3027 except OSError:
2994 3028 pass
2995 3029
2996 3030 # Clear all user namespaces to release all references cleanly.
2997 3031 self.reset(new_session=False)
2998 3032
2999 3033 # Run user hooks
3000 3034 self.hooks.shutdown_hook()
3001 3035
3002 3036 def cleanup(self):
3003 3037 self.restore_sys_module_state()
3004 3038
3005 3039
3006 3040 class InteractiveShellABC(object):
3007 3041 """An abstract base class for InteractiveShell."""
3008 3042 __metaclass__ = abc.ABCMeta
3009 3043
3010 3044 InteractiveShellABC.register(InteractiveShell)
@@ -1,1035 +1,1077 b''
1 1 """Implementation of execution-related magic functions.
2 2 """
3 3 #-----------------------------------------------------------------------------
4 4 # Copyright (c) 2012 The IPython Development Team.
5 5 #
6 6 # Distributed under the terms of the Modified BSD License.
7 7 #
8 8 # The full license is in the file COPYING.txt, distributed with this software.
9 9 #-----------------------------------------------------------------------------
10 10
11 11 #-----------------------------------------------------------------------------
12 12 # Imports
13 13 #-----------------------------------------------------------------------------
14 14
15 15 # Stdlib
16 16 import __builtin__ as builtin_mod
17 import ast
17 18 import bdb
18 19 import os
19 20 import sys
20 21 import time
21 22 from StringIO import StringIO
22 23
23 24 # cProfile was added in Python2.5
24 25 try:
25 26 import cProfile as profile
26 27 import pstats
27 28 except ImportError:
28 29 # profile isn't bundled by default in Debian for license reasons
29 30 try:
30 31 import profile, pstats
31 32 except ImportError:
32 33 profile = pstats = None
33 34
34 35 # Our own packages
35 36 from IPython.core import debugger, oinspect
36 37 from IPython.core import magic_arguments
37 38 from IPython.core import page
38 39 from IPython.core.error import UsageError
39 40 from IPython.core.macro import Macro
40 41 from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,
41 42 line_cell_magic, on_off, needs_local_scope)
42 43 from IPython.testing.skipdoctest import skip_doctest
43 44 from IPython.utils import py3compat
44 45 from IPython.utils.io import capture_output
45 46 from IPython.utils.ipstruct import Struct
46 47 from IPython.utils.module_paths import find_mod
47 48 from IPython.utils.path import get_py_filename, unquote_filename, shellglob
48 49 from IPython.utils.timing import clock, clock2
49 50 from IPython.utils.warn import warn, error
50 51
51 52
52 53 #-----------------------------------------------------------------------------
53 54 # Magic implementation classes
54 55 #-----------------------------------------------------------------------------
55 56
56 57 @magics_class
57 58 class ExecutionMagics(Magics):
58 59 """Magics related to code execution, debugging, profiling, etc.
59 60
60 61 """
61 62
62 63 def __init__(self, shell):
63 64 super(ExecutionMagics, self).__init__(shell)
64 65 if profile is None:
65 66 self.prun = self.profile_missing_notice
66 67 # Default execution function used to actually run user code.
67 68 self.default_runner = None
68 69
69 70 def profile_missing_notice(self, *args, **kwargs):
70 71 error("""\
71 72 The profile module could not be found. It has been removed from the standard
72 73 python packages because of its non-free license. To use profiling, install the
73 74 python-profiler package from non-free.""")
74 75
75 76 @skip_doctest
76 77 @line_cell_magic
77 78 def prun(self, parameter_s='', cell=None, user_mode=True,
78 79 opts=None,arg_lst=None,prog_ns=None):
79 80
80 81 """Run a statement through the python code profiler.
81 82
82 83 Usage, in line mode:
83 84 %prun [options] statement
84 85
85 86 Usage, in cell mode:
86 87 %%prun [options] [statement]
87 88 code...
88 89 code...
89 90
90 91 In cell mode, the additional code lines are appended to the (possibly
91 92 empty) statement in the first line. Cell mode allows you to easily
92 93 profile multiline blocks without having to put them in a separate
93 94 function.
94 95
95 96 The given statement (which doesn't require quote marks) is run via the
96 97 python profiler in a manner similar to the profile.run() function.
97 98 Namespaces are internally managed to work correctly; profile.run
98 99 cannot be used in IPython because it makes certain assumptions about
99 100 namespaces which do not hold under IPython.
100 101
101 102 Options:
102 103
103 104 -l <limit>: you can place restrictions on what or how much of the
104 105 profile gets printed. The limit value can be:
105 106
106 107 * A string: only information for function names containing this string
107 108 is printed.
108 109
109 110 * An integer: only these many lines are printed.
110 111
111 112 * A float (between 0 and 1): this fraction of the report is printed
112 113 (for example, use a limit of 0.4 to see the topmost 40% only).
113 114
114 115 You can combine several limits with repeated use of the option. For
115 116 example, '-l __init__ -l 5' will print only the topmost 5 lines of
116 117 information about class constructors.
117 118
118 119 -r: return the pstats.Stats object generated by the profiling. This
119 120 object has all the information about the profile in it, and you can
120 121 later use it for further analysis or in other functions.
121 122
122 123 -s <key>: sort profile by given key. You can provide more than one key
123 124 by using the option several times: '-s key1 -s key2 -s key3...'. The
124 125 default sorting key is 'time'.
125 126
126 127 The following is copied verbatim from the profile documentation
127 128 referenced below:
128 129
129 130 When more than one key is provided, additional keys are used as
130 131 secondary criteria when the there is equality in all keys selected
131 132 before them.
132 133
133 134 Abbreviations can be used for any key names, as long as the
134 135 abbreviation is unambiguous. The following are the keys currently
135 136 defined:
136 137
137 138 Valid Arg Meaning
138 139 "calls" call count
139 140 "cumulative" cumulative time
140 141 "file" file name
141 142 "module" file name
142 143 "pcalls" primitive call count
143 144 "line" line number
144 145 "name" function name
145 146 "nfl" name/file/line
146 147 "stdname" standard name
147 148 "time" internal time
148 149
149 150 Note that all sorts on statistics are in descending order (placing
150 151 most time consuming items first), where as name, file, and line number
151 152 searches are in ascending order (i.e., alphabetical). The subtle
152 153 distinction between "nfl" and "stdname" is that the standard name is a
153 154 sort of the name as printed, which means that the embedded line
154 155 numbers get compared in an odd way. For example, lines 3, 20, and 40
155 156 would (if the file names were the same) appear in the string order
156 157 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
157 158 line numbers. In fact, sort_stats("nfl") is the same as
158 159 sort_stats("name", "file", "line").
159 160
160 161 -T <filename>: save profile results as shown on screen to a text
161 162 file. The profile is still shown on screen.
162 163
163 164 -D <filename>: save (via dump_stats) profile statistics to given
164 165 filename. This data is in a format understood by the pstats module, and
165 166 is generated by a call to the dump_stats() method of profile
166 167 objects. The profile is still shown on screen.
167 168
168 169 -q: suppress output to the pager. Best used with -T and/or -D above.
169 170
170 171 If you want to run complete programs under the profiler's control, use
171 172 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
172 173 contains profiler specific options as described here.
173 174
174 175 You can read the complete documentation for the profile module with::
175 176
176 177 In [1]: import profile; profile.help()
177 178 """
178 179
179 180 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
180 181
181 182 if user_mode: # regular user call
182 183 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:q',
183 184 list_all=True, posix=False)
184 185 namespace = self.shell.user_ns
185 186 if cell is not None:
186 187 arg_str += '\n' + cell
187 188 else: # called to run a program by %run -p
188 189 try:
189 190 filename = get_py_filename(arg_lst[0])
190 191 except IOError as e:
191 192 try:
192 193 msg = str(e)
193 194 except UnicodeError:
194 195 msg = e.message
195 196 error(msg)
196 197 return
197 198
198 199 arg_str = 'execfile(filename,prog_ns)'
199 200 namespace = {
200 201 'execfile': self.shell.safe_execfile,
201 202 'prog_ns': prog_ns,
202 203 'filename': filename
203 204 }
204 205
205 206 opts.merge(opts_def)
206 207
207 208 prof = profile.Profile()
208 209 try:
209 210 prof = prof.runctx(arg_str,namespace,namespace)
210 211 sys_exit = ''
211 212 except SystemExit:
212 213 sys_exit = """*** SystemExit exception caught in code being profiled."""
213 214
214 215 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
215 216
216 217 lims = opts.l
217 218 if lims:
218 219 lims = [] # rebuild lims with ints/floats/strings
219 220 for lim in opts.l:
220 221 try:
221 222 lims.append(int(lim))
222 223 except ValueError:
223 224 try:
224 225 lims.append(float(lim))
225 226 except ValueError:
226 227 lims.append(lim)
227 228
228 229 # Trap output.
229 230 stdout_trap = StringIO()
230 231 stats_stream = stats.stream
231 232 try:
232 233 stats.stream = stdout_trap
233 234 stats.print_stats(*lims)
234 235 finally:
235 236 stats.stream = stats_stream
236 237
237 238 output = stdout_trap.getvalue()
238 239 output = output.rstrip()
239 240
240 241 if 'q' not in opts:
241 242 page.page(output)
242 243 print sys_exit,
243 244
244 245 dump_file = opts.D[0]
245 246 text_file = opts.T[0]
246 247 if dump_file:
247 248 dump_file = unquote_filename(dump_file)
248 249 prof.dump_stats(dump_file)
249 250 print '\n*** Profile stats marshalled to file',\
250 251 repr(dump_file)+'.',sys_exit
251 252 if text_file:
252 253 text_file = unquote_filename(text_file)
253 254 pfile = open(text_file,'w')
254 255 pfile.write(output)
255 256 pfile.close()
256 257 print '\n*** Profile printout saved to text file',\
257 258 repr(text_file)+'.',sys_exit
258 259
259 260 if 'r' in opts:
260 261 return stats
261 262 else:
262 263 return None
263 264
264 265 @line_magic
265 266 def pdb(self, parameter_s=''):
266 267 """Control the automatic calling of the pdb interactive debugger.
267 268
268 269 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
269 270 argument it works as a toggle.
270 271
271 272 When an exception is triggered, IPython can optionally call the
272 273 interactive pdb debugger after the traceback printout. %pdb toggles
273 274 this feature on and off.
274 275
275 276 The initial state of this feature is set in your configuration
276 277 file (the option is ``InteractiveShell.pdb``).
277 278
278 279 If you want to just activate the debugger AFTER an exception has fired,
279 280 without having to type '%pdb on' and rerunning your code, you can use
280 281 the %debug magic."""
281 282
282 283 par = parameter_s.strip().lower()
283 284
284 285 if par:
285 286 try:
286 287 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
287 288 except KeyError:
288 289 print ('Incorrect argument. Use on/1, off/0, '
289 290 'or nothing for a toggle.')
290 291 return
291 292 else:
292 293 # toggle
293 294 new_pdb = not self.shell.call_pdb
294 295
295 296 # set on the shell
296 297 self.shell.call_pdb = new_pdb
297 298 print 'Automatic pdb calling has been turned',on_off(new_pdb)
298 299
299 300 @line_magic
300 301 def debug(self, parameter_s=''):
301 302 """Activate the interactive debugger in post-mortem mode.
302 303
303 304 If an exception has just occurred, this lets you inspect its stack
304 305 frames interactively. Note that this will always work only on the last
305 306 traceback that occurred, so you must call this quickly after an
306 307 exception that you wish to inspect has fired, because if another one
307 308 occurs, it clobbers the previous one.
308 309
309 310 If you want IPython to automatically do this on every exception, see
310 311 the %pdb magic for more details.
311 312 """
312 313 self.shell.debugger(force=True)
313 314
314 315 @line_magic
315 316 def tb(self, s):
316 317 """Print the last traceback with the currently active exception mode.
317 318
318 319 See %xmode for changing exception reporting modes."""
319 320 self.shell.showtraceback()
320 321
321 322 @skip_doctest
322 323 @line_magic
323 324 def run(self, parameter_s='', runner=None,
324 325 file_finder=get_py_filename):
325 326 """Run the named file inside IPython as a program.
326 327
327 328 Usage:\\
328 329 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options] -G] file [args]
329 330
330 331 Parameters after the filename are passed as command-line arguments to
331 332 the program (put in sys.argv). Then, control returns to IPython's
332 333 prompt.
333 334
334 335 This is similar to running at a system prompt:\\
335 336 $ python file args\\
336 337 but with the advantage of giving you IPython's tracebacks, and of
337 338 loading all variables into your interactive namespace for further use
338 339 (unless -p is used, see below).
339 340
340 341 The file is executed in a namespace initially consisting only of
341 342 __name__=='__main__' and sys.argv constructed as indicated. It thus
342 343 sees its environment as if it were being run as a stand-alone program
343 344 (except for sharing global objects such as previously imported
344 345 modules). But after execution, the IPython interactive namespace gets
345 346 updated with all variables defined in the program (except for __name__
346 347 and sys.argv). This allows for very convenient loading of code for
347 348 interactive work, while giving each program a 'clean sheet' to run in.
348 349
349 350 Arguments are expanded using shell-like glob match. Patterns
350 351 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
351 352 tilde '~' will be expanded into user's home directory. Unlike
352 353 real shells, quotation does not suppress expansions. Use
353 354 *two* back slashes (e.g., '\\\\*') to suppress expansions.
354 355 To completely disable these expansions, you can use -G flag.
355 356
356 357 Options:
357 358
358 359 -n: __name__ is NOT set to '__main__', but to the running file's name
359 360 without extension (as python does under import). This allows running
360 361 scripts and reloading the definitions in them without calling code
361 362 protected by an ' if __name__ == "__main__" ' clause.
362 363
363 364 -i: run the file in IPython's namespace instead of an empty one. This
364 365 is useful if you are experimenting with code written in a text editor
365 366 which depends on variables defined interactively.
366 367
367 368 -e: ignore sys.exit() calls or SystemExit exceptions in the script
368 369 being run. This is particularly useful if IPython is being used to
369 370 run unittests, which always exit with a sys.exit() call. In such
370 371 cases you are interested in the output of the test results, not in
371 372 seeing a traceback of the unittest module.
372 373
373 374 -t: print timing information at the end of the run. IPython will give
374 375 you an estimated CPU time consumption for your script, which under
375 376 Unix uses the resource module to avoid the wraparound problems of
376 377 time.clock(). Under Unix, an estimate of time spent on system tasks
377 378 is also given (for Windows platforms this is reported as 0.0).
378 379
379 380 If -t is given, an additional -N<N> option can be given, where <N>
380 381 must be an integer indicating how many times you want the script to
381 382 run. The final timing report will include total and per run results.
382 383
383 384 For example (testing the script uniq_stable.py)::
384 385
385 386 In [1]: run -t uniq_stable
386 387
387 388 IPython CPU timings (estimated):\\
388 389 User : 0.19597 s.\\
389 390 System: 0.0 s.\\
390 391
391 392 In [2]: run -t -N5 uniq_stable
392 393
393 394 IPython CPU timings (estimated):\\
394 395 Total runs performed: 5\\
395 396 Times : Total Per run\\
396 397 User : 0.910862 s, 0.1821724 s.\\
397 398 System: 0.0 s, 0.0 s.
398 399
399 400 -d: run your program under the control of pdb, the Python debugger.
400 401 This allows you to execute your program step by step, watch variables,
401 402 etc. Internally, what IPython does is similar to calling:
402 403
403 404 pdb.run('execfile("YOURFILENAME")')
404 405
405 406 with a breakpoint set on line 1 of your file. You can change the line
406 407 number for this automatic breakpoint to be <N> by using the -bN option
407 408 (where N must be an integer). For example::
408 409
409 410 %run -d -b40 myscript
410 411
411 412 will set the first breakpoint at line 40 in myscript.py. Note that
412 413 the first breakpoint must be set on a line which actually does
413 414 something (not a comment or docstring) for it to stop execution.
414 415
415 416 When the pdb debugger starts, you will see a (Pdb) prompt. You must
416 417 first enter 'c' (without quotes) to start execution up to the first
417 418 breakpoint.
418 419
419 420 Entering 'help' gives information about the use of the debugger. You
420 421 can easily see pdb's full documentation with "import pdb;pdb.help()"
421 422 at a prompt.
422 423
423 424 -p: run program under the control of the Python profiler module (which
424 425 prints a detailed report of execution times, function calls, etc).
425 426
426 427 You can pass other options after -p which affect the behavior of the
427 428 profiler itself. See the docs for %prun for details.
428 429
429 430 In this mode, the program's variables do NOT propagate back to the
430 431 IPython interactive namespace (because they remain in the namespace
431 432 where the profiler executes them).
432 433
433 434 Internally this triggers a call to %prun, see its documentation for
434 435 details on the options available specifically for profiling.
435 436
436 437 There is one special usage for which the text above doesn't apply:
437 438 if the filename ends with .ipy, the file is run as ipython script,
438 439 just as if the commands were written on IPython prompt.
439 440
440 441 -m: specify module name to load instead of script path. Similar to
441 442 the -m option for the python interpreter. Use this option last if you
442 443 want to combine with other %run options. Unlike the python interpreter
443 444 only source modules are allowed no .pyc or .pyo files.
444 445 For example::
445 446
446 447 %run -m example
447 448
448 449 will run the example module.
449 450
450 451 -G: disable shell-like glob expansion of arguments.
451 452
452 453 """
453 454
454 455 # get arguments and set sys.argv for program to be run.
455 456 opts, arg_lst = self.parse_options(parameter_s,
456 457 'nidtN:b:pD:l:rs:T:em:G',
457 458 mode='list', list_all=1)
458 459 if "m" in opts:
459 460 modulename = opts["m"][0]
460 461 modpath = find_mod(modulename)
461 462 if modpath is None:
462 463 warn('%r is not a valid modulename on sys.path'%modulename)
463 464 return
464 465 arg_lst = [modpath] + arg_lst
465 466 try:
466 467 filename = file_finder(arg_lst[0])
467 468 except IndexError:
468 469 warn('you must provide at least a filename.')
469 470 print '\n%run:\n', oinspect.getdoc(self.run)
470 471 return
471 472 except IOError as e:
472 473 try:
473 474 msg = str(e)
474 475 except UnicodeError:
475 476 msg = e.message
476 477 error(msg)
477 478 return
478 479
479 480 if filename.lower().endswith('.ipy'):
480 481 self.shell.safe_execfile_ipy(filename)
481 482 return
482 483
483 484 # Control the response to exit() calls made by the script being run
484 485 exit_ignore = 'e' in opts
485 486
486 487 # Make sure that the running script gets a proper sys.argv as if it
487 488 # were run from a system shell.
488 489 save_argv = sys.argv # save it for later restoring
489 490
490 491 if 'G' in opts:
491 492 args = arg_lst[1:]
492 493 else:
493 494 # tilde and glob expansion
494 495 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
495 496
496 497 sys.argv = [filename] + args # put in the proper filename
497 498 # protect sys.argv from potential unicode strings on Python 2:
498 499 if not py3compat.PY3:
499 500 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
500 501
501 502 if 'i' in opts:
502 503 # Run in user's interactive namespace
503 504 prog_ns = self.shell.user_ns
504 505 __name__save = self.shell.user_ns['__name__']
505 506 prog_ns['__name__'] = '__main__'
506 507 main_mod = self.shell.new_main_mod(prog_ns)
507 508 else:
508 509 # Run in a fresh, empty namespace
509 510 if 'n' in opts:
510 511 name = os.path.splitext(os.path.basename(filename))[0]
511 512 else:
512 513 name = '__main__'
513 514
514 515 main_mod = self.shell.new_main_mod()
515 516 prog_ns = main_mod.__dict__
516 517 prog_ns['__name__'] = name
517 518
518 519 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
519 520 # set the __file__ global in the script's namespace
520 521 prog_ns['__file__'] = filename
521 522
522 523 # pickle fix. See interactiveshell for an explanation. But we need to
523 524 # make sure that, if we overwrite __main__, we replace it at the end
524 525 main_mod_name = prog_ns['__name__']
525 526
526 527 if main_mod_name == '__main__':
527 528 restore_main = sys.modules['__main__']
528 529 else:
529 530 restore_main = False
530 531
531 532 # This needs to be undone at the end to prevent holding references to
532 533 # every single object ever created.
533 534 sys.modules[main_mod_name] = main_mod
534 535
535 536 try:
536 537 stats = None
537 538 with self.shell.readline_no_record:
538 539 if 'p' in opts:
539 540 stats = self.prun('', None, False, opts, arg_lst, prog_ns)
540 541 else:
541 542 if 'd' in opts:
542 543 deb = debugger.Pdb(self.shell.colors)
543 544 # reset Breakpoint state, which is moronically kept
544 545 # in a class
545 546 bdb.Breakpoint.next = 1
546 547 bdb.Breakpoint.bplist = {}
547 548 bdb.Breakpoint.bpbynumber = [None]
548 549 # Set an initial breakpoint to stop execution
549 550 maxtries = 10
550 551 bp = int(opts.get('b', [1])[0])
551 552 checkline = deb.checkline(filename, bp)
552 553 if not checkline:
553 554 for bp in range(bp + 1, bp + maxtries + 1):
554 555 if deb.checkline(filename, bp):
555 556 break
556 557 else:
557 558 msg = ("\nI failed to find a valid line to set "
558 559 "a breakpoint\n"
559 560 "after trying up to line: %s.\n"
560 561 "Please set a valid breakpoint manually "
561 562 "with the -b option." % bp)
562 563 error(msg)
563 564 return
564 565 # if we find a good linenumber, set the breakpoint
565 566 deb.do_break('%s:%s' % (filename, bp))
566 567
567 568 # Mimic Pdb._runscript(...)
568 569 deb._wait_for_mainpyfile = True
569 570 deb.mainpyfile = deb.canonic(filename)
570 571
571 572 # Start file run
572 573 print "NOTE: Enter 'c' at the",
573 574 print "%s prompt to start your script." % deb.prompt
574 575 ns = {'execfile': py3compat.execfile, 'prog_ns': prog_ns}
575 576 try:
576 577 #save filename so it can be used by methods on the deb object
577 578 deb._exec_filename = filename
578 579 deb.run('execfile("%s", prog_ns)' % filename, ns)
579 580
580 581 except:
581 582 etype, value, tb = sys.exc_info()
582 583 # Skip three frames in the traceback: the %run one,
583 584 # one inside bdb.py, and the command-line typed by the
584 585 # user (run by exec in pdb itself).
585 586 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
586 587 else:
587 588 if runner is None:
588 589 runner = self.default_runner
589 590 if runner is None:
590 591 runner = self.shell.safe_execfile
591 592 if 't' in opts:
592 593 # timed execution
593 594 try:
594 595 nruns = int(opts['N'][0])
595 596 if nruns < 1:
596 597 error('Number of runs must be >=1')
597 598 return
598 599 except (KeyError):
599 600 nruns = 1
600 601 twall0 = time.time()
601 602 if nruns == 1:
602 603 t0 = clock2()
603 604 runner(filename, prog_ns, prog_ns,
604 605 exit_ignore=exit_ignore)
605 606 t1 = clock2()
606 607 t_usr = t1[0] - t0[0]
607 608 t_sys = t1[1] - t0[1]
608 609 print "\nIPython CPU timings (estimated):"
609 610 print " User : %10.2f s." % t_usr
610 611 print " System : %10.2f s." % t_sys
611 612 else:
612 613 runs = range(nruns)
613 614 t0 = clock2()
614 615 for nr in runs:
615 616 runner(filename, prog_ns, prog_ns,
616 617 exit_ignore=exit_ignore)
617 618 t1 = clock2()
618 619 t_usr = t1[0] - t0[0]
619 620 t_sys = t1[1] - t0[1]
620 621 print "\nIPython CPU timings (estimated):"
621 622 print "Total runs performed:", nruns
622 623 print " Times : %10.2f %10.2f" % ('Total', 'Per run')
623 624 print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns)
624 625 print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns)
625 626 twall1 = time.time()
626 627 print "Wall time: %10.2f s." % (twall1 - twall0)
627 628
628 629 else:
629 630 # regular execution
630 631 runner(filename, prog_ns, prog_ns, exit_ignore=exit_ignore)
631 632
632 633 if 'i' in opts:
633 634 self.shell.user_ns['__name__'] = __name__save
634 635 else:
635 636 # The shell MUST hold a reference to prog_ns so after %run
636 637 # exits, the python deletion mechanism doesn't zero it out
637 638 # (leaving dangling references).
638 639 self.shell.cache_main_mod(prog_ns, filename)
639 640 # update IPython interactive namespace
640 641
641 642 # Some forms of read errors on the file may mean the
642 643 # __name__ key was never set; using pop we don't have to
643 644 # worry about a possible KeyError.
644 645 prog_ns.pop('__name__', None)
645 646
646 647 self.shell.user_ns.update(prog_ns)
647 648 finally:
648 649 # It's a bit of a mystery why, but __builtins__ can change from
649 650 # being a module to becoming a dict missing some key data after
650 651 # %run. As best I can see, this is NOT something IPython is doing
651 652 # at all, and similar problems have been reported before:
652 653 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
653 654 # Since this seems to be done by the interpreter itself, the best
654 655 # we can do is to at least restore __builtins__ for the user on
655 656 # exit.
656 657 self.shell.user_ns['__builtins__'] = builtin_mod
657 658
658 659 # Ensure key global structures are restored
659 660 sys.argv = save_argv
660 661 if restore_main:
661 662 sys.modules['__main__'] = restore_main
662 663 else:
663 664 # Remove from sys.modules the reference to main_mod we'd
664 665 # added. Otherwise it will trap references to objects
665 666 # contained therein.
666 667 del sys.modules[main_mod_name]
667 668
668 669 return stats
669 670
670 671 @skip_doctest
671 672 @line_cell_magic
672 673 def timeit(self, line='', cell=None):
673 674 """Time execution of a Python statement or expression
674 675
675 676 Usage, in line mode:
676 677 %timeit [-n<N> -r<R> [-t|-c]] statement
677 678 or in cell mode:
678 679 %%timeit [-n<N> -r<R> [-t|-c]] setup_code
679 680 code
680 681 code...
681 682
682 683 Time execution of a Python statement or expression using the timeit
683 684 module. This function can be used both as a line and cell magic:
684 685
685 686 - In line mode you can time a single-line statement (though multiple
686 687 ones can be chained with using semicolons).
687 688
688 689 - In cell mode, the statement in the first line is used as setup code
689 690 (executed but not timed) and the body of the cell is timed. The cell
690 691 body has access to any variables created in the setup code.
691 692
692 693 Options:
693 694 -n<N>: execute the given statement <N> times in a loop. If this value
694 695 is not given, a fitting value is chosen.
695 696
696 697 -r<R>: repeat the loop iteration <R> times and take the best result.
697 698 Default: 3
698 699
699 700 -t: use time.time to measure the time, which is the default on Unix.
700 701 This function measures wall time.
701 702
702 703 -c: use time.clock to measure the time, which is the default on
703 704 Windows and measures wall time. On Unix, resource.getrusage is used
704 705 instead and returns the CPU user time.
705 706
706 707 -p<P>: use a precision of <P> digits to display the timing result.
707 708 Default: 3
708 709
709 710
710 711 Examples
711 712 --------
712 713 ::
713 714
714 715 In [1]: %timeit pass
715 716 10000000 loops, best of 3: 53.3 ns per loop
716 717
717 718 In [2]: u = None
718 719
719 720 In [3]: %timeit u is None
720 721 10000000 loops, best of 3: 184 ns per loop
721 722
722 723 In [4]: %timeit -r 4 u == None
723 724 1000000 loops, best of 4: 242 ns per loop
724 725
725 726 In [5]: import time
726 727
727 728 In [6]: %timeit -n1 time.sleep(2)
728 729 1 loops, best of 3: 2 s per loop
729 730
730 731
731 732 The times reported by %timeit will be slightly higher than those
732 733 reported by the timeit.py script when variables are accessed. This is
733 734 due to the fact that %timeit executes the statement in the namespace
734 735 of the shell, compared with timeit.py, which uses a single setup
735 736 statement to import function or create variables. Generally, the bias
736 737 does not matter as long as results from timeit.py are not mixed with
737 738 those from %timeit."""
738 739
739 740 import timeit
740 741 import math
741 742
742 743 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
743 744 # certain terminals. Until we figure out a robust way of
744 745 # auto-detecting if the terminal can deal with it, use plain 'us' for
745 746 # microseconds. I am really NOT happy about disabling the proper
746 747 # 'micro' prefix, but crashing is worse... If anyone knows what the
747 748 # right solution for this is, I'm all ears...
748 749 #
749 750 # Note: using
750 751 #
751 752 # s = u'\xb5'
752 753 # s.encode(sys.getdefaultencoding())
753 754 #
754 755 # is not sufficient, as I've seen terminals where that fails but
755 756 # print s
756 757 #
757 758 # succeeds
758 759 #
759 760 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
760 761
761 762 #units = [u"s", u"ms",u'\xb5',"ns"]
762 763 units = [u"s", u"ms",u'us',"ns"]
763 764
764 765 scaling = [1, 1e3, 1e6, 1e9]
765 766
766 767 opts, stmt = self.parse_options(line,'n:r:tcp:',
767 768 posix=False, strict=False)
768 769 if stmt == "" and cell is None:
769 770 return
770 771 timefunc = timeit.default_timer
771 772 number = int(getattr(opts, "n", 0))
772 773 repeat = int(getattr(opts, "r", timeit.default_repeat))
773 774 precision = int(getattr(opts, "p", 3))
774 775 if hasattr(opts, "t"):
775 776 timefunc = time.time
776 777 if hasattr(opts, "c"):
777 778 timefunc = clock
778 779
779 780 timer = timeit.Timer(timer=timefunc)
780 781 # this code has tight coupling to the inner workings of timeit.Timer,
781 782 # but is there a better way to achieve that the code stmt has access
782 783 # to the shell namespace?
783 784 transform = self.shell.input_splitter.transform_cell
785
784 786 if cell is None:
785 787 # called as line magic
786 setup = 'pass'
787 stmt = timeit.reindent(transform(stmt), 8)
788 else:
789 setup = timeit.reindent(transform(stmt), 4)
790 stmt = timeit.reindent(transform(cell), 8)
791
792 # From Python 3.3, this template uses new-style string formatting.
793 if sys.version_info >= (3, 3):
794 src = timeit.template.format(stmt=stmt, setup=setup)
788 ast_setup = ast.parse("pass")
789 ast_stmt = ast.parse(transform(stmt))
795 790 else:
796 src = timeit.template % dict(stmt=stmt, setup=setup)
791 ast_setup = ast.parse(transform(stmt))
792 ast_stmt = ast.parse(transform(cell))
793
794 ast_setup = self.shell.transform_ast(ast_setup)
795 ast_stmt = self.shell.transform_ast(ast_stmt)
796
797 # This codestring is taken from timeit.template - we fill it in as an
798 # AST, so that we can apply our AST transformations to the user code
799 # without affecting the timing code.
800 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
801 ' setup\n'
802 ' _t0 = _timer()\n'
803 ' for _i in _it:\n'
804 ' stmt\n'
805 ' _t1 = _timer()\n'
806 ' return _t1 - _t0\n')
807
808 class TimeitTemplateFiller(ast.NodeTransformer):
809 "This is quite tightly tied to the template definition above."
810 def visit_FunctionDef(self, node):
811 "Fill in the setup statement"
812 self.generic_visit(node)
813 if node.name == "inner":
814 node.body[:1] = ast_setup.body
815
816 return node
817
818 def visit_For(self, node):
819 "Fill in the statement to be timed"
820 if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
821 node.body = ast_stmt.body
822 return node
823
824 timeit_ast = TimeitTemplateFiller().visit(timeit_ast_template)
825 timeit_ast = ast.fix_missing_locations(timeit_ast)
797 826
798 827 # Track compilation time so it can be reported if too long
799 828 # Minimum time above which compilation time will be reported
800 829 tc_min = 0.1
801 830
802 831 t0 = clock()
803 code = compile(src, "<magic-timeit>", "exec")
832 code = compile(timeit_ast, "<magic-timeit>", "exec")
804 833 tc = clock()-t0
805 834
806 835 ns = {}
807 836 exec code in self.shell.user_ns, ns
808 837 timer.inner = ns["inner"]
809 838
810 839 if number == 0:
811 840 # determine number so that 0.2 <= total time < 2.0
812 841 number = 1
813 842 for i in range(1, 10):
814 843 if timer.timeit(number) >= 0.2:
815 844 break
816 845 number *= 10
817 846
818 847 best = min(timer.repeat(repeat, number)) / number
819 848
820 849 if best > 0.0 and best < 1000.0:
821 850 order = min(-int(math.floor(math.log10(best)) // 3), 3)
822 851 elif best >= 1000.0:
823 852 order = 0
824 853 else:
825 854 order = 3
826 855 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
827 856 precision,
828 857 best * scaling[order],
829 858 units[order])
830 859 if tc > tc_min:
831 860 print "Compiler time: %.2f s" % tc
832 861
833 862 @skip_doctest
834 863 @needs_local_scope
835 864 @line_magic
836 865 def time(self,parameter_s, local_ns=None):
837 866 """Time execution of a Python statement or expression.
838 867
839 868 The CPU and wall clock times are printed, and the value of the
840 869 expression (if any) is returned. Note that under Win32, system time
841 870 is always reported as 0, since it can not be measured.
842 871
843 872 This function provides very basic timing functionality. In Python
844 873 2.3, the timeit module offers more control and sophistication, so this
845 874 could be rewritten to use it (patches welcome).
846 875
847 876 Examples
848 877 --------
849 878 ::
850 879
851 880 In [1]: time 2**128
852 881 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
853 882 Wall time: 0.00
854 883 Out[1]: 340282366920938463463374607431768211456L
855 884
856 885 In [2]: n = 1000000
857 886
858 887 In [3]: time sum(range(n))
859 888 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
860 889 Wall time: 1.37
861 890 Out[3]: 499999500000L
862 891
863 892 In [4]: time print 'hello world'
864 893 hello world
865 894 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
866 895 Wall time: 0.00
867 896
868 897 Note that the time needed by Python to compile the given expression
869 898 will be reported if it is more than 0.1s. In this example, the
870 899 actual exponentiation is done by Python at compilation time, so while
871 900 the expression can take a noticeable amount of time to compute, that
872 901 time is purely due to the compilation:
873 902
874 903 In [5]: time 3**9999;
875 904 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
876 905 Wall time: 0.00 s
877 906
878 907 In [6]: time 3**999999;
879 908 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
880 909 Wall time: 0.00 s
881 910 Compiler : 0.78 s
882 911 """
883 912
884 913 # fail immediately if the given expression can't be compiled
885 914
886 915 expr = self.shell.prefilter(parameter_s,False)
916
917 # Minimum time above which parse time will be reported
918 tp_min = 0.1
919
920 t0 = clock()
921 expr_ast = ast.parse(expr)
922 tp = clock()-t0
923
924 # Apply AST transformations
925 expr_ast = self.shell.transform_ast(expr_ast)
887 926
888 927 # Minimum time above which compilation time will be reported
889 928 tc_min = 0.1
890 929
891 try:
930 if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
892 931 mode = 'eval'
893 t0 = clock()
894 code = compile(expr,'<timed eval>',mode)
895 tc = clock()-t0
896 except SyntaxError:
932 source = '<timed eval>'
933 expr_ast = ast.Expression(expr_ast.body[0].value)
934 else:
897 935 mode = 'exec'
898 t0 = clock()
899 code = compile(expr,'<timed exec>',mode)
900 tc = clock()-t0
936 source = '<timed exec>'
937 t0 = clock()
938 code = compile(expr_ast, source, mode)
939 tc = clock()-t0
940
901 941 # skew measurement as little as possible
902 942 glob = self.shell.user_ns
903 943 wtime = time.time
904 944 # time execution
905 945 wall_st = wtime()
906 946 if mode=='eval':
907 947 st = clock2()
908 948 out = eval(code, glob, local_ns)
909 949 end = clock2()
910 950 else:
911 951 st = clock2()
912 952 exec code in glob, local_ns
913 953 end = clock2()
914 954 out = None
915 955 wall_end = wtime()
916 956 # Compute actual times and report
917 957 wall_time = wall_end-wall_st
918 958 cpu_user = end[0]-st[0]
919 959 cpu_sys = end[1]-st[1]
920 960 cpu_tot = cpu_user+cpu_sys
921 961 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
922 962 (cpu_user,cpu_sys,cpu_tot)
923 963 print "Wall time: %.2f s" % wall_time
924 964 if tc > tc_min:
925 965 print "Compiler : %.2f s" % tc
966 if tp > tp_min:
967 print "Parser : %.2f s" % tp
926 968 return out
927 969
928 970 @skip_doctest
929 971 @line_magic
930 972 def macro(self, parameter_s=''):
931 973 """Define a macro for future re-execution. It accepts ranges of history,
932 974 filenames or string objects.
933 975
934 976 Usage:\\
935 977 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
936 978
937 979 Options:
938 980
939 981 -r: use 'raw' input. By default, the 'processed' history is used,
940 982 so that magics are loaded in their transformed version to valid
941 983 Python. If this option is given, the raw input as typed as the
942 984 command line is used instead.
943 985
944 986 This will define a global variable called `name` which is a string
945 987 made of joining the slices and lines you specify (n1,n2,... numbers
946 988 above) from your input history into a single string. This variable
947 989 acts like an automatic function which re-executes those lines as if
948 990 you had typed them. You just type 'name' at the prompt and the code
949 991 executes.
950 992
951 993 The syntax for indicating input ranges is described in %history.
952 994
953 995 Note: as a 'hidden' feature, you can also use traditional python slice
954 996 notation, where N:M means numbers N through M-1.
955 997
956 998 For example, if your history contains (%hist prints it)::
957 999
958 1000 44: x=1
959 1001 45: y=3
960 1002 46: z=x+y
961 1003 47: print x
962 1004 48: a=5
963 1005 49: print 'x',x,'y',y
964 1006
965 1007 you can create a macro with lines 44 through 47 (included) and line 49
966 1008 called my_macro with::
967 1009
968 1010 In [55]: %macro my_macro 44-47 49
969 1011
970 1012 Now, typing `my_macro` (without quotes) will re-execute all this code
971 1013 in one pass.
972 1014
973 1015 You don't need to give the line-numbers in order, and any given line
974 1016 number can appear multiple times. You can assemble macros with any
975 1017 lines from your input history in any order.
976 1018
977 1019 The macro is a simple object which holds its value in an attribute,
978 1020 but IPython's display system checks for macros and executes them as
979 1021 code instead of printing them when you type their name.
980 1022
981 1023 You can view a macro's contents by explicitly printing it with::
982 1024
983 1025 print macro_name
984 1026
985 1027 """
986 1028 opts,args = self.parse_options(parameter_s,'r',mode='list')
987 1029 if not args: # List existing macros
988 1030 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
989 1031 isinstance(v, Macro))
990 1032 if len(args) == 1:
991 1033 raise UsageError(
992 1034 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
993 1035 name, codefrom = args[0], " ".join(args[1:])
994 1036
995 1037 #print 'rng',ranges # dbg
996 1038 try:
997 1039 lines = self.shell.find_user_code(codefrom, 'r' in opts)
998 1040 except (ValueError, TypeError) as e:
999 1041 print e.args[0]
1000 1042 return
1001 1043 macro = Macro(lines)
1002 1044 self.shell.define_macro(name, macro)
1003 1045 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1004 1046 print '=== Macro contents: ==='
1005 1047 print macro,
1006 1048
1007 1049 @magic_arguments.magic_arguments()
1008 1050 @magic_arguments.argument('output', type=str, default='', nargs='?',
1009 1051 help="""The name of the variable in which to store output.
1010 1052 This is a utils.io.CapturedIO object with stdout/err attributes
1011 1053 for the text of the captured output.
1012 1054
1013 1055 CapturedOutput also has a show() method for displaying the output,
1014 1056 and __call__ as well, so you can use that to quickly display the
1015 1057 output.
1016 1058
1017 1059 If unspecified, captured output is discarded.
1018 1060 """
1019 1061 )
1020 1062 @magic_arguments.argument('--no-stderr', action="store_true",
1021 1063 help="""Don't capture stderr."""
1022 1064 )
1023 1065 @magic_arguments.argument('--no-stdout', action="store_true",
1024 1066 help="""Don't capture stdout."""
1025 1067 )
1026 1068 @cell_magic
1027 1069 def capture(self, line, cell):
1028 1070 """run the cell, capturing stdout/err"""
1029 1071 args = magic_arguments.parse_argstring(self.capture, line)
1030 1072 out = not args.no_stdout
1031 1073 err = not args.no_stderr
1032 1074 with capture_output(out, err) as io:
1033 1075 self.shell.run_cell(cell)
1034 1076 if args.output:
1035 1077 self.shell.user_ns[args.output] = io
@@ -1,432 +1,559 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Tests for the key interactiveshell module.
3 3
4 4 Historically the main classes in interactiveshell have been under-tested. This
5 5 module should grow as many single-method tests as possible to trap many of the
6 6 recurring bugs we seem to encounter with high-level interaction.
7 7
8 8 Authors
9 9 -------
10 10 * Fernando Perez
11 11 """
12 12 #-----------------------------------------------------------------------------
13 13 # Copyright (C) 2011 The IPython Development Team
14 14 #
15 15 # Distributed under the terms of the BSD License. The full license is in
16 16 # the file COPYING, distributed as part of this software.
17 17 #-----------------------------------------------------------------------------
18 18
19 19 #-----------------------------------------------------------------------------
20 20 # Imports
21 21 #-----------------------------------------------------------------------------
22 22 # stdlib
23 import ast
23 24 import os
24 25 import shutil
25 26 import sys
26 27 import tempfile
27 28 import unittest
28 29 from os.path import join
29 30 from StringIO import StringIO
30 31
31 32 # third-party
32 33 import nose.tools as nt
33 34
34 35 # Our own
35 36 from IPython.testing.decorators import skipif
36 37 from IPython.testing import tools as tt
37 38 from IPython.utils import io
38 39
39 40 #-----------------------------------------------------------------------------
40 41 # Globals
41 42 #-----------------------------------------------------------------------------
42 43 # This is used by every single test, no point repeating it ad nauseam
43 44 ip = get_ipython()
44 45
45 46 #-----------------------------------------------------------------------------
46 47 # Tests
47 48 #-----------------------------------------------------------------------------
48 49
49 50 class InteractiveShellTestCase(unittest.TestCase):
50 51 def test_naked_string_cells(self):
51 52 """Test that cells with only naked strings are fully executed"""
52 53 # First, single-line inputs
53 54 ip.run_cell('"a"\n')
54 55 self.assertEqual(ip.user_ns['_'], 'a')
55 56 # And also multi-line cells
56 57 ip.run_cell('"""a\nb"""\n')
57 58 self.assertEqual(ip.user_ns['_'], 'a\nb')
58 59
59 60 def test_run_empty_cell(self):
60 61 """Just make sure we don't get a horrible error with a blank
61 62 cell of input. Yes, I did overlook that."""
62 63 old_xc = ip.execution_count
63 64 ip.run_cell('')
64 65 self.assertEqual(ip.execution_count, old_xc)
65 66
66 67 def test_run_cell_multiline(self):
67 68 """Multi-block, multi-line cells must execute correctly.
68 69 """
69 70 src = '\n'.join(["x=1",
70 71 "y=2",
71 72 "if 1:",
72 73 " x += 1",
73 74 " y += 1",])
74 75 ip.run_cell(src)
75 76 self.assertEqual(ip.user_ns['x'], 2)
76 77 self.assertEqual(ip.user_ns['y'], 3)
77 78
78 79 def test_multiline_string_cells(self):
79 80 "Code sprinkled with multiline strings should execute (GH-306)"
80 81 ip.run_cell('tmp=0')
81 82 self.assertEqual(ip.user_ns['tmp'], 0)
82 83 ip.run_cell('tmp=1;"""a\nb"""\n')
83 84 self.assertEqual(ip.user_ns['tmp'], 1)
84 85
85 86 def test_dont_cache_with_semicolon(self):
86 87 "Ending a line with semicolon should not cache the returned object (GH-307)"
87 88 oldlen = len(ip.user_ns['Out'])
88 89 a = ip.run_cell('1;', store_history=True)
89 90 newlen = len(ip.user_ns['Out'])
90 91 self.assertEqual(oldlen, newlen)
91 92 #also test the default caching behavior
92 93 ip.run_cell('1', store_history=True)
93 94 newlen = len(ip.user_ns['Out'])
94 95 self.assertEqual(oldlen+1, newlen)
95 96
96 97 def test_In_variable(self):
97 98 "Verify that In variable grows with user input (GH-284)"
98 99 oldlen = len(ip.user_ns['In'])
99 100 ip.run_cell('1;', store_history=True)
100 101 newlen = len(ip.user_ns['In'])
101 102 self.assertEqual(oldlen+1, newlen)
102 103 self.assertEqual(ip.user_ns['In'][-1],'1;')
103 104
104 105 def test_magic_names_in_string(self):
105 106 ip.run_cell('a = """\n%exit\n"""')
106 107 self.assertEqual(ip.user_ns['a'], '\n%exit\n')
107 108
108 109 def test_alias_crash(self):
109 110 """Errors in prefilter can't crash IPython"""
110 111 ip.run_cell('%alias parts echo first %s second %s')
111 112 # capture stderr:
112 113 save_err = io.stderr
113 114 io.stderr = StringIO()
114 115 ip.run_cell('parts 1')
115 116 err = io.stderr.getvalue()
116 117 io.stderr = save_err
117 118 self.assertEqual(err.split(':')[0], 'ERROR')
118 119
119 120 def test_trailing_newline(self):
120 121 """test that running !(command) does not raise a SyntaxError"""
121 122 ip.run_cell('!(true)\n', False)
122 123 ip.run_cell('!(true)\n\n\n', False)
123 124
124 125 def test_gh_597(self):
125 126 """Pretty-printing lists of objects with non-ascii reprs may cause
126 127 problems."""
127 128 class Spam(object):
128 129 def __repr__(self):
129 130 return "\xe9"*50
130 131 import IPython.core.formatters
131 132 f = IPython.core.formatters.PlainTextFormatter()
132 133 f([Spam(),Spam()])
133 134
134 135
135 136 def test_future_flags(self):
136 137 """Check that future flags are used for parsing code (gh-777)"""
137 138 ip.run_cell('from __future__ import print_function')
138 139 try:
139 140 ip.run_cell('prfunc_return_val = print(1,2, sep=" ")')
140 141 assert 'prfunc_return_val' in ip.user_ns
141 142 finally:
142 143 # Reset compiler flags so we don't mess up other tests.
143 144 ip.compile.reset_compiler_flags()
144 145
145 146 def test_future_unicode(self):
146 147 """Check that unicode_literals is imported from __future__ (gh #786)"""
147 148 try:
148 149 ip.run_cell(u'byte_str = "a"')
149 150 assert isinstance(ip.user_ns['byte_str'], str) # string literals are byte strings by default
150 151 ip.run_cell('from __future__ import unicode_literals')
151 152 ip.run_cell(u'unicode_str = "a"')
152 153 assert isinstance(ip.user_ns['unicode_str'], unicode) # strings literals are now unicode
153 154 finally:
154 155 # Reset compiler flags so we don't mess up other tests.
155 156 ip.compile.reset_compiler_flags()
156 157
157 158 def test_can_pickle(self):
158 159 "Can we pickle objects defined interactively (GH-29)"
159 160 ip = get_ipython()
160 161 ip.reset()
161 162 ip.run_cell(("class Mylist(list):\n"
162 163 " def __init__(self,x=[]):\n"
163 164 " list.__init__(self,x)"))
164 165 ip.run_cell("w=Mylist([1,2,3])")
165 166
166 167 from cPickle import dumps
167 168
168 169 # We need to swap in our main module - this is only necessary
169 170 # inside the test framework, because IPython puts the interactive module
170 171 # in place (but the test framework undoes this).
171 172 _main = sys.modules['__main__']
172 173 sys.modules['__main__'] = ip.user_module
173 174 try:
174 175 res = dumps(ip.user_ns["w"])
175 176 finally:
176 177 sys.modules['__main__'] = _main
177 178 self.assertTrue(isinstance(res, bytes))
178 179
179 180 def test_global_ns(self):
180 181 "Code in functions must be able to access variables outside them."
181 182 ip = get_ipython()
182 183 ip.run_cell("a = 10")
183 184 ip.run_cell(("def f(x):\n"
184 185 " return x + a"))
185 186 ip.run_cell("b = f(12)")
186 187 self.assertEqual(ip.user_ns["b"], 22)
187 188
188 189 def test_bad_custom_tb(self):
189 190 """Check that InteractiveShell is protected from bad custom exception handlers"""
190 191 from IPython.utils import io
191 192 save_stderr = io.stderr
192 193 try:
193 194 # capture stderr
194 195 io.stderr = StringIO()
195 196 ip.set_custom_exc((IOError,), lambda etype,value,tb: 1/0)
196 197 self.assertEqual(ip.custom_exceptions, (IOError,))
197 198 ip.run_cell(u'raise IOError("foo")')
198 199 self.assertEqual(ip.custom_exceptions, ())
199 200 self.assertTrue("Custom TB Handler failed" in io.stderr.getvalue())
200 201 finally:
201 202 io.stderr = save_stderr
202 203
203 204 def test_bad_custom_tb_return(self):
204 205 """Check that InteractiveShell is protected from bad return types in custom exception handlers"""
205 206 from IPython.utils import io
206 207 save_stderr = io.stderr
207 208 try:
208 209 # capture stderr
209 210 io.stderr = StringIO()
210 211 ip.set_custom_exc((NameError,),lambda etype,value,tb, tb_offset=None: 1)
211 212 self.assertEqual(ip.custom_exceptions, (NameError,))
212 213 ip.run_cell(u'a=abracadabra')
213 214 self.assertEqual(ip.custom_exceptions, ())
214 215 self.assertTrue("Custom TB Handler failed" in io.stderr.getvalue())
215 216 finally:
216 217 io.stderr = save_stderr
217 218
218 219 def test_drop_by_id(self):
219 220 myvars = {"a":object(), "b":object(), "c": object()}
220 221 ip.push(myvars, interactive=False)
221 222 for name in myvars:
222 223 assert name in ip.user_ns, name
223 224 assert name in ip.user_ns_hidden, name
224 225 ip.user_ns['b'] = 12
225 226 ip.drop_by_id(myvars)
226 227 for name in ["a", "c"]:
227 228 assert name not in ip.user_ns, name
228 229 assert name not in ip.user_ns_hidden, name
229 230 assert ip.user_ns['b'] == 12
230 231 ip.reset()
231 232
232 233 def test_var_expand(self):
233 234 ip.user_ns['f'] = u'Ca\xf1o'
234 235 self.assertEqual(ip.var_expand(u'echo $f'), u'echo Ca\xf1o')
235 236 self.assertEqual(ip.var_expand(u'echo {f}'), u'echo Ca\xf1o')
236 237 self.assertEqual(ip.var_expand(u'echo {f[:-1]}'), u'echo Ca\xf1')
237 238 self.assertEqual(ip.var_expand(u'echo {1*2}'), u'echo 2')
238 239
239 240 ip.user_ns['f'] = b'Ca\xc3\xb1o'
240 241 # This should not raise any exception:
241 242 ip.var_expand(u'echo $f')
242 243
243 244 def test_var_expand_local(self):
244 245 """Test local variable expansion in !system and %magic calls"""
245 246 # !system
246 247 ip.run_cell('def test():\n'
247 248 ' lvar = "ttt"\n'
248 249 ' ret = !echo {lvar}\n'
249 250 ' return ret[0]\n')
250 251 res = ip.user_ns['test']()
251 252 nt.assert_in('ttt', res)
252 253
253 254 # %magic
254 255 ip.run_cell('def makemacro():\n'
255 256 ' macroname = "macro_var_expand_locals"\n'
256 257 ' %macro {macroname} codestr\n')
257 258 ip.user_ns['codestr'] = "str(12)"
258 259 ip.run_cell('makemacro()')
259 260 nt.assert_in('macro_var_expand_locals', ip.user_ns)
260 261
261 262 def test_var_expand_self(self):
262 263 """Test variable expansion with the name 'self', which was failing.
263 264
264 265 See https://github.com/ipython/ipython/issues/1878#issuecomment-7698218
265 266 """
266 267 ip.run_cell('class cTest:\n'
267 268 ' classvar="see me"\n'
268 269 ' def test(self):\n'
269 270 ' res = !echo Variable: {self.classvar}\n'
270 271 ' return res[0]\n')
271 272 nt.assert_in('see me', ip.user_ns['cTest']().test())
272 273
273 274 def test_bad_var_expand(self):
274 275 """var_expand on invalid formats shouldn't raise"""
275 276 # SyntaxError
276 277 self.assertEqual(ip.var_expand(u"{'a':5}"), u"{'a':5}")
277 278 # NameError
278 279 self.assertEqual(ip.var_expand(u"{asdf}"), u"{asdf}")
279 280 # ZeroDivisionError
280 281 self.assertEqual(ip.var_expand(u"{1/0}"), u"{1/0}")
281 282
282 283 def test_silent_nopostexec(self):
283 284 """run_cell(silent=True) doesn't invoke post-exec funcs"""
284 285 d = dict(called=False)
285 286 def set_called():
286 287 d['called'] = True
287 288
288 289 ip.register_post_execute(set_called)
289 290 ip.run_cell("1", silent=True)
290 291 self.assertFalse(d['called'])
291 292 # double-check that non-silent exec did what we expected
292 293 # silent to avoid
293 294 ip.run_cell("1")
294 295 self.assertTrue(d['called'])
295 296 # remove post-exec
296 297 ip._post_execute.pop(set_called)
297 298
298 299 def test_silent_noadvance(self):
299 300 """run_cell(silent=True) doesn't advance execution_count"""
300 301 ec = ip.execution_count
301 302 # silent should force store_history=False
302 303 ip.run_cell("1", store_history=True, silent=True)
303 304
304 305 self.assertEqual(ec, ip.execution_count)
305 306 # double-check that non-silent exec did what we expected
306 307 # silent to avoid
307 308 ip.run_cell("1", store_history=True)
308 309 self.assertEqual(ec+1, ip.execution_count)
309 310
310 311 def test_silent_nodisplayhook(self):
311 312 """run_cell(silent=True) doesn't trigger displayhook"""
312 313 d = dict(called=False)
313 314
314 315 trap = ip.display_trap
315 316 save_hook = trap.hook
316 317
317 318 def failing_hook(*args, **kwargs):
318 319 d['called'] = True
319 320
320 321 try:
321 322 trap.hook = failing_hook
322 323 ip.run_cell("1", silent=True)
323 324 self.assertFalse(d['called'])
324 325 # double-check that non-silent exec did what we expected
325 326 # silent to avoid
326 327 ip.run_cell("1")
327 328 self.assertTrue(d['called'])
328 329 finally:
329 330 trap.hook = save_hook
330 331
331 332 @skipif(sys.version_info[0] >= 3, "softspace removed in py3")
332 333 def test_print_softspace(self):
333 334 """Verify that softspace is handled correctly when executing multiple
334 335 statements.
335 336
336 337 In [1]: print 1; print 2
337 338 1
338 339 2
339 340
340 341 In [2]: print 1,; print 2
341 342 1 2
342 343 """
343 344
344 345 def test_ofind_line_magic(self):
345 346 from IPython.core.magic import register_line_magic
346 347
347 348 @register_line_magic
348 349 def lmagic(line):
349 350 "A line magic"
350 351
351 352 # Get info on line magic
352 353 lfind = ip._ofind('lmagic')
353 354 info = dict(found=True, isalias=False, ismagic=True,
354 355 namespace = 'IPython internal', obj= lmagic.__wrapped__,
355 356 parent = None)
356 357 nt.assert_equal(lfind, info)
357 358
358 359 def test_ofind_cell_magic(self):
359 360 from IPython.core.magic import register_cell_magic
360 361
361 362 @register_cell_magic
362 363 def cmagic(line, cell):
363 364 "A cell magic"
364 365
365 366 # Get info on cell magic
366 367 find = ip._ofind('cmagic')
367 368 info = dict(found=True, isalias=False, ismagic=True,
368 369 namespace = 'IPython internal', obj= cmagic.__wrapped__,
369 370 parent = None)
370 371 nt.assert_equal(find, info)
371 372
372 373 def test_custom_exception(self):
373 374 called = []
374 375 def my_handler(shell, etype, value, tb, tb_offset=None):
375 376 called.append(etype)
376 377 shell.showtraceback((etype, value, tb), tb_offset=tb_offset)
377 378
378 379 ip.set_custom_exc((ValueError,), my_handler)
379 380 try:
380 381 ip.run_cell("raise ValueError('test')")
381 382 # Check that this was called, and only once.
382 383 self.assertEqual(called, [ValueError])
383 384 finally:
384 385 # Reset the custom exception hook
385 386 ip.set_custom_exc((), None)
386 387
387 388
388 389 class TestSafeExecfileNonAsciiPath(unittest.TestCase):
389 390
390 391 def setUp(self):
391 392 self.BASETESTDIR = tempfile.mkdtemp()
392 393 self.TESTDIR = join(self.BASETESTDIR, u"Γ₯Àâ")
393 394 os.mkdir(self.TESTDIR)
394 395 with open(join(self.TESTDIR, u"Γ₯Àâtestscript.py"), "w") as sfile:
395 396 sfile.write("pass\n")
396 397 self.oldpath = os.getcwdu()
397 398 os.chdir(self.TESTDIR)
398 399 self.fname = u"Γ₯Àâtestscript.py"
399 400
400 401 def tearDown(self):
401 402 os.chdir(self.oldpath)
402 403 shutil.rmtree(self.BASETESTDIR)
403 404
404 405 def test_1(self):
405 406 """Test safe_execfile with non-ascii path
406 407 """
407 408 ip.safe_execfile(self.fname, {}, raise_exceptions=True)
408 409
409 410
410 411 class TestSystemRaw(unittest.TestCase):
411 412 def test_1(self):
412 413 """Test system_raw with non-ascii cmd
413 414 """
414 415 cmd = ur'''python -c "'Γ₯Àâ'" '''
415 416 ip.system_raw(cmd)
416 417
417 418 class TestModules(unittest.TestCase, tt.TempFileMixin):
418 419 def test_extraneous_loads(self):
419 420 """Test we're not loading modules on startup that we shouldn't.
420 421 """
421 422 self.mktmp("import sys\n"
422 423 "print('numpy' in sys.modules)\n"
423 424 "print('IPython.parallel' in sys.modules)\n"
424 425 "print('IPython.zmq' in sys.modules)\n"
425 426 )
426 427 out = "False\nFalse\nFalse\n"
427 428 tt.ipexec_validate(self.fname, out)
428 429
430 class Negator(ast.NodeTransformer):
431 """Negates all number literals in an AST."""
432 def visit_Num(self, node):
433 node.n = -node.n
434 return node
435
436 class TestAstTransform(unittest.TestCase):
437 def setUp(self):
438 self.negator = Negator()
439 ip.ast_transformers.append(self.negator)
440
441 def tearDown(self):
442 ip.ast_transformers.remove(self.negator)
443
444 def test_run_cell(self):
445 with tt.AssertPrints('-34'):
446 ip.run_cell('print (12 + 22)')
447
448 # A named reference to a number shouldn't be transformed.
449 ip.user_ns['n'] = 55
450 with tt.AssertNotPrints('-55'):
451 ip.run_cell('print (n)')
452
453 def test_timeit(self):
454 called = set()
455 def f(x):
456 called.add(x)
457 ip.push({'f':f})
458
459 with tt.AssertPrints("best of "):
460 ip.run_line_magic("timeit", "-n1 f(1)")
461 self.assertEqual(called, set([-1]))
462 called.clear()
463
464 with tt.AssertPrints("best of "):
465 ip.run_cell_magic("timeit", "-n1 f(2)", "f(3)")
466 self.assertEqual(called, set([-2, -3]))
467
468 def test_time(self):
469 called = []
470 def f(x):
471 called.append(x)
472 ip.push({'f':f})
473
474 # Test with an expression
475 with tt.AssertPrints("CPU times"):
476 ip.run_line_magic("time", "f(5+9)")
477 self.assertEqual(called, [-14])
478 called[:] = []
479
480 # Test with a statement (different code path)
481 with tt.AssertPrints("CPU times"):
482 ip.run_line_magic("time", "a = f(-3 + -2)")
483 self.assertEqual(called, [5])
484
485 def test_macro(self):
486 ip.push({'a':10})
487 # The AST transformation makes this do a+=-1
488 ip.define_macro("amacro", "a+=1\nprint(a)")
489
490 with tt.AssertPrints("9"):
491 ip.run_cell("amacro")
492 with tt.AssertPrints("8"):
493 ip.run_cell("amacro")
494
495 class IntegerWrapper(ast.NodeTransformer):
496 """Wraps all integers in a call to Integer()"""
497 def visit_Num(self, node):
498 if isinstance(node.n, int):
499 return ast.Call(func=ast.Name(id='Integer', ctx=ast.Load()),
500 args=[node], keywords=[])
501 return node
502
503 class TestAstTransform2(unittest.TestCase):
504 def setUp(self):
505 self.intwrapper = IntegerWrapper()
506 ip.ast_transformers.append(self.intwrapper)
507
508 self.calls = []
509 def Integer(*args):
510 self.calls.append(args)
511 return args
512 ip.push({"Integer": Integer})
513
514 def tearDown(self):
515 ip.ast_transformers.remove(self.intwrapper)
516 del ip.user_ns['Integer']
517
518 def test_run_cell(self):
519 ip.run_cell("n = 2")
520 self.assertEqual(self.calls, [(2,)])
521
522 # This shouldn't throw an error
523 ip.run_cell("o = 2.0")
524 self.assertEqual(ip.user_ns['o'], 2.0)
525
526 def test_timeit(self):
527 called = set()
528 def f(x):
529 called.add(x)
530 ip.push({'f':f})
531
532 with tt.AssertPrints("best of "):
533 ip.run_line_magic("timeit", "-n1 f(1)")
534 self.assertEqual(called, set([(1,)]))
535 called.clear()
536
537 with tt.AssertPrints("best of "):
538 ip.run_cell_magic("timeit", "-n1 f(2)", "f(3)")
539 self.assertEqual(called, set([(2,), (3,)]))
540
541 class ErrorTransformer(ast.NodeTransformer):
542 """Throws an error when it sees a number."""
543 def visit_Num(self):
544 raise ValueError("test")
545
546 class TestAstTransformError(unittest.TestCase):
547 def test_unregistering(self):
548 err_transformer = ErrorTransformer()
549 ip.ast_transformers.append(err_transformer)
550
551 with tt.AssertPrints("unregister", channel='stderr'):
552 ip.run_cell("1 + 2")
553
554 # This should have been removed.
555 nt.assert_not_in(err_transformer, ip.ast_transformers)
429 556
430 557 def test__IPYTHON__():
431 558 # This shouldn't raise a NameError, that's all
432 559 __IPYTHON__
@@ -1,393 +1,393 b''
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3 """
4 4 The :class:`~IPython.core.application.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 12 * Min Ragan-Kelley
13 13 """
14 14
15 15 #-----------------------------------------------------------------------------
16 16 # Copyright (C) 2008-2011 The IPython Development Team
17 17 #
18 18 # Distributed under the terms of the BSD License. The full license is in
19 19 # the file COPYING, distributed as part of this software.
20 20 #-----------------------------------------------------------------------------
21 21
22 22 #-----------------------------------------------------------------------------
23 23 # Imports
24 24 #-----------------------------------------------------------------------------
25 25
26 26 from __future__ import absolute_import
27 27
28 28 import logging
29 29 import os
30 30 import sys
31 31
32 32 from IPython.config.loader import (
33 33 Config, PyFileConfigLoader, ConfigFileNotFound
34 34 )
35 35 from IPython.config.application import boolean_flag, catch_config_error
36 36 from IPython.core import release
37 37 from IPython.core import usage
38 38 from IPython.core.completer import IPCompleter
39 39 from IPython.core.crashhandler import CrashHandler
40 40 from IPython.core.formatters import PlainTextFormatter
41 41 from IPython.core.history import HistoryManager
42 42 from IPython.core.prompts import PromptManager
43 43 from IPython.core.application import (
44 44 ProfileDir, BaseIPythonApplication, base_flags, base_aliases
45 45 )
46 46 from IPython.core.magics import ScriptMagics
47 47 from IPython.core.shellapp import (
48 48 InteractiveShellApp, shell_flags, shell_aliases
49 49 )
50 50 from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
51 51 from IPython.lib import inputhook
52 52 from IPython.utils import warn
53 53 from IPython.utils.path import get_ipython_dir, check_for_old_config
54 54 from IPython.utils.traitlets import (
55 55 Bool, List, Dict, CaselessStrEnum
56 56 )
57 57
58 58 #-----------------------------------------------------------------------------
59 59 # Globals, utilities and helpers
60 60 #-----------------------------------------------------------------------------
61 61
62 62 #: The default config file name for this application.
63 63 default_config_file_name = u'ipython_config.py'
64 64
65 65 _examples = """
66 66 ipython --pylab # start in pylab mode
67 67 ipython --pylab=qt # start in pylab mode with the qt4 backend
68 68 ipython --log-level=DEBUG # set logging to DEBUG
69 69 ipython --profile=foo # start with profile foo
70 70
71 71 ipython qtconsole # start the qtconsole GUI application
72 72 ipython help qtconsole # show the help for the qtconsole subcmd
73 73
74 74 ipython console # start the terminal-based console application
75 75 ipython help console # show the help for the console subcmd
76 76
77 77 ipython notebook # start the IPython notebook
78 78 ipython help notebook # show the help for the notebook subcmd
79 79
80 80 ipython profile create foo # create profile foo w/ default config files
81 81 ipython help profile # show the help for the profile subcmd
82 82
83 83 ipython locate # print the path to the IPython directory
84 84 ipython locate profile foo # print the path to the directory for profile `foo`
85 85 """
86 86
87 87 #-----------------------------------------------------------------------------
88 88 # Crash handler for this application
89 89 #-----------------------------------------------------------------------------
90 90
91 91 class IPAppCrashHandler(CrashHandler):
92 92 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
93 93
94 94 def __init__(self, app):
95 95 contact_name = release.authors['Fernando'][0]
96 96 contact_email = release.author_email
97 97 bug_tracker = 'https://github.com/ipython/ipython/issues'
98 98 super(IPAppCrashHandler,self).__init__(
99 99 app, contact_name, contact_email, bug_tracker
100 100 )
101 101
102 102 def make_report(self,traceback):
103 103 """Return a string containing a crash report."""
104 104
105 105 sec_sep = self.section_sep
106 106 # Start with parent report
107 107 report = [super(IPAppCrashHandler, self).make_report(traceback)]
108 108 # Add interactive-specific info we may have
109 109 rpt_add = report.append
110 110 try:
111 111 rpt_add(sec_sep+"History of session input:")
112 112 for line in self.app.shell.user_ns['_ih']:
113 113 rpt_add(line)
114 114 rpt_add('\n*** Last line of input (may not be in above history):\n')
115 115 rpt_add(self.app.shell._last_input_line+'\n')
116 116 except:
117 117 pass
118 118
119 119 return ''.join(report)
120 120
121 121 #-----------------------------------------------------------------------------
122 122 # Aliases and Flags
123 123 #-----------------------------------------------------------------------------
124 124 flags = dict(base_flags)
125 125 flags.update(shell_flags)
126 126 frontend_flags = {}
127 127 addflag = lambda *args: frontend_flags.update(boolean_flag(*args))
128 128 addflag('autoedit-syntax', 'TerminalInteractiveShell.autoedit_syntax',
129 129 'Turn on auto editing of files with syntax errors.',
130 130 'Turn off auto editing of files with syntax errors.'
131 131 )
132 132 addflag('banner', 'TerminalIPythonApp.display_banner',
133 133 "Display a banner upon starting IPython.",
134 134 "Don't display a banner upon starting IPython."
135 135 )
136 136 addflag('confirm-exit', 'TerminalInteractiveShell.confirm_exit',
137 137 """Set to confirm when you try to exit IPython with an EOF (Control-D
138 138 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
139 139 you can force a direct exit without any confirmation.""",
140 140 "Don't prompt the user when exiting."
141 141 )
142 142 addflag('term-title', 'TerminalInteractiveShell.term_title',
143 143 "Enable auto setting the terminal title.",
144 144 "Disable auto setting the terminal title."
145 145 )
146 146 classic_config = Config()
147 147 classic_config.InteractiveShell.cache_size = 0
148 148 classic_config.PlainTextFormatter.pprint = False
149 149 classic_config.PromptManager.in_template = '>>> '
150 150 classic_config.PromptManager.in2_template = '... '
151 151 classic_config.PromptManager.out_template = ''
152 152 classic_config.InteractiveShell.separate_in = ''
153 153 classic_config.InteractiveShell.separate_out = ''
154 154 classic_config.InteractiveShell.separate_out2 = ''
155 155 classic_config.InteractiveShell.colors = 'NoColor'
156 156 classic_config.InteractiveShell.xmode = 'Plain'
157 157
158 158 frontend_flags['classic']=(
159 159 classic_config,
160 160 "Gives IPython a similar feel to the classic Python prompt."
161 161 )
162 162 # # log doesn't make so much sense this way anymore
163 163 # paa('--log','-l',
164 164 # action='store_true', dest='InteractiveShell.logstart',
165 165 # help="Start logging to the default log file (./ipython_log.py).")
166 166 #
167 167 # # quick is harder to implement
168 168 frontend_flags['quick']=(
169 169 {'TerminalIPythonApp' : {'quick' : True}},
170 170 "Enable quick startup with no config files."
171 171 )
172 172
173 173 frontend_flags['i'] = (
174 174 {'TerminalIPythonApp' : {'force_interact' : True}},
175 175 """If running code from the command line, become interactive afterwards.
176 176 Note: can also be given simply as '-i.'"""
177 177 )
178 178 flags.update(frontend_flags)
179 179
180 180 aliases = dict(base_aliases)
181 181 aliases.update(shell_aliases)
182 182
183 183 #-----------------------------------------------------------------------------
184 184 # Main classes and functions
185 185 #-----------------------------------------------------------------------------
186 186
187 187
188 188 class LocateIPythonApp(BaseIPythonApplication):
189 189 description = """print the path to the IPython dir"""
190 190 subcommands = Dict(dict(
191 191 profile=('IPython.core.profileapp.ProfileLocate',
192 192 "print the path to an IPython profile directory",
193 193 ),
194 194 ))
195 195 def start(self):
196 196 if self.subapp is not None:
197 197 return self.subapp.start()
198 198 else:
199 199 print self.ipython_dir
200 200
201 201
202 202 class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):
203 203 name = u'ipython'
204 204 description = usage.cl_usage
205 205 default_config_file_name = default_config_file_name
206 206 crash_handler_class = IPAppCrashHandler
207 207 examples = _examples
208 208
209 209 flags = Dict(flags)
210 210 aliases = Dict(aliases)
211 211 classes = List()
212 212 def _classes_default(self):
213 213 """This has to be in a method, for TerminalIPythonApp to be available."""
214 214 return [
215 215 InteractiveShellApp, # ShellApp comes before TerminalApp, because
216 216 self.__class__, # it will also affect subclasses (e.g. QtConsole)
217 217 TerminalInteractiveShell,
218 218 PromptManager,
219 219 HistoryManager,
220 220 ProfileDir,
221 221 PlainTextFormatter,
222 222 IPCompleter,
223 223 ScriptMagics,
224 224 ]
225 225
226 226 subcommands = Dict(dict(
227 227 qtconsole=('IPython.frontend.qt.console.qtconsoleapp.IPythonQtConsoleApp',
228 228 """Launch the IPython Qt Console."""
229 229 ),
230 230 notebook=('IPython.frontend.html.notebook.notebookapp.NotebookApp',
231 231 """Launch the IPython HTML Notebook Server."""
232 232 ),
233 233 profile = ("IPython.core.profileapp.ProfileApp",
234 234 "Create and manage IPython profiles."
235 235 ),
236 236 kernel = ("IPython.zmq.ipkernel.IPKernelApp",
237 237 "Start a kernel without an attached frontend."
238 238 ),
239 239 console=('IPython.frontend.terminal.console.app.ZMQTerminalIPythonApp',
240 240 """Launch the IPython terminal-based Console."""
241 241 ),
242 242 locate=('IPython.frontend.terminal.ipapp.LocateIPythonApp',
243 243 LocateIPythonApp.description
244 244 ),
245 245 ))
246 246
247 247 # *do* autocreate requested profile, but don't create the config file.
248 248 auto_create=Bool(True)
249 249 # configurables
250 250 ignore_old_config=Bool(False, config=True,
251 251 help="Suppress warning messages about legacy config files"
252 252 )
253 253 quick = Bool(False, config=True,
254 254 help="""Start IPython quickly by skipping the loading of config files."""
255 255 )
256 256 def _quick_changed(self, name, old, new):
257 257 if new:
258 258 self.load_config_file = lambda *a, **kw: None
259 259 self.ignore_old_config=True
260 260
261 261 display_banner = Bool(True, config=True,
262 262 help="Whether to display a banner upon starting IPython."
263 263 )
264 264
265 265 # if there is code of files to run from the cmd line, don't interact
266 266 # unless the --i flag (App.force_interact) is true.
267 267 force_interact = Bool(False, config=True,
268 268 help="""If a command or file is given via the command-line,
269 269 e.g. 'ipython foo.py"""
270 270 )
271 271 def _force_interact_changed(self, name, old, new):
272 272 if new:
273 273 self.interact = True
274 274
275 275 def _file_to_run_changed(self, name, old, new):
276 276 if new:
277 277 self.something_to_run = True
278 278 if new and not self.force_interact:
279 279 self.interact = False
280 280 _code_to_run_changed = _file_to_run_changed
281 281 _module_to_run_changed = _file_to_run_changed
282 282
283 283 # internal, not-configurable
284 284 interact=Bool(True)
285 285 something_to_run=Bool(False)
286 286
287 287 def parse_command_line(self, argv=None):
288 288 """override to allow old '-pylab' flag with deprecation warning"""
289 289
290 290 argv = sys.argv[1:] if argv is None else argv
291 291
292 292 if '-pylab' in argv:
293 293 # deprecated `-pylab` given,
294 294 # warn and transform into current syntax
295 295 argv = argv[:] # copy, don't clobber
296 296 idx = argv.index('-pylab')
297 297 warn.warn("`-pylab` flag has been deprecated.\n"
298 298 " Use `--pylab` instead, or `--pylab=foo` to specify a backend.")
299 299 sub = '--pylab'
300 300 if len(argv) > idx+1:
301 301 # check for gui arg, as in '-pylab qt'
302 302 gui = argv[idx+1]
303 303 if gui in ('wx', 'qt', 'qt4', 'gtk', 'auto'):
304 304 sub = '--pylab='+gui
305 305 argv.pop(idx+1)
306 306 argv[idx] = sub
307 307
308 308 return super(TerminalIPythonApp, self).parse_command_line(argv)
309 309
310 310 @catch_config_error
311 311 def initialize(self, argv=None):
312 312 """Do actions after construct, but before starting the app."""
313 313 super(TerminalIPythonApp, self).initialize(argv)
314 314 if self.subapp is not None:
315 315 # don't bother initializing further, starting subapp
316 316 return
317 317 if not self.ignore_old_config:
318 318 check_for_old_config(self.ipython_dir)
319 319 # print self.extra_args
320 320 if self.extra_args and not self.something_to_run:
321 321 self.file_to_run = self.extra_args[0]
322 322 self.init_path()
323 323 # create the shell
324 324 self.init_shell()
325 325 # and draw the banner
326 326 self.init_banner()
327 327 # Now a variety of things that happen after the banner is printed.
328 328 self.init_gui_pylab()
329 329 self.init_extensions()
330 330 self.init_code()
331 331
332 332 def init_shell(self):
333 333 """initialize the InteractiveShell instance"""
334 334 # Create an InteractiveShell instance.
335 335 # shell.display_banner should always be False for the terminal
336 336 # based app, because we call shell.show_banner() by hand below
337 337 # so the banner shows *before* all extension loading stuff.
338 338 self.shell = TerminalInteractiveShell.instance(config=self.config,
339 339 display_banner=False, profile_dir=self.profile_dir,
340 340 ipython_dir=self.ipython_dir)
341 341 self.shell.configurables.append(self)
342 342
343 343 def init_banner(self):
344 344 """optionally display the banner"""
345 345 if self.display_banner and self.interact:
346 346 self.shell.show_banner()
347 347 # Make sure there is a space below the banner.
348 348 if self.log_level <= logging.INFO: print
349 349
350 350 def _pylab_changed(self, name, old, new):
351 351 """Replace --pylab='inline' with --pylab='auto'"""
352 352 if new == 'inline':
353 353 warn.warn("'inline' not available as pylab backend, "
354 "using 'auto' instead.\n")
354 "using 'auto' instead.")
355 355 self.pylab = 'auto'
356 356
357 357 def start(self):
358 358 if self.subapp is not None:
359 359 return self.subapp.start()
360 360 # perform any prexec steps:
361 361 if self.interact:
362 362 self.log.debug("Starting IPython's mainloop...")
363 363 self.shell.mainloop()
364 364 else:
365 365 self.log.debug("IPython not interactive...")
366 366
367 367
368 368 def load_default_config(ipython_dir=None):
369 369 """Load the default config file from the default ipython_dir.
370 370
371 371 This is useful for embedded shells.
372 372 """
373 373 if ipython_dir is None:
374 374 ipython_dir = get_ipython_dir()
375 375 profile_dir = os.path.join(ipython_dir, 'profile_default')
376 376 cl = PyFileConfigLoader(default_config_file_name, profile_dir)
377 377 try:
378 378 config = cl.load_config()
379 379 except ConfigFileNotFound:
380 380 # no config found
381 381 config = Config()
382 382 return config
383 383
384 384
385 385 def launch_new_instance():
386 386 """Create and run a full blown IPython instance"""
387 387 app = TerminalIPythonApp.instance()
388 388 app.initialize()
389 389 app.start()
390 390
391 391
392 392 if __name__ == '__main__':
393 393 launch_new_instance()
@@ -1,529 +1,529 b''
1 1 # coding: utf-8
2 2 """
3 3 Inputhook management for GUI event loop integration.
4 4 """
5 5
6 6 #-----------------------------------------------------------------------------
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 try:
18 18 import ctypes
19 19 except ImportError:
20 20 ctypes = None
21 21 import os
22 22 import sys
23 23 from distutils.version import LooseVersion as V
24 24
25 25 from IPython.utils.warn import warn
26 26
27 27 #-----------------------------------------------------------------------------
28 28 # Constants
29 29 #-----------------------------------------------------------------------------
30 30
31 31 # Constants for identifying the GUI toolkits.
32 32 GUI_WX = 'wx'
33 33 GUI_QT = 'qt'
34 34 GUI_QT4 = 'qt4'
35 35 GUI_GTK = 'gtk'
36 36 GUI_TK = 'tk'
37 37 GUI_OSX = 'osx'
38 38 GUI_GLUT = 'glut'
39 39 GUI_PYGLET = 'pyglet'
40 40 GUI_GTK3 = 'gtk3'
41 41 GUI_NONE = 'none' # i.e. disable
42 42
43 43 #-----------------------------------------------------------------------------
44 44 # Utilities
45 45 #-----------------------------------------------------------------------------
46 46
47 47 def _stdin_ready_posix():
48 48 """Return True if there's something to read on stdin (posix version)."""
49 49 infds, outfds, erfds = select.select([sys.stdin],[],[],0)
50 50 return bool(infds)
51 51
52 52 def _stdin_ready_nt():
53 53 """Return True if there's something to read on stdin (nt version)."""
54 54 return msvcrt.kbhit()
55 55
56 56 def _stdin_ready_other():
57 57 """Return True, assuming there's something to read on stdin."""
58 58 return True #
59 59
60 60
61 61 def _ignore_CTRL_C_posix():
62 62 """Ignore CTRL+C (SIGINT)."""
63 63 signal.signal(signal.SIGINT, signal.SIG_IGN)
64 64
65 65 def _allow_CTRL_C_posix():
66 66 """Take CTRL+C into account (SIGINT)."""
67 67 signal.signal(signal.SIGINT, signal.default_int_handler)
68 68
69 69 def _ignore_CTRL_C_other():
70 70 """Ignore CTRL+C (not implemented)."""
71 71 pass
72 72
73 73 def _allow_CTRL_C_other():
74 74 """Take CTRL+C into account (not implemented)."""
75 75 pass
76 76
77 77 if os.name == 'posix':
78 78 import select
79 79 import signal
80 80 stdin_ready = _stdin_ready_posix
81 81 ignore_CTRL_C = _ignore_CTRL_C_posix
82 82 allow_CTRL_C = _allow_CTRL_C_posix
83 83 elif os.name == 'nt':
84 84 import msvcrt
85 85 stdin_ready = _stdin_ready_nt
86 86 ignore_CTRL_C = _ignore_CTRL_C_other
87 87 allow_CTRL_C = _allow_CTRL_C_other
88 88 else:
89 89 stdin_ready = _stdin_ready_other
90 90 ignore_CTRL_C = _ignore_CTRL_C_other
91 91 allow_CTRL_C = _allow_CTRL_C_other
92 92
93 93
94 94 #-----------------------------------------------------------------------------
95 95 # Main InputHookManager class
96 96 #-----------------------------------------------------------------------------
97 97
98 98
99 99 class InputHookManager(object):
100 100 """Manage PyOS_InputHook for different GUI toolkits.
101 101
102 102 This class installs various hooks under ``PyOSInputHook`` to handle
103 103 GUI event loop integration.
104 104 """
105 105
106 106 def __init__(self):
107 107 if ctypes is None:
108 warn("IPython GUI event loop requires ctypes, %gui will not be available\n")
108 warn("IPython GUI event loop requires ctypes, %gui will not be available")
109 109 return
110 110 self.PYFUNC = ctypes.PYFUNCTYPE(ctypes.c_int)
111 111 self._apps = {}
112 112 self._reset()
113 113
114 114 def _reset(self):
115 115 self._callback_pyfunctype = None
116 116 self._callback = None
117 117 self._installed = False
118 118 self._current_gui = None
119 119
120 120 def get_pyos_inputhook(self):
121 121 """Return the current PyOS_InputHook as a ctypes.c_void_p."""
122 122 return ctypes.c_void_p.in_dll(ctypes.pythonapi,"PyOS_InputHook")
123 123
124 124 def get_pyos_inputhook_as_func(self):
125 125 """Return the current PyOS_InputHook as a ctypes.PYFUNCYPE."""
126 126 return self.PYFUNC.in_dll(ctypes.pythonapi,"PyOS_InputHook")
127 127
128 128 def set_inputhook(self, callback):
129 129 """Set PyOS_InputHook to callback and return the previous one."""
130 130 # On platforms with 'readline' support, it's all too likely to
131 131 # have a KeyboardInterrupt signal delivered *even before* an
132 132 # initial ``try:`` clause in the callback can be executed, so
133 133 # we need to disable CTRL+C in this situation.
134 134 ignore_CTRL_C()
135 135 self._callback = callback
136 136 self._callback_pyfunctype = self.PYFUNC(callback)
137 137 pyos_inputhook_ptr = self.get_pyos_inputhook()
138 138 original = self.get_pyos_inputhook_as_func()
139 139 pyos_inputhook_ptr.value = \
140 140 ctypes.cast(self._callback_pyfunctype, ctypes.c_void_p).value
141 141 self._installed = True
142 142 return original
143 143
144 144 def clear_inputhook(self, app=None):
145 145 """Set PyOS_InputHook to NULL and return the previous one.
146 146
147 147 Parameters
148 148 ----------
149 149 app : optional, ignored
150 150 This parameter is allowed only so that clear_inputhook() can be
151 151 called with a similar interface as all the ``enable_*`` methods. But
152 152 the actual value of the parameter is ignored. This uniform interface
153 153 makes it easier to have user-level entry points in the main IPython
154 154 app like :meth:`enable_gui`."""
155 155 pyos_inputhook_ptr = self.get_pyos_inputhook()
156 156 original = self.get_pyos_inputhook_as_func()
157 157 pyos_inputhook_ptr.value = ctypes.c_void_p(None).value
158 158 allow_CTRL_C()
159 159 self._reset()
160 160 return original
161 161
162 162 def clear_app_refs(self, gui=None):
163 163 """Clear IPython's internal reference to an application instance.
164 164
165 165 Whenever we create an app for a user on qt4 or wx, we hold a
166 166 reference to the app. This is needed because in some cases bad things
167 167 can happen if a user doesn't hold a reference themselves. This
168 168 method is provided to clear the references we are holding.
169 169
170 170 Parameters
171 171 ----------
172 172 gui : None or str
173 173 If None, clear all app references. If ('wx', 'qt4') clear
174 174 the app for that toolkit. References are not held for gtk or tk
175 175 as those toolkits don't have the notion of an app.
176 176 """
177 177 if gui is None:
178 178 self._apps = {}
179 179 elif gui in self._apps:
180 180 del self._apps[gui]
181 181
182 182 def enable_wx(self, app=None):
183 183 """Enable event loop integration with wxPython.
184 184
185 185 Parameters
186 186 ----------
187 187 app : WX Application, optional.
188 188 Running application to use. If not given, we probe WX for an
189 189 existing application object, and create a new one if none is found.
190 190
191 191 Notes
192 192 -----
193 193 This methods sets the ``PyOS_InputHook`` for wxPython, which allows
194 194 the wxPython to integrate with terminal based applications like
195 195 IPython.
196 196
197 197 If ``app`` is not given we probe for an existing one, and return it if
198 198 found. If no existing app is found, we create an :class:`wx.App` as
199 199 follows::
200 200
201 201 import wx
202 202 app = wx.App(redirect=False, clearSigInt=False)
203 203 """
204 204 import wx
205 205
206 206 wx_version = V(wx.__version__).version
207 207
208 208 if wx_version < [2, 8]:
209 209 raise ValueError("requires wxPython >= 2.8, but you have %s" % wx.__version__)
210 210
211 211 from IPython.lib.inputhookwx import inputhook_wx
212 212 self.set_inputhook(inputhook_wx)
213 213 self._current_gui = GUI_WX
214 214 import wx
215 215 if app is None:
216 216 app = wx.GetApp()
217 217 if app is None:
218 218 app = wx.App(redirect=False, clearSigInt=False)
219 219 app._in_event_loop = True
220 220 self._apps[GUI_WX] = app
221 221 return app
222 222
223 223 def disable_wx(self):
224 224 """Disable event loop integration with wxPython.
225 225
226 226 This merely sets PyOS_InputHook to NULL.
227 227 """
228 228 if GUI_WX in self._apps:
229 229 self._apps[GUI_WX]._in_event_loop = False
230 230 self.clear_inputhook()
231 231
232 232 def enable_qt4(self, app=None):
233 233 """Enable event loop integration with PyQt4.
234 234
235 235 Parameters
236 236 ----------
237 237 app : Qt Application, optional.
238 238 Running application to use. If not given, we probe Qt for an
239 239 existing application object, and create a new one if none is found.
240 240
241 241 Notes
242 242 -----
243 243 This methods sets the PyOS_InputHook for PyQt4, which allows
244 244 the PyQt4 to integrate with terminal based applications like
245 245 IPython.
246 246
247 247 If ``app`` is not given we probe for an existing one, and return it if
248 248 found. If no existing app is found, we create an :class:`QApplication`
249 249 as follows::
250 250
251 251 from PyQt4 import QtCore
252 252 app = QtGui.QApplication(sys.argv)
253 253 """
254 254 from IPython.lib.inputhookqt4 import create_inputhook_qt4
255 255 app, inputhook_qt4 = create_inputhook_qt4(self, app)
256 256 self.set_inputhook(inputhook_qt4)
257 257
258 258 self._current_gui = GUI_QT4
259 259 app._in_event_loop = True
260 260 self._apps[GUI_QT4] = app
261 261 return app
262 262
263 263 def disable_qt4(self):
264 264 """Disable event loop integration with PyQt4.
265 265
266 266 This merely sets PyOS_InputHook to NULL.
267 267 """
268 268 if GUI_QT4 in self._apps:
269 269 self._apps[GUI_QT4]._in_event_loop = False
270 270 self.clear_inputhook()
271 271
272 272 def enable_gtk(self, app=None):
273 273 """Enable event loop integration with PyGTK.
274 274
275 275 Parameters
276 276 ----------
277 277 app : ignored
278 278 Ignored, it's only a placeholder to keep the call signature of all
279 279 gui activation methods consistent, which simplifies the logic of
280 280 supporting magics.
281 281
282 282 Notes
283 283 -----
284 284 This methods sets the PyOS_InputHook for PyGTK, which allows
285 285 the PyGTK to integrate with terminal based applications like
286 286 IPython.
287 287 """
288 288 import gtk
289 289 try:
290 290 gtk.set_interactive(True)
291 291 self._current_gui = GUI_GTK
292 292 except AttributeError:
293 293 # For older versions of gtk, use our own ctypes version
294 294 from IPython.lib.inputhookgtk import inputhook_gtk
295 295 self.set_inputhook(inputhook_gtk)
296 296 self._current_gui = GUI_GTK
297 297
298 298 def disable_gtk(self):
299 299 """Disable event loop integration with PyGTK.
300 300
301 301 This merely sets PyOS_InputHook to NULL.
302 302 """
303 303 self.clear_inputhook()
304 304
305 305 def enable_tk(self, app=None):
306 306 """Enable event loop integration with Tk.
307 307
308 308 Parameters
309 309 ----------
310 310 app : toplevel :class:`Tkinter.Tk` widget, optional.
311 311 Running toplevel widget to use. If not given, we probe Tk for an
312 312 existing one, and create a new one if none is found.
313 313
314 314 Notes
315 315 -----
316 316 If you have already created a :class:`Tkinter.Tk` object, the only
317 317 thing done by this method is to register with the
318 318 :class:`InputHookManager`, since creating that object automatically
319 319 sets ``PyOS_InputHook``.
320 320 """
321 321 self._current_gui = GUI_TK
322 322 if app is None:
323 323 import Tkinter
324 324 app = Tkinter.Tk()
325 325 app.withdraw()
326 326 self._apps[GUI_TK] = app
327 327 return app
328 328
329 329 def disable_tk(self):
330 330 """Disable event loop integration with Tkinter.
331 331
332 332 This merely sets PyOS_InputHook to NULL.
333 333 """
334 334 self.clear_inputhook()
335 335
336 336
337 337 def enable_glut(self, app=None):
338 338 """ Enable event loop integration with GLUT.
339 339
340 340 Parameters
341 341 ----------
342 342
343 343 app : ignored
344 344 Ignored, it's only a placeholder to keep the call signature of all
345 345 gui activation methods consistent, which simplifies the logic of
346 346 supporting magics.
347 347
348 348 Notes
349 349 -----
350 350
351 351 This methods sets the PyOS_InputHook for GLUT, which allows the GLUT to
352 352 integrate with terminal based applications like IPython. Due to GLUT
353 353 limitations, it is currently not possible to start the event loop
354 354 without first creating a window. You should thus not create another
355 355 window but use instead the created one. See 'gui-glut.py' in the
356 356 docs/examples/lib directory.
357 357
358 358 The default screen mode is set to:
359 359 glut.GLUT_DOUBLE | glut.GLUT_RGBA | glut.GLUT_DEPTH
360 360 """
361 361
362 362 import OpenGL.GLUT as glut
363 363 from IPython.lib.inputhookglut import glut_display_mode, \
364 364 glut_close, glut_display, \
365 365 glut_idle, inputhook_glut
366 366
367 367 if GUI_GLUT not in self._apps:
368 368 glut.glutInit( sys.argv )
369 369 glut.glutInitDisplayMode( glut_display_mode )
370 370 # This is specific to freeglut
371 371 if bool(glut.glutSetOption):
372 372 glut.glutSetOption( glut.GLUT_ACTION_ON_WINDOW_CLOSE,
373 373 glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS )
374 374 glut.glutCreateWindow( sys.argv[0] )
375 375 glut.glutReshapeWindow( 1, 1 )
376 376 glut.glutHideWindow( )
377 377 glut.glutWMCloseFunc( glut_close )
378 378 glut.glutDisplayFunc( glut_display )
379 379 glut.glutIdleFunc( glut_idle )
380 380 else:
381 381 glut.glutWMCloseFunc( glut_close )
382 382 glut.glutDisplayFunc( glut_display )
383 383 glut.glutIdleFunc( glut_idle)
384 384 self.set_inputhook( inputhook_glut )
385 385 self._current_gui = GUI_GLUT
386 386 self._apps[GUI_GLUT] = True
387 387
388 388
389 389 def disable_glut(self):
390 390 """Disable event loop integration with glut.
391 391
392 392 This sets PyOS_InputHook to NULL and set the display function to a
393 393 dummy one and set the timer to a dummy timer that will be triggered
394 394 very far in the future.
395 395 """
396 396 import OpenGL.GLUT as glut
397 397 from glut_support import glutMainLoopEvent
398 398
399 399 glut.glutHideWindow() # This is an event to be processed below
400 400 glutMainLoopEvent()
401 401 self.clear_inputhook()
402 402
403 403 def enable_pyglet(self, app=None):
404 404 """Enable event loop integration with pyglet.
405 405
406 406 Parameters
407 407 ----------
408 408 app : ignored
409 409 Ignored, it's only a placeholder to keep the call signature of all
410 410 gui activation methods consistent, which simplifies the logic of
411 411 supporting magics.
412 412
413 413 Notes
414 414 -----
415 415 This methods sets the ``PyOS_InputHook`` for pyglet, which allows
416 416 pyglet to integrate with terminal based applications like
417 417 IPython.
418 418
419 419 """
420 420 import pyglet
421 421 from IPython.lib.inputhookpyglet import inputhook_pyglet
422 422 self.set_inputhook(inputhook_pyglet)
423 423 self._current_gui = GUI_PYGLET
424 424 return app
425 425
426 426 def disable_pyglet(self):
427 427 """Disable event loop integration with pyglet.
428 428
429 429 This merely sets PyOS_InputHook to NULL.
430 430 """
431 431 self.clear_inputhook()
432 432
433 433 def enable_gtk3(self, app=None):
434 434 """Enable event loop integration with Gtk3 (gir bindings).
435 435
436 436 Parameters
437 437 ----------
438 438 app : ignored
439 439 Ignored, it's only a placeholder to keep the call signature of all
440 440 gui activation methods consistent, which simplifies the logic of
441 441 supporting magics.
442 442
443 443 Notes
444 444 -----
445 445 This methods sets the PyOS_InputHook for Gtk3, which allows
446 446 the Gtk3 to integrate with terminal based applications like
447 447 IPython.
448 448 """
449 449 from IPython.lib.inputhookgtk3 import inputhook_gtk3
450 450 self.set_inputhook(inputhook_gtk3)
451 451 self._current_gui = GUI_GTK
452 452
453 453 def disable_gtk3(self):
454 454 """Disable event loop integration with PyGTK.
455 455
456 456 This merely sets PyOS_InputHook to NULL.
457 457 """
458 458 self.clear_inputhook()
459 459
460 460 def current_gui(self):
461 461 """Return a string indicating the currently active GUI or None."""
462 462 return self._current_gui
463 463
464 464 inputhook_manager = InputHookManager()
465 465
466 466 enable_wx = inputhook_manager.enable_wx
467 467 disable_wx = inputhook_manager.disable_wx
468 468 enable_qt4 = inputhook_manager.enable_qt4
469 469 disable_qt4 = inputhook_manager.disable_qt4
470 470 enable_gtk = inputhook_manager.enable_gtk
471 471 disable_gtk = inputhook_manager.disable_gtk
472 472 enable_tk = inputhook_manager.enable_tk
473 473 disable_tk = inputhook_manager.disable_tk
474 474 enable_glut = inputhook_manager.enable_glut
475 475 disable_glut = inputhook_manager.disable_glut
476 476 enable_pyglet = inputhook_manager.enable_pyglet
477 477 disable_pyglet = inputhook_manager.disable_pyglet
478 478 enable_gtk3 = inputhook_manager.enable_gtk3
479 479 disable_gtk3 = inputhook_manager.disable_gtk3
480 480 clear_inputhook = inputhook_manager.clear_inputhook
481 481 set_inputhook = inputhook_manager.set_inputhook
482 482 current_gui = inputhook_manager.current_gui
483 483 clear_app_refs = inputhook_manager.clear_app_refs
484 484
485 485
486 486 # Convenience function to switch amongst them
487 487 def enable_gui(gui=None, app=None):
488 488 """Switch amongst GUI input hooks by name.
489 489
490 490 This is just a utility wrapper around the methods of the InputHookManager
491 491 object.
492 492
493 493 Parameters
494 494 ----------
495 495 gui : optional, string or None
496 496 If None (or 'none'), clears input hook, otherwise it must be one
497 497 of the recognized GUI names (see ``GUI_*`` constants in module).
498 498
499 499 app : optional, existing application object.
500 500 For toolkits that have the concept of a global app, you can supply an
501 501 existing one. If not given, the toolkit will be probed for one, and if
502 502 none is found, a new one will be created. Note that GTK does not have
503 503 this concept, and passing an app if `gui`=="GTK" will raise an error.
504 504
505 505 Returns
506 506 -------
507 507 The output of the underlying gui switch routine, typically the actual
508 508 PyOS_InputHook wrapper object or the GUI toolkit app created, if there was
509 509 one.
510 510 """
511 511 guis = {None: clear_inputhook,
512 512 GUI_NONE: clear_inputhook,
513 513 GUI_OSX: lambda app=False: None,
514 514 GUI_TK: enable_tk,
515 515 GUI_GTK: enable_gtk,
516 516 GUI_WX: enable_wx,
517 517 GUI_QT: enable_qt4, # qt3 not supported
518 518 GUI_QT4: enable_qt4,
519 519 GUI_GLUT: enable_glut,
520 520 GUI_PYGLET: enable_pyglet,
521 521 GUI_GTK3: enable_gtk3,
522 522 }
523 523 try:
524 524 gui_hook = guis[gui]
525 525 except KeyError:
526 526 e = "Invalid GUI request %r, valid ones are:%s" % (gui, guis.keys())
527 527 raise ValueError(e)
528 528 return gui_hook(app)
529 529
@@ -1,595 +1,595 b''
1 1 # -*- coding: utf-8 -*-
2 2 """IPython Test Suite Runner.
3 3
4 4 This module provides a main entry point to a user script to test IPython
5 5 itself from the command line. There are two ways of running this script:
6 6
7 7 1. With the syntax `iptest all`. This runs our entire test suite by
8 8 calling this script (with different arguments) recursively. This
9 9 causes modules and package to be tested in different processes, using nose
10 10 or trial where appropriate.
11 11 2. With the regular nose syntax, like `iptest -vvs IPython`. In this form
12 12 the script simply calls nose, but with special command line flags and
13 13 plugins loaded.
14 14
15 15 """
16 16
17 17 #-----------------------------------------------------------------------------
18 18 # Copyright (C) 2009-2011 The IPython Development Team
19 19 #
20 20 # Distributed under the terms of the BSD License. The full license is in
21 21 # the file COPYING, distributed as part of this software.
22 22 #-----------------------------------------------------------------------------
23 23
24 24 #-----------------------------------------------------------------------------
25 25 # Imports
26 26 #-----------------------------------------------------------------------------
27 27 from __future__ import print_function
28 28
29 29 # Stdlib
30 30 import glob
31 31 import os
32 32 import os.path as path
33 33 import signal
34 34 import sys
35 35 import subprocess
36 36 import tempfile
37 37 import time
38 38 import warnings
39 39
40 40 # Note: monkeypatch!
41 41 # We need to monkeypatch a small problem in nose itself first, before importing
42 42 # it for actual use. This should get into nose upstream, but its release cycle
43 43 # is slow and we need it for our parametric tests to work correctly.
44 44 from IPython.testing import nosepatch
45 45
46 46 # Monkeypatch extra assert methods into nose.tools if they're not already there.
47 47 # This can be dropped once we no longer test on Python 2.6
48 48 from IPython.testing import nose_assert_methods
49 49
50 50 # Now, proceed to import nose itself
51 51 import nose.plugins.builtin
52 52 from nose.plugins.xunit import Xunit
53 53 from nose import SkipTest
54 54 from nose.core import TestProgram
55 55
56 56 # Our own imports
57 57 from IPython.utils import py3compat
58 58 from IPython.utils.importstring import import_item
59 59 from IPython.utils.path import get_ipython_module_path, get_ipython_package_dir
60 60 from IPython.utils.process import find_cmd, pycmd2argv
61 61 from IPython.utils.sysinfo import sys_info
62 62 from IPython.utils.tempdir import TemporaryDirectory
63 63 from IPython.utils.warn import warn
64 64
65 65 from IPython.testing import globalipapp
66 66 from IPython.testing.plugin.ipdoctest import IPythonDoctest
67 67 from IPython.external.decorators import KnownFailure, knownfailureif
68 68
69 69 pjoin = path.join
70 70
71 71
72 72 #-----------------------------------------------------------------------------
73 73 # Globals
74 74 #-----------------------------------------------------------------------------
75 75
76 76
77 77 #-----------------------------------------------------------------------------
78 78 # Warnings control
79 79 #-----------------------------------------------------------------------------
80 80
81 81 # Twisted generates annoying warnings with Python 2.6, as will do other code
82 82 # that imports 'sets' as of today
83 83 warnings.filterwarnings('ignore', 'the sets module is deprecated',
84 84 DeprecationWarning )
85 85
86 86 # This one also comes from Twisted
87 87 warnings.filterwarnings('ignore', 'the sha module is deprecated',
88 88 DeprecationWarning)
89 89
90 90 # Wx on Fedora11 spits these out
91 91 warnings.filterwarnings('ignore', 'wxPython/wxWidgets release number mismatch',
92 92 UserWarning)
93 93
94 94 # ------------------------------------------------------------------------------
95 95 # Monkeypatch Xunit to count known failures as skipped.
96 96 # ------------------------------------------------------------------------------
97 97 def monkeypatch_xunit():
98 98 try:
99 99 knownfailureif(True)(lambda: None)()
100 100 except Exception as e:
101 101 KnownFailureTest = type(e)
102 102
103 103 def addError(self, test, err, capt=None):
104 104 if issubclass(err[0], KnownFailureTest):
105 105 err = (SkipTest,) + err[1:]
106 106 return self.orig_addError(test, err, capt)
107 107
108 108 Xunit.orig_addError = Xunit.addError
109 109 Xunit.addError = addError
110 110
111 111 #-----------------------------------------------------------------------------
112 112 # Logic for skipping doctests
113 113 #-----------------------------------------------------------------------------
114 114 def extract_version(mod):
115 115 return mod.__version__
116 116
117 117 def test_for(item, min_version=None, callback=extract_version):
118 118 """Test to see if item is importable, and optionally check against a minimum
119 119 version.
120 120
121 121 If min_version is given, the default behavior is to check against the
122 122 `__version__` attribute of the item, but specifying `callback` allows you to
123 123 extract the value you are interested in. e.g::
124 124
125 125 In [1]: import sys
126 126
127 127 In [2]: from IPython.testing.iptest import test_for
128 128
129 129 In [3]: test_for('sys', (2,6), callback=lambda sys: sys.version_info)
130 130 Out[3]: True
131 131
132 132 """
133 133 try:
134 134 check = import_item(item)
135 135 except (ImportError, RuntimeError):
136 136 # GTK reports Runtime error if it can't be initialized even if it's
137 137 # importable.
138 138 return False
139 139 else:
140 140 if min_version:
141 141 if callback:
142 142 # extra processing step to get version to compare
143 143 check = callback(check)
144 144
145 145 return check >= min_version
146 146 else:
147 147 return True
148 148
149 149 # Global dict where we can store information on what we have and what we don't
150 150 # have available at test run time
151 151 have = {}
152 152
153 153 have['curses'] = test_for('_curses')
154 154 have['matplotlib'] = test_for('matplotlib')
155 155 have['numpy'] = test_for('numpy')
156 156 have['pexpect'] = test_for('IPython.external.pexpect')
157 157 have['pymongo'] = test_for('pymongo')
158 158 have['pygments'] = test_for('pygments')
159 159 have['qt'] = test_for('IPython.external.qt')
160 160 have['rpy2'] = test_for('rpy2')
161 161 have['sqlite3'] = test_for('sqlite3')
162 162 have['cython'] = test_for('Cython')
163 163 have['oct2py'] = test_for('oct2py')
164 164 have['tornado'] = test_for('tornado.version_info', (2,1,0), callback=None)
165 165 have['wx'] = test_for('wx')
166 166 have['wx.aui'] = test_for('wx.aui')
167 167 have['azure'] = test_for('azure')
168 168
169 169 if os.name == 'nt':
170 170 min_zmq = (2,1,7)
171 171 else:
172 172 min_zmq = (2,1,4)
173 173
174 174 def version_tuple(mod):
175 175 "turn '2.1.9' into (2,1,9), and '2.1dev' into (2,1,999)"
176 176 # turn 'dev' into 999, because Python3 rejects str-int comparisons
177 177 vs = mod.__version__.replace('dev', '.999')
178 178 tup = tuple([int(v) for v in vs.split('.') ])
179 179 return tup
180 180
181 181 have['zmq'] = test_for('zmq', min_zmq, version_tuple)
182 182
183 183 #-----------------------------------------------------------------------------
184 184 # Functions and classes
185 185 #-----------------------------------------------------------------------------
186 186
187 187 def report():
188 188 """Return a string with a summary report of test-related variables."""
189 189
190 190 out = [ sys_info(), '\n']
191 191
192 192 avail = []
193 193 not_avail = []
194 194
195 195 for k, is_avail in have.items():
196 196 if is_avail:
197 197 avail.append(k)
198 198 else:
199 199 not_avail.append(k)
200 200
201 201 if avail:
202 202 out.append('\nTools and libraries available at test time:\n')
203 203 avail.sort()
204 204 out.append(' ' + ' '.join(avail)+'\n')
205 205
206 206 if not_avail:
207 207 out.append('\nTools and libraries NOT available at test time:\n')
208 208 not_avail.sort()
209 209 out.append(' ' + ' '.join(not_avail)+'\n')
210 210
211 211 return ''.join(out)
212 212
213 213
214 214 def make_exclude():
215 215 """Make patterns of modules and packages to exclude from testing.
216 216
217 217 For the IPythonDoctest plugin, we need to exclude certain patterns that
218 218 cause testing problems. We should strive to minimize the number of
219 219 skipped modules, since this means untested code.
220 220
221 221 These modules and packages will NOT get scanned by nose at all for tests.
222 222 """
223 223 # Simple utility to make IPython paths more readably, we need a lot of
224 224 # these below
225 225 ipjoin = lambda *paths: pjoin('IPython', *paths)
226 226
227 227 exclusions = [ipjoin('external'),
228 228 ipjoin('quarantine'),
229 229 ipjoin('deathrow'),
230 230 # This guy is probably attic material
231 231 ipjoin('testing', 'mkdoctests'),
232 232 # Testing inputhook will need a lot of thought, to figure out
233 233 # how to have tests that don't lock up with the gui event
234 234 # loops in the picture
235 235 ipjoin('lib', 'inputhook'),
236 236 # Config files aren't really importable stand-alone
237 237 ipjoin('config', 'profile'),
238 238 # The notebook 'static' directory contains JS, css and other
239 239 # files for web serving. Occasionally projects may put a .py
240 240 # file in there (MathJax ships a conf.py), so we might as
241 241 # well play it safe and skip the whole thing.
242 242 ipjoin('frontend', 'html', 'notebook', 'static')
243 243 ]
244 244 if not have['sqlite3']:
245 245 exclusions.append(ipjoin('core', 'tests', 'test_history'))
246 246 exclusions.append(ipjoin('core', 'history'))
247 247 if not have['wx']:
248 248 exclusions.append(ipjoin('lib', 'inputhookwx'))
249 249
250 250 # FIXME: temporarily disable autoreload tests, as they can produce
251 251 # spurious failures in subsequent tests (cythonmagic).
252 252 exclusions.append(ipjoin('extensions', 'autoreload'))
253 253 exclusions.append(ipjoin('extensions', 'tests', 'test_autoreload'))
254 254
255 255 # We do this unconditionally, so that the test suite doesn't import
256 256 # gtk, changing the default encoding and masking some unicode bugs.
257 257 exclusions.append(ipjoin('lib', 'inputhookgtk'))
258 258 exclusions.append(ipjoin('zmq', 'gui', 'gtkembed'))
259 259
260 260 # These have to be skipped on win32 because the use echo, rm, cd, etc.
261 261 # See ticket https://github.com/ipython/ipython/issues/87
262 262 if sys.platform == 'win32':
263 263 exclusions.append(ipjoin('testing', 'plugin', 'test_exampleip'))
264 264 exclusions.append(ipjoin('testing', 'plugin', 'dtexample'))
265 265
266 266 if not have['pexpect']:
267 267 exclusions.extend([ipjoin('lib', 'irunner'),
268 268 ipjoin('lib', 'tests', 'test_irunner'),
269 269 ipjoin('frontend', 'terminal', 'console'),
270 270 ])
271 271
272 272 if not have['zmq']:
273 273 exclusions.append(ipjoin('zmq'))
274 274 exclusions.append(ipjoin('frontend', 'qt'))
275 275 exclusions.append(ipjoin('frontend', 'html'))
276 276 exclusions.append(ipjoin('frontend', 'consoleapp.py'))
277 277 exclusions.append(ipjoin('frontend', 'terminal', 'console'))
278 278 exclusions.append(ipjoin('parallel'))
279 279 elif not have['qt'] or not have['pygments']:
280 280 exclusions.append(ipjoin('frontend', 'qt'))
281 281
282 282 if not have['pymongo']:
283 283 exclusions.append(ipjoin('parallel', 'controller', 'mongodb'))
284 284 exclusions.append(ipjoin('parallel', 'tests', 'test_mongodb'))
285 285
286 286 if not have['matplotlib']:
287 287 exclusions.extend([ipjoin('core', 'pylabtools'),
288 288 ipjoin('core', 'tests', 'test_pylabtools'),
289 289 ipjoin('zmq', 'pylab'),
290 290 ])
291 291
292 292 if not have['cython']:
293 293 exclusions.extend([ipjoin('extensions', 'cythonmagic')])
294 294 exclusions.extend([ipjoin('extensions', 'tests', 'test_cythonmagic')])
295 295
296 296 if not have['oct2py']:
297 297 exclusions.extend([ipjoin('extensions', 'octavemagic')])
298 298 exclusions.extend([ipjoin('extensions', 'tests', 'test_octavemagic')])
299 299
300 300 if not have['tornado']:
301 301 exclusions.append(ipjoin('frontend', 'html'))
302 302
303 303 if not have['rpy2'] or not have['numpy']:
304 304 exclusions.append(ipjoin('extensions', 'rmagic'))
305 305 exclusions.append(ipjoin('extensions', 'tests', 'test_rmagic'))
306 306
307 307 if not have['azure']:
308 308 exclusions.append(ipjoin('frontend', 'html', 'notebook', 'azurenbmanager'))
309 309
310 310 # This is needed for the reg-exp to match on win32 in the ipdoctest plugin.
311 311 if sys.platform == 'win32':
312 312 exclusions = [s.replace('\\','\\\\') for s in exclusions]
313 313
314 314 # check for any exclusions that don't seem to exist:
315 315 parent, _ = os.path.split(get_ipython_package_dir())
316 316 for exclusion in exclusions:
317 317 if exclusion.endswith(('deathrow', 'quarantine')):
318 318 # ignore deathrow/quarantine, which exist in dev, but not install
319 319 continue
320 320 fullpath = pjoin(parent, exclusion)
321 321 if not os.path.exists(fullpath) and not glob.glob(fullpath + '.*'):
322 warn("Excluding nonexistent file: %r\n" % exclusion)
322 warn("Excluding nonexistent file: %r" % exclusion)
323 323
324 324 return exclusions
325 325
326 326
327 327 class IPTester(object):
328 328 """Call that calls iptest or trial in a subprocess.
329 329 """
330 330 #: string, name of test runner that will be called
331 331 runner = None
332 332 #: list, parameters for test runner
333 333 params = None
334 334 #: list, arguments of system call to be made to call test runner
335 335 call_args = None
336 336 #: list, subprocesses we start (for cleanup)
337 337 processes = None
338 338 #: str, coverage xml output file
339 339 coverage_xml = None
340 340
341 341 def __init__(self, runner='iptest', params=None):
342 342 """Create new test runner."""
343 343 p = os.path
344 344 if runner == 'iptest':
345 345 iptest_app = get_ipython_module_path('IPython.testing.iptest')
346 346 self.runner = pycmd2argv(iptest_app) + sys.argv[1:]
347 347 else:
348 348 raise Exception('Not a valid test runner: %s' % repr(runner))
349 349 if params is None:
350 350 params = []
351 351 if isinstance(params, str):
352 352 params = [params]
353 353 self.params = params
354 354
355 355 # Assemble call
356 356 self.call_args = self.runner+self.params
357 357
358 358 # Find the section we're testing (IPython.foo)
359 359 for sect in self.params:
360 360 if sect.startswith('IPython'): break
361 361 else:
362 362 raise ValueError("Section not found", self.params)
363 363
364 364 if '--with-xunit' in self.call_args:
365 365
366 366 self.call_args.append('--xunit-file')
367 367 # FIXME: when Windows uses subprocess.call, these extra quotes are unnecessary:
368 368 xunit_file = path.abspath(sect+'.xunit.xml')
369 369 if sys.platform == 'win32':
370 370 xunit_file = '"%s"' % xunit_file
371 371 self.call_args.append(xunit_file)
372 372
373 373 if '--with-xml-coverage' in self.call_args:
374 374 self.coverage_xml = path.abspath(sect+".coverage.xml")
375 375 self.call_args.remove('--with-xml-coverage')
376 376 self.call_args = ["coverage", "run", "--source="+sect] + self.call_args[1:]
377 377
378 378 # Store anything we start to clean up on deletion
379 379 self.processes = []
380 380
381 381 def _run_cmd(self):
382 382 with TemporaryDirectory() as IPYTHONDIR:
383 383 env = os.environ.copy()
384 384 env['IPYTHONDIR'] = IPYTHONDIR
385 385 # print >> sys.stderr, '*** CMD:', ' '.join(self.call_args) # dbg
386 386 subp = subprocess.Popen(self.call_args, env=env)
387 387 self.processes.append(subp)
388 388 # If this fails, the process will be left in self.processes and
389 389 # cleaned up later, but if the wait call succeeds, then we can
390 390 # clear the stored process.
391 391 retcode = subp.wait()
392 392 self.processes.pop()
393 393 return retcode
394 394
395 395 def run(self):
396 396 """Run the stored commands"""
397 397 try:
398 398 retcode = self._run_cmd()
399 399 except KeyboardInterrupt:
400 400 return -signal.SIGINT
401 401 except:
402 402 import traceback
403 403 traceback.print_exc()
404 404 return 1 # signal failure
405 405
406 406 if self.coverage_xml:
407 407 subprocess.call(["coverage", "xml", "-o", self.coverage_xml])
408 408 return retcode
409 409
410 410 def __del__(self):
411 411 """Cleanup on exit by killing any leftover processes."""
412 412 for subp in self.processes:
413 413 if subp.poll() is not None:
414 414 continue # process is already dead
415 415
416 416 try:
417 417 print('Cleaning up stale PID: %d' % subp.pid)
418 418 subp.kill()
419 419 except: # (OSError, WindowsError) ?
420 420 # This is just a best effort, if we fail or the process was
421 421 # really gone, ignore it.
422 422 pass
423 423 else:
424 424 for i in range(10):
425 425 if subp.poll() is None:
426 426 time.sleep(0.1)
427 427 else:
428 428 break
429 429
430 430 if subp.poll() is None:
431 431 # The process did not die...
432 432 print('... failed. Manual cleanup may be required.')
433 433
434 434 def make_runners(inc_slow=False):
435 435 """Define the top-level packages that need to be tested.
436 436 """
437 437
438 438 # Packages to be tested via nose, that only depend on the stdlib
439 439 nose_pkg_names = ['config', 'core', 'extensions', 'frontend', 'lib',
440 440 'testing', 'utils', 'nbformat' ]
441 441
442 442 if have['zmq']:
443 443 nose_pkg_names.append('zmq')
444 444 if inc_slow:
445 445 nose_pkg_names.append('parallel')
446 446
447 447 # For debugging this code, only load quick stuff
448 448 #nose_pkg_names = ['core', 'extensions'] # dbg
449 449
450 450 # Make fully qualified package names prepending 'IPython.' to our name lists
451 451 nose_packages = ['IPython.%s' % m for m in nose_pkg_names ]
452 452
453 453 # Make runners
454 454 runners = [ (v, IPTester('iptest', params=v)) for v in nose_packages ]
455 455
456 456 return runners
457 457
458 458
459 459 def run_iptest():
460 460 """Run the IPython test suite using nose.
461 461
462 462 This function is called when this script is **not** called with the form
463 463 `iptest all`. It simply calls nose with appropriate command line flags
464 464 and accepts all of the standard nose arguments.
465 465 """
466 466 # Apply our monkeypatch to Xunit
467 467 if '--with-xunit' in sys.argv and not hasattr(Xunit, 'orig_addError'):
468 468 monkeypatch_xunit()
469 469
470 470 warnings.filterwarnings('ignore',
471 471 'This will be removed soon. Use IPython.testing.util instead')
472 472
473 473 argv = sys.argv + [ '--detailed-errors', # extra info in tracebacks
474 474
475 475 '--with-ipdoctest',
476 476 '--ipdoctest-tests','--ipdoctest-extension=txt',
477 477
478 478 # We add --exe because of setuptools' imbecility (it
479 479 # blindly does chmod +x on ALL files). Nose does the
480 480 # right thing and it tries to avoid executables,
481 481 # setuptools unfortunately forces our hand here. This
482 482 # has been discussed on the distutils list and the
483 483 # setuptools devs refuse to fix this problem!
484 484 '--exe',
485 485 ]
486 486 if '-a' not in argv and '-A' not in argv:
487 487 argv = argv + ['-a', '!crash']
488 488
489 489 if nose.__version__ >= '0.11':
490 490 # I don't fully understand why we need this one, but depending on what
491 491 # directory the test suite is run from, if we don't give it, 0 tests
492 492 # get run. Specifically, if the test suite is run from the source dir
493 493 # with an argument (like 'iptest.py IPython.core', 0 tests are run,
494 494 # even if the same call done in this directory works fine). It appears
495 495 # that if the requested package is in the current dir, nose bails early
496 496 # by default. Since it's otherwise harmless, leave it in by default
497 497 # for nose >= 0.11, though unfortunately nose 0.10 doesn't support it.
498 498 argv.append('--traverse-namespace')
499 499
500 500 # use our plugin for doctesting. It will remove the standard doctest plugin
501 501 # if it finds it enabled
502 502 plugins = [IPythonDoctest(make_exclude()), KnownFailure()]
503 503 # We need a global ipython running in this process
504 504 globalipapp.start_ipython()
505 505 # Now nose can run
506 506 TestProgram(argv=argv, addplugins=plugins)
507 507
508 508
509 509 def run_iptestall(inc_slow=False):
510 510 """Run the entire IPython test suite by calling nose and trial.
511 511
512 512 This function constructs :class:`IPTester` instances for all IPython
513 513 modules and package and then runs each of them. This causes the modules
514 514 and packages of IPython to be tested each in their own subprocess using
515 515 nose.
516 516
517 517 Parameters
518 518 ----------
519 519
520 520 inc_slow : bool, optional
521 521 Include slow tests, like IPython.parallel. By default, these tests aren't
522 522 run.
523 523 """
524 524
525 525 runners = make_runners(inc_slow=inc_slow)
526 526
527 527 # Run the test runners in a temporary dir so we can nuke it when finished
528 528 # to clean up any junk files left over by accident. This also makes it
529 529 # robust against being run in non-writeable directories by mistake, as the
530 530 # temp dir will always be user-writeable.
531 531 curdir = os.getcwdu()
532 532 testdir = tempfile.gettempdir()
533 533 os.chdir(testdir)
534 534
535 535 # Run all test runners, tracking execution time
536 536 failed = []
537 537 t_start = time.time()
538 538 try:
539 539 for (name, runner) in runners:
540 540 print('*'*70)
541 541 print('IPython test group:',name)
542 542 res = runner.run()
543 543 if res:
544 544 failed.append( (name, runner) )
545 545 if res == -signal.SIGINT:
546 546 print("Interrupted")
547 547 break
548 548 finally:
549 549 os.chdir(curdir)
550 550 t_end = time.time()
551 551 t_tests = t_end - t_start
552 552 nrunners = len(runners)
553 553 nfail = len(failed)
554 554 # summarize results
555 555 print()
556 556 print('*'*70)
557 557 print('Test suite completed for system with the following information:')
558 558 print(report())
559 559 print('Ran %s test groups in %.3fs' % (nrunners, t_tests))
560 560 print()
561 561 print('Status:')
562 562 if not failed:
563 563 print('OK')
564 564 else:
565 565 # If anything went wrong, point out what command to rerun manually to
566 566 # see the actual errors and individual summary
567 567 print('ERROR - %s out of %s test groups failed.' % (nfail, nrunners))
568 568 for name, failed_runner in failed:
569 569 print('-'*40)
570 570 print('Runner failed:',name)
571 571 print('You may wish to rerun this one individually, with:')
572 572 failed_call_args = [py3compat.cast_unicode(x) for x in failed_runner.call_args]
573 573 print(u' '.join(failed_call_args))
574 574 print()
575 575 # Ensure that our exit code indicates failure
576 576 sys.exit(1)
577 577
578 578
579 579 def main():
580 580 for arg in sys.argv[1:]:
581 581 if arg.startswith('IPython'):
582 582 # This is in-process
583 583 run_iptest()
584 584 else:
585 585 if "--all" in sys.argv:
586 586 sys.argv.remove("--all")
587 587 inc_slow = True
588 588 else:
589 589 inc_slow = False
590 590 # This starts subprocesses
591 591 run_iptestall(inc_slow=inc_slow)
592 592
593 593
594 594 if __name__ == '__main__':
595 595 main()
@@ -1,167 +1,167 b''
1 1 # encoding: utf-8
2 2 """
3 3 Older utilities that are not being used.
4 4
5 5 WARNING: IF YOU NEED TO USE ONE OF THESE FUNCTIONS, PLEASE FIRST MOVE IT
6 6 TO ANOTHER APPROPRIATE MODULE IN IPython.utils.
7 7 """
8 8
9 9 #-----------------------------------------------------------------------------
10 10 # Copyright (C) 2008-2011 The IPython Development Team
11 11 #
12 12 # Distributed under the terms of the BSD License. The full license is in
13 13 # the file COPYING, distributed as part of this software.
14 14 #-----------------------------------------------------------------------------
15 15
16 16 #-----------------------------------------------------------------------------
17 17 # Imports
18 18 #-----------------------------------------------------------------------------
19 19
20 20 import sys
21 21 import warnings
22 22
23 23 from IPython.utils.warn import warn
24 24
25 25 #-----------------------------------------------------------------------------
26 26 # Code
27 27 #-----------------------------------------------------------------------------
28 28
29 29
30 30 def mutex_opts(dict,ex_op):
31 31 """Check for presence of mutually exclusive keys in a dict.
32 32
33 33 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
34 34 for op1,op2 in ex_op:
35 35 if op1 in dict and op2 in dict:
36 36 raise ValueError('\n*** ERROR in Arguments *** '\
37 37 'Options '+op1+' and '+op2+' are mutually exclusive.')
38 38
39 39
40 40 class EvalDict:
41 41 """
42 42 Emulate a dict which evaluates its contents in the caller's frame.
43 43
44 44 Usage:
45 45 >>> number = 19
46 46
47 47 >>> text = "python"
48 48
49 49 >>> print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
50 50 Python 2.1 rules!
51 51 """
52 52
53 53 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
54 54 # modified (shorter) version of:
55 55 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
56 56 # Skip Montanaro (skip@pobox.com).
57 57
58 58 def __getitem__(self, name):
59 59 frame = sys._getframe(1)
60 60 return eval(name, frame.f_globals, frame.f_locals)
61 61
62 62 EvalString = EvalDict # for backwards compatibility
63 63
64 64
65 65 def all_belong(candidates,checklist):
66 66 """Check whether a list of items ALL appear in a given list of options.
67 67
68 68 Returns a single 1 or 0 value."""
69 69
70 70 return 1-(0 in [x in checklist for x in candidates])
71 71
72 72
73 73 def belong(candidates,checklist):
74 74 """Check whether a list of items appear in a given list of options.
75 75
76 76 Returns a list of 1 and 0, one for each candidate given."""
77 77
78 78 return [x in checklist for x in candidates]
79 79
80 80
81 81 def with_obj(object, **args):
82 82 """Set multiple attributes for an object, similar to Pascal's with.
83 83
84 84 Example:
85 85 with_obj(jim,
86 86 born = 1960,
87 87 haircolour = 'Brown',
88 88 eyecolour = 'Green')
89 89
90 90 Credit: Greg Ewing, in
91 91 http://mail.python.org/pipermail/python-list/2001-May/040703.html.
92 92
93 93 NOTE: up until IPython 0.7.2, this was called simply 'with', but 'with'
94 94 has become a keyword for Python 2.5, so we had to rename it."""
95 95
96 96 object.__dict__.update(args)
97 97
98 98
99 99 def map_method(method,object_list,*argseq,**kw):
100 100 """map_method(method,object_list,*args,**kw) -> list
101 101
102 102 Return a list of the results of applying the methods to the items of the
103 103 argument sequence(s). If more than one sequence is given, the method is
104 104 called with an argument list consisting of the corresponding item of each
105 105 sequence. All sequences must be of the same length.
106 106
107 107 Keyword arguments are passed verbatim to all objects called.
108 108
109 109 This is Python code, so it's not nearly as fast as the builtin map()."""
110 110
111 111 out_list = []
112 112 idx = 0
113 113 for object in object_list:
114 114 try:
115 115 handler = getattr(object, method)
116 116 except AttributeError:
117 117 out_list.append(None)
118 118 else:
119 119 if argseq:
120 120 args = map(lambda lst:lst[idx],argseq)
121 121 #print 'ob',object,'hand',handler,'ar',args # dbg
122 122 out_list.append(handler(args,**kw))
123 123 else:
124 124 out_list.append(handler(**kw))
125 125 idx += 1
126 126 return out_list
127 127
128 128
129 129 def import_fail_info(mod_name,fns=None):
130 130 """Inform load failure for a module."""
131 131
132 132 if fns == None:
133 warn("Loading of %s failed.\n" % (mod_name,))
133 warn("Loading of %s failed." % (mod_name,))
134 134 else:
135 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
135 warn("Loading of %s from %s failed." % (fns,mod_name))
136 136
137 137
138 138 class NotGiven: pass
139 139
140 140 def popkey(dct,key,default=NotGiven):
141 141 """Return dct[key] and delete dct[key].
142 142
143 143 If default is given, return it if dct[key] doesn't exist, otherwise raise
144 144 KeyError. """
145 145
146 146 try:
147 147 val = dct[key]
148 148 except KeyError:
149 149 if default is NotGiven:
150 150 raise
151 151 else:
152 152 return default
153 153 else:
154 154 del dct[key]
155 155 return val
156 156
157 157
158 158 def wrap_deprecated(func, suggest = '<nothing>'):
159 159 def newFunc(*args, **kwargs):
160 160 warnings.warn("Call to deprecated function %s, use %s instead" %
161 161 ( func.__name__, suggest),
162 162 category=DeprecationWarning,
163 163 stacklevel = 2)
164 164 return func(*args, **kwargs)
165 165 return newFunc
166 166
167 167
@@ -1,67 +1,67 b''
1 1 # encoding: utf-8
2 2 """
3 3 Utilities for warnings. Shoudn't we just use the built in warnings module.
4 4 """
5 5
6 6 #-----------------------------------------------------------------------------
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 from __future__ import print_function
17 17
18 18 import sys
19 19
20 20 from IPython.utils import io
21 21
22 22 #-----------------------------------------------------------------------------
23 23 # Code
24 24 #-----------------------------------------------------------------------------
25 25
26 26 def warn(msg,level=2,exit_val=1):
27 27 """Standard warning printer. Gives formatting consistency.
28 28
29 29 Output is sent to io.stderr (sys.stderr by default).
30 30
31 31 Options:
32 32
33 33 -level(2): allows finer control:
34 34 0 -> Do nothing, dummy function.
35 35 1 -> Print message.
36 36 2 -> Print 'WARNING:' + message. (Default level).
37 37 3 -> Print 'ERROR:' + message.
38 38 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
39 39
40 40 -exit_val (1): exit value returned by sys.exit() for a level 4
41 41 warning. Ignored for all other levels."""
42 42
43 43 if level>0:
44 44 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
45 io.stderr.write('%s%s' % (header[level],msg))
45 print(header[level], msg, sep='', file=io.stderr)
46 46 if level == 4:
47 47 print('Exiting.\n', file=io.stderr)
48 48 sys.exit(exit_val)
49 49
50 50
51 51 def info(msg):
52 52 """Equivalent to warn(msg,level=1)."""
53 53
54 54 warn(msg,level=1)
55 55
56 56
57 57 def error(msg):
58 58 """Equivalent to warn(msg,level=3)."""
59 59
60 60 warn(msg,level=3)
61 61
62 62
63 63 def fatal(msg,exit_val=1):
64 64 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
65 65
66 66 warn(msg,exit_val=exit_val,level=4)
67 67
General Comments 0
You need to be logged in to leave comments. Login now