##// 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 """ History related magics and functionality """
1 """ History related magics and functionality """
2 #-----------------------------------------------------------------------------
2 #-----------------------------------------------------------------------------
3 # Copyright (C) 2010-2011 The IPython Development Team.
3 # Copyright (C) 2010-2011 The IPython Development Team.
4 #
4 #
5 # Distributed under the terms of the BSD License.
5 # Distributed under the terms of the BSD License.
6 #
6 #
7 # The full license is in the file COPYING.txt, distributed with this software.
7 # The full license is in the file COPYING.txt, distributed with this software.
8 #-----------------------------------------------------------------------------
8 #-----------------------------------------------------------------------------
9
9
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11 # Imports
11 # Imports
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 from __future__ import print_function
13 from __future__ import print_function
14
14
15 # Stdlib imports
15 # Stdlib imports
16 import atexit
16 import atexit
17 import datetime
17 import datetime
18 import os
18 import os
19 import re
19 import re
20 try:
20 try:
21 import sqlite3
21 import sqlite3
22 except ImportError:
22 except ImportError:
23 sqlite3 = None
23 sqlite3 = None
24 import threading
24 import threading
25
25
26 # Our own packages
26 # Our own packages
27 from IPython.config.configurable import Configurable
27 from IPython.config.configurable import Configurable
28 from IPython.external.decorator import decorator
28 from IPython.external.decorator import decorator
29 from IPython.utils.path import locate_profile
29 from IPython.utils.path import locate_profile
30 from IPython.utils.traitlets import (
30 from IPython.utils.traitlets import (
31 Any, Bool, Dict, Instance, Integer, List, Unicode, TraitError,
31 Any, Bool, Dict, Instance, Integer, List, Unicode, TraitError,
32 )
32 )
33 from IPython.utils.warn import warn
33 from IPython.utils.warn import warn
34
34
35 #-----------------------------------------------------------------------------
35 #-----------------------------------------------------------------------------
36 # Classes and functions
36 # Classes and functions
37 #-----------------------------------------------------------------------------
37 #-----------------------------------------------------------------------------
38
38
39 class DummyDB(object):
39 class DummyDB(object):
40 """Dummy DB that will act as a black hole for history.
40 """Dummy DB that will act as a black hole for history.
41
41
42 Only used in the absence of sqlite"""
42 Only used in the absence of sqlite"""
43 def execute(*args, **kwargs):
43 def execute(*args, **kwargs):
44 return []
44 return []
45
45
46 def commit(self, *args, **kwargs):
46 def commit(self, *args, **kwargs):
47 pass
47 pass
48
48
49 def __enter__(self, *args, **kwargs):
49 def __enter__(self, *args, **kwargs):
50 pass
50 pass
51
51
52 def __exit__(self, *args, **kwargs):
52 def __exit__(self, *args, **kwargs):
53 pass
53 pass
54
54
55
55
56 @decorator
56 @decorator
57 def needs_sqlite(f, self, *a, **kw):
57 def needs_sqlite(f, self, *a, **kw):
58 """return an empty list in the absence of sqlite"""
58 """return an empty list in the absence of sqlite"""
59 if sqlite3 is None or not self.enabled:
59 if sqlite3 is None or not self.enabled:
60 return []
60 return []
61 else:
61 else:
62 return f(self, *a, **kw)
62 return f(self, *a, **kw)
63
63
64
64
65 if sqlite3 is not None:
65 if sqlite3 is not None:
66 DatabaseError = sqlite3.DatabaseError
66 DatabaseError = sqlite3.DatabaseError
67 else:
67 else:
68 class DatabaseError(Exception):
68 class DatabaseError(Exception):
69 "Dummy exception when sqlite could not be imported. Should never occur."
69 "Dummy exception when sqlite could not be imported. Should never occur."
70
70
71 @decorator
71 @decorator
72 def catch_corrupt_db(f, self, *a, **kw):
72 def catch_corrupt_db(f, self, *a, **kw):
73 """A decorator which wraps HistoryAccessor method calls to catch errors from
73 """A decorator which wraps HistoryAccessor method calls to catch errors from
74 a corrupt SQLite database, move the old database out of the way, and create
74 a corrupt SQLite database, move the old database out of the way, and create
75 a new one.
75 a new one.
76 """
76 """
77 try:
77 try:
78 return f(self, *a, **kw)
78 return f(self, *a, **kw)
79 except DatabaseError:
79 except DatabaseError:
80 if os.path.isfile(self.hist_file):
80 if os.path.isfile(self.hist_file):
81 # Try to move the file out of the way
81 # Try to move the file out of the way
82 base,ext = os.path.splitext(self.hist_file)
82 base,ext = os.path.splitext(self.hist_file)
83 newpath = base + '-corrupt' + ext
83 newpath = base + '-corrupt' + ext
84 os.rename(self.hist_file, newpath)
84 os.rename(self.hist_file, newpath)
85 self.init_db()
85 self.init_db()
86 print("ERROR! History file wasn't a valid SQLite database.",
86 print("ERROR! History file wasn't a valid SQLite database.",
87 "It was moved to %s" % newpath, "and a new file created.")
87 "It was moved to %s" % newpath, "and a new file created.")
88 return []
88 return []
89
89
90 else:
90 else:
91 # The hist_file is probably :memory: or something else.
91 # The hist_file is probably :memory: or something else.
92 raise
92 raise
93
93
94
94
95
95
96 class HistoryAccessor(Configurable):
96 class HistoryAccessor(Configurable):
97 """Access the history database without adding to it.
97 """Access the history database without adding to it.
98
98
99 This is intended for use by standalone history tools. IPython shells use
99 This is intended for use by standalone history tools. IPython shells use
100 HistoryManager, below, which is a subclass of this."""
100 HistoryManager, below, which is a subclass of this."""
101
101
102 # String holding the path to the history file
102 # String holding the path to the history file
103 hist_file = Unicode(config=True,
103 hist_file = Unicode(config=True,
104 help="""Path to file to use for SQLite history database.
104 help="""Path to file to use for SQLite history database.
105
105
106 By default, IPython will put the history database in the IPython
106 By default, IPython will put the history database in the IPython
107 profile directory. If you would rather share one history among
107 profile directory. If you would rather share one history among
108 profiles, you can set this value in each, so that they are consistent.
108 profiles, you can set this value in each, so that they are consistent.
109
109
110 Due to an issue with fcntl, SQLite is known to misbehave on some NFS
110 Due to an issue with fcntl, SQLite is known to misbehave on some NFS
111 mounts. If you see IPython hanging, try setting this to something on a
111 mounts. If you see IPython hanging, try setting this to something on a
112 local disk, e.g::
112 local disk, e.g::
113
113
114 ipython --HistoryManager.hist_file=/tmp/ipython_hist.sqlite
114 ipython --HistoryManager.hist_file=/tmp/ipython_hist.sqlite
115
115
116 """)
116 """)
117
117
118 enabled = Bool(True, config=True,
118 enabled = Bool(True, config=True,
119 help="""enable the SQLite history
119 help="""enable the SQLite history
120
120
121 set enabled=False to disable the SQLite history,
121 set enabled=False to disable the SQLite history,
122 in which case there will be no stored history, no SQLite connection,
122 in which case there will be no stored history, no SQLite connection,
123 and no background saving thread. This may be necessary in some
123 and no background saving thread. This may be necessary in some
124 threaded environments where IPython is embedded.
124 threaded environments where IPython is embedded.
125 """
125 """
126 )
126 )
127
127
128 connection_options = Dict(config=True,
128 connection_options = Dict(config=True,
129 help="""Options for configuring the SQLite connection
129 help="""Options for configuring the SQLite connection
130
130
131 These options are passed as keyword args to sqlite3.connect
131 These options are passed as keyword args to sqlite3.connect
132 when establishing database conenctions.
132 when establishing database conenctions.
133 """
133 """
134 )
134 )
135
135
136 # The SQLite database
136 # The SQLite database
137 db = Any()
137 db = Any()
138 def _db_changed(self, name, old, new):
138 def _db_changed(self, name, old, new):
139 """validate the db, since it can be an Instance of two different types"""
139 """validate the db, since it can be an Instance of two different types"""
140 connection_types = (DummyDB,)
140 connection_types = (DummyDB,)
141 if sqlite3 is not None:
141 if sqlite3 is not None:
142 connection_types = (DummyDB, sqlite3.Connection)
142 connection_types = (DummyDB, sqlite3.Connection)
143 if not isinstance(new, connection_types):
143 if not isinstance(new, connection_types):
144 msg = "%s.db must be sqlite3 Connection or DummyDB, not %r" % \
144 msg = "%s.db must be sqlite3 Connection or DummyDB, not %r" % \
145 (self.__class__.__name__, new)
145 (self.__class__.__name__, new)
146 raise TraitError(msg)
146 raise TraitError(msg)
147
147
148 def __init__(self, profile='default', hist_file=u'', config=None, **traits):
148 def __init__(self, profile='default', hist_file=u'', config=None, **traits):
149 """Create a new history accessor.
149 """Create a new history accessor.
150
150
151 Parameters
151 Parameters
152 ----------
152 ----------
153 profile : str
153 profile : str
154 The name of the profile from which to open history.
154 The name of the profile from which to open history.
155 hist_file : str
155 hist_file : str
156 Path to an SQLite history database stored by IPython. If specified,
156 Path to an SQLite history database stored by IPython. If specified,
157 hist_file overrides profile.
157 hist_file overrides profile.
158 config :
158 config :
159 Config object. hist_file can also be set through this.
159 Config object. hist_file can also be set through this.
160 """
160 """
161 # We need a pointer back to the shell for various tasks.
161 # We need a pointer back to the shell for various tasks.
162 super(HistoryAccessor, self).__init__(config=config, **traits)
162 super(HistoryAccessor, self).__init__(config=config, **traits)
163 # defer setting hist_file from kwarg until after init,
163 # defer setting hist_file from kwarg until after init,
164 # otherwise the default kwarg value would clobber any value
164 # otherwise the default kwarg value would clobber any value
165 # set by config
165 # set by config
166 if hist_file:
166 if hist_file:
167 self.hist_file = hist_file
167 self.hist_file = hist_file
168
168
169 if self.hist_file == u'':
169 if self.hist_file == u'':
170 # No one has set the hist_file, yet.
170 # No one has set the hist_file, yet.
171 self.hist_file = self._get_hist_file_name(profile)
171 self.hist_file = self._get_hist_file_name(profile)
172
172
173 if sqlite3 is None and self.enabled:
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 self.enabled = False
175 self.enabled = False
176
176
177 self.init_db()
177 self.init_db()
178
178
179 def _get_hist_file_name(self, profile='default'):
179 def _get_hist_file_name(self, profile='default'):
180 """Find the history file for the given profile name.
180 """Find the history file for the given profile name.
181
181
182 This is overridden by the HistoryManager subclass, to use the shell's
182 This is overridden by the HistoryManager subclass, to use the shell's
183 active profile.
183 active profile.
184
184
185 Parameters
185 Parameters
186 ----------
186 ----------
187 profile : str
187 profile : str
188 The name of a profile which has a history file.
188 The name of a profile which has a history file.
189 """
189 """
190 return os.path.join(locate_profile(profile), 'history.sqlite')
190 return os.path.join(locate_profile(profile), 'history.sqlite')
191
191
192 @catch_corrupt_db
192 @catch_corrupt_db
193 def init_db(self):
193 def init_db(self):
194 """Connect to the database, and create tables if necessary."""
194 """Connect to the database, and create tables if necessary."""
195 if not self.enabled:
195 if not self.enabled:
196 self.db = DummyDB()
196 self.db = DummyDB()
197 return
197 return
198
198
199 # use detect_types so that timestamps return datetime objects
199 # use detect_types so that timestamps return datetime objects
200 kwargs = dict(detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
200 kwargs = dict(detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
201 kwargs.update(self.connection_options)
201 kwargs.update(self.connection_options)
202 self.db = sqlite3.connect(self.hist_file, **kwargs)
202 self.db = sqlite3.connect(self.hist_file, **kwargs)
203 self.db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer
203 self.db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer
204 primary key autoincrement, start timestamp,
204 primary key autoincrement, start timestamp,
205 end timestamp, num_cmds integer, remark text)""")
205 end timestamp, num_cmds integer, remark text)""")
206 self.db.execute("""CREATE TABLE IF NOT EXISTS history
206 self.db.execute("""CREATE TABLE IF NOT EXISTS history
207 (session integer, line integer, source text, source_raw text,
207 (session integer, line integer, source text, source_raw text,
208 PRIMARY KEY (session, line))""")
208 PRIMARY KEY (session, line))""")
209 # Output history is optional, but ensure the table's there so it can be
209 # Output history is optional, but ensure the table's there so it can be
210 # enabled later.
210 # enabled later.
211 self.db.execute("""CREATE TABLE IF NOT EXISTS output_history
211 self.db.execute("""CREATE TABLE IF NOT EXISTS output_history
212 (session integer, line integer, output text,
212 (session integer, line integer, output text,
213 PRIMARY KEY (session, line))""")
213 PRIMARY KEY (session, line))""")
214 self.db.commit()
214 self.db.commit()
215
215
216 def writeout_cache(self):
216 def writeout_cache(self):
217 """Overridden by HistoryManager to dump the cache before certain
217 """Overridden by HistoryManager to dump the cache before certain
218 database lookups."""
218 database lookups."""
219 pass
219 pass
220
220
221 ## -------------------------------
221 ## -------------------------------
222 ## Methods for retrieving history:
222 ## Methods for retrieving history:
223 ## -------------------------------
223 ## -------------------------------
224 def _run_sql(self, sql, params, raw=True, output=False):
224 def _run_sql(self, sql, params, raw=True, output=False):
225 """Prepares and runs an SQL query for the history database.
225 """Prepares and runs an SQL query for the history database.
226
226
227 Parameters
227 Parameters
228 ----------
228 ----------
229 sql : str
229 sql : str
230 Any filtering expressions to go after SELECT ... FROM ...
230 Any filtering expressions to go after SELECT ... FROM ...
231 params : tuple
231 params : tuple
232 Parameters passed to the SQL query (to replace "?")
232 Parameters passed to the SQL query (to replace "?")
233 raw, output : bool
233 raw, output : bool
234 See :meth:`get_range`
234 See :meth:`get_range`
235
235
236 Returns
236 Returns
237 -------
237 -------
238 Tuples as :meth:`get_range`
238 Tuples as :meth:`get_range`
239 """
239 """
240 toget = 'source_raw' if raw else 'source'
240 toget = 'source_raw' if raw else 'source'
241 sqlfrom = "history"
241 sqlfrom = "history"
242 if output:
242 if output:
243 sqlfrom = "history LEFT JOIN output_history USING (session, line)"
243 sqlfrom = "history LEFT JOIN output_history USING (session, line)"
244 toget = "history.%s, output_history.output" % toget
244 toget = "history.%s, output_history.output" % toget
245 cur = self.db.execute("SELECT session, line, %s FROM %s " %\
245 cur = self.db.execute("SELECT session, line, %s FROM %s " %\
246 (toget, sqlfrom) + sql, params)
246 (toget, sqlfrom) + sql, params)
247 if output: # Regroup into 3-tuples, and parse JSON
247 if output: # Regroup into 3-tuples, and parse JSON
248 return ((ses, lin, (inp, out)) for ses, lin, inp, out in cur)
248 return ((ses, lin, (inp, out)) for ses, lin, inp, out in cur)
249 return cur
249 return cur
250
250
251 @needs_sqlite
251 @needs_sqlite
252 @catch_corrupt_db
252 @catch_corrupt_db
253 def get_session_info(self, session=0):
253 def get_session_info(self, session=0):
254 """get info about a session
254 """get info about a session
255
255
256 Parameters
256 Parameters
257 ----------
257 ----------
258
258
259 session : int
259 session : int
260 Session number to retrieve. The current session is 0, and negative
260 Session number to retrieve. The current session is 0, and negative
261 numbers count back from current session, so -1 is previous session.
261 numbers count back from current session, so -1 is previous session.
262
262
263 Returns
263 Returns
264 -------
264 -------
265
265
266 (session_id [int], start [datetime], end [datetime], num_cmds [int],
266 (session_id [int], start [datetime], end [datetime], num_cmds [int],
267 remark [unicode])
267 remark [unicode])
268
268
269 Sessions that are running or did not exit cleanly will have `end=None`
269 Sessions that are running or did not exit cleanly will have `end=None`
270 and `num_cmds=None`.
270 and `num_cmds=None`.
271
271
272 """
272 """
273
273
274 if session <= 0:
274 if session <= 0:
275 session += self.session_number
275 session += self.session_number
276
276
277 query = "SELECT * from sessions where session == ?"
277 query = "SELECT * from sessions where session == ?"
278 return self.db.execute(query, (session,)).fetchone()
278 return self.db.execute(query, (session,)).fetchone()
279
279
280 @catch_corrupt_db
280 @catch_corrupt_db
281 def get_tail(self, n=10, raw=True, output=False, include_latest=False):
281 def get_tail(self, n=10, raw=True, output=False, include_latest=False):
282 """Get the last n lines from the history database.
282 """Get the last n lines from the history database.
283
283
284 Parameters
284 Parameters
285 ----------
285 ----------
286 n : int
286 n : int
287 The number of lines to get
287 The number of lines to get
288 raw, output : bool
288 raw, output : bool
289 See :meth:`get_range`
289 See :meth:`get_range`
290 include_latest : bool
290 include_latest : bool
291 If False (default), n+1 lines are fetched, and the latest one
291 If False (default), n+1 lines are fetched, and the latest one
292 is discarded. This is intended to be used where the function
292 is discarded. This is intended to be used where the function
293 is called by a user command, which it should not return.
293 is called by a user command, which it should not return.
294
294
295 Returns
295 Returns
296 -------
296 -------
297 Tuples as :meth:`get_range`
297 Tuples as :meth:`get_range`
298 """
298 """
299 self.writeout_cache()
299 self.writeout_cache()
300 if not include_latest:
300 if not include_latest:
301 n += 1
301 n += 1
302 cur = self._run_sql("ORDER BY session DESC, line DESC LIMIT ?",
302 cur = self._run_sql("ORDER BY session DESC, line DESC LIMIT ?",
303 (n,), raw=raw, output=output)
303 (n,), raw=raw, output=output)
304 if not include_latest:
304 if not include_latest:
305 return reversed(list(cur)[1:])
305 return reversed(list(cur)[1:])
306 return reversed(list(cur))
306 return reversed(list(cur))
307
307
308 @catch_corrupt_db
308 @catch_corrupt_db
309 def search(self, pattern="*", raw=True, search_raw=True,
309 def search(self, pattern="*", raw=True, search_raw=True,
310 output=False, n=None):
310 output=False, n=None):
311 """Search the database using unix glob-style matching (wildcards
311 """Search the database using unix glob-style matching (wildcards
312 * and ?).
312 * and ?).
313
313
314 Parameters
314 Parameters
315 ----------
315 ----------
316 pattern : str
316 pattern : str
317 The wildcarded pattern to match when searching
317 The wildcarded pattern to match when searching
318 search_raw : bool
318 search_raw : bool
319 If True, search the raw input, otherwise, the parsed input
319 If True, search the raw input, otherwise, the parsed input
320 raw, output : bool
320 raw, output : bool
321 See :meth:`get_range`
321 See :meth:`get_range`
322 n : None or int
322 n : None or int
323 If an integer is given, it defines the limit of
323 If an integer is given, it defines the limit of
324 returned entries.
324 returned entries.
325
325
326 Returns
326 Returns
327 -------
327 -------
328 Tuples as :meth:`get_range`
328 Tuples as :meth:`get_range`
329 """
329 """
330 tosearch = "source_raw" if search_raw else "source"
330 tosearch = "source_raw" if search_raw else "source"
331 if output:
331 if output:
332 tosearch = "history." + tosearch
332 tosearch = "history." + tosearch
333 self.writeout_cache()
333 self.writeout_cache()
334 sqlform = "WHERE %s GLOB ?" % tosearch
334 sqlform = "WHERE %s GLOB ?" % tosearch
335 params = (pattern,)
335 params = (pattern,)
336 if n is not None:
336 if n is not None:
337 sqlform += " ORDER BY session DESC, line DESC LIMIT ?"
337 sqlform += " ORDER BY session DESC, line DESC LIMIT ?"
338 params += (n,)
338 params += (n,)
339 cur = self._run_sql(sqlform, params, raw=raw, output=output)
339 cur = self._run_sql(sqlform, params, raw=raw, output=output)
340 if n is not None:
340 if n is not None:
341 return reversed(list(cur))
341 return reversed(list(cur))
342 return cur
342 return cur
343
343
344 @catch_corrupt_db
344 @catch_corrupt_db
345 def get_range(self, session, start=1, stop=None, raw=True,output=False):
345 def get_range(self, session, start=1, stop=None, raw=True,output=False):
346 """Retrieve input by session.
346 """Retrieve input by session.
347
347
348 Parameters
348 Parameters
349 ----------
349 ----------
350 session : int
350 session : int
351 Session number to retrieve.
351 Session number to retrieve.
352 start : int
352 start : int
353 First line to retrieve.
353 First line to retrieve.
354 stop : int
354 stop : int
355 End of line range (excluded from output itself). If None, retrieve
355 End of line range (excluded from output itself). If None, retrieve
356 to the end of the session.
356 to the end of the session.
357 raw : bool
357 raw : bool
358 If True, return untranslated input
358 If True, return untranslated input
359 output : bool
359 output : bool
360 If True, attempt to include output. This will be 'real' Python
360 If True, attempt to include output. This will be 'real' Python
361 objects for the current session, or text reprs from previous
361 objects for the current session, or text reprs from previous
362 sessions if db_log_output was enabled at the time. Where no output
362 sessions if db_log_output was enabled at the time. Where no output
363 is found, None is used.
363 is found, None is used.
364
364
365 Returns
365 Returns
366 -------
366 -------
367 An iterator over the desired lines. Each line is a 3-tuple, either
367 An iterator over the desired lines. Each line is a 3-tuple, either
368 (session, line, input) if output is False, or
368 (session, line, input) if output is False, or
369 (session, line, (input, output)) if output is True.
369 (session, line, (input, output)) if output is True.
370 """
370 """
371 if stop:
371 if stop:
372 lineclause = "line >= ? AND line < ?"
372 lineclause = "line >= ? AND line < ?"
373 params = (session, start, stop)
373 params = (session, start, stop)
374 else:
374 else:
375 lineclause = "line>=?"
375 lineclause = "line>=?"
376 params = (session, start)
376 params = (session, start)
377
377
378 return self._run_sql("WHERE session==? AND %s" % lineclause,
378 return self._run_sql("WHERE session==? AND %s" % lineclause,
379 params, raw=raw, output=output)
379 params, raw=raw, output=output)
380
380
381 def get_range_by_str(self, rangestr, raw=True, output=False):
381 def get_range_by_str(self, rangestr, raw=True, output=False):
382 """Get lines of history from a string of ranges, as used by magic
382 """Get lines of history from a string of ranges, as used by magic
383 commands %hist, %save, %macro, etc.
383 commands %hist, %save, %macro, etc.
384
384
385 Parameters
385 Parameters
386 ----------
386 ----------
387 rangestr : str
387 rangestr : str
388 A string specifying ranges, e.g. "5 ~2/1-4". See
388 A string specifying ranges, e.g. "5 ~2/1-4". See
389 :func:`magic_history` for full details.
389 :func:`magic_history` for full details.
390 raw, output : bool
390 raw, output : bool
391 As :meth:`get_range`
391 As :meth:`get_range`
392
392
393 Returns
393 Returns
394 -------
394 -------
395 Tuples as :meth:`get_range`
395 Tuples as :meth:`get_range`
396 """
396 """
397 for sess, s, e in extract_hist_ranges(rangestr):
397 for sess, s, e in extract_hist_ranges(rangestr):
398 for line in self.get_range(sess, s, e, raw=raw, output=output):
398 for line in self.get_range(sess, s, e, raw=raw, output=output):
399 yield line
399 yield line
400
400
401
401
402 class HistoryManager(HistoryAccessor):
402 class HistoryManager(HistoryAccessor):
403 """A class to organize all history-related functionality in one place.
403 """A class to organize all history-related functionality in one place.
404 """
404 """
405 # Public interface
405 # Public interface
406
406
407 # An instance of the IPython shell we are attached to
407 # An instance of the IPython shell we are attached to
408 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
408 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
409 # Lists to hold processed and raw history. These start with a blank entry
409 # Lists to hold processed and raw history. These start with a blank entry
410 # so that we can index them starting from 1
410 # so that we can index them starting from 1
411 input_hist_parsed = List([""])
411 input_hist_parsed = List([""])
412 input_hist_raw = List([""])
412 input_hist_raw = List([""])
413 # A list of directories visited during session
413 # A list of directories visited during session
414 dir_hist = List()
414 dir_hist = List()
415 def _dir_hist_default(self):
415 def _dir_hist_default(self):
416 try:
416 try:
417 return [os.getcwdu()]
417 return [os.getcwdu()]
418 except OSError:
418 except OSError:
419 return []
419 return []
420
420
421 # A dict of output history, keyed with ints from the shell's
421 # A dict of output history, keyed with ints from the shell's
422 # execution count.
422 # execution count.
423 output_hist = Dict()
423 output_hist = Dict()
424 # The text/plain repr of outputs.
424 # The text/plain repr of outputs.
425 output_hist_reprs = Dict()
425 output_hist_reprs = Dict()
426
426
427 # The number of the current session in the history database
427 # The number of the current session in the history database
428 session_number = Integer()
428 session_number = Integer()
429 # Should we log output to the database? (default no)
429 # Should we log output to the database? (default no)
430 db_log_output = Bool(False, config=True)
430 db_log_output = Bool(False, config=True)
431 # Write to database every x commands (higher values save disk access & power)
431 # Write to database every x commands (higher values save disk access & power)
432 # Values of 1 or less effectively disable caching.
432 # Values of 1 or less effectively disable caching.
433 db_cache_size = Integer(0, config=True)
433 db_cache_size = Integer(0, config=True)
434 # The input and output caches
434 # The input and output caches
435 db_input_cache = List()
435 db_input_cache = List()
436 db_output_cache = List()
436 db_output_cache = List()
437
437
438 # History saving in separate thread
438 # History saving in separate thread
439 save_thread = Instance('IPython.core.history.HistorySavingThread')
439 save_thread = Instance('IPython.core.history.HistorySavingThread')
440 try: # Event is a function returning an instance of _Event...
440 try: # Event is a function returning an instance of _Event...
441 save_flag = Instance(threading._Event)
441 save_flag = Instance(threading._Event)
442 except AttributeError: # ...until Python 3.3, when it's a class.
442 except AttributeError: # ...until Python 3.3, when it's a class.
443 save_flag = Instance(threading.Event)
443 save_flag = Instance(threading.Event)
444
444
445 # Private interface
445 # Private interface
446 # Variables used to store the three last inputs from the user. On each new
446 # Variables used to store the three last inputs from the user. On each new
447 # history update, we populate the user's namespace with these, shifted as
447 # history update, we populate the user's namespace with these, shifted as
448 # necessary.
448 # necessary.
449 _i00 = Unicode(u'')
449 _i00 = Unicode(u'')
450 _i = Unicode(u'')
450 _i = Unicode(u'')
451 _ii = Unicode(u'')
451 _ii = Unicode(u'')
452 _iii = Unicode(u'')
452 _iii = Unicode(u'')
453
453
454 # A regex matching all forms of the exit command, so that we don't store
454 # A regex matching all forms of the exit command, so that we don't store
455 # them in the history (it's annoying to rewind the first entry and land on
455 # them in the history (it's annoying to rewind the first entry and land on
456 # an exit call).
456 # an exit call).
457 _exit_re = re.compile(r"(exit|quit)(\s*\(.*\))?$")
457 _exit_re = re.compile(r"(exit|quit)(\s*\(.*\))?$")
458
458
459 def __init__(self, shell=None, config=None, **traits):
459 def __init__(self, shell=None, config=None, **traits):
460 """Create a new history manager associated with a shell instance.
460 """Create a new history manager associated with a shell instance.
461 """
461 """
462 # We need a pointer back to the shell for various tasks.
462 # We need a pointer back to the shell for various tasks.
463 super(HistoryManager, self).__init__(shell=shell, config=config,
463 super(HistoryManager, self).__init__(shell=shell, config=config,
464 **traits)
464 **traits)
465 self.save_flag = threading.Event()
465 self.save_flag = threading.Event()
466 self.db_input_cache_lock = threading.Lock()
466 self.db_input_cache_lock = threading.Lock()
467 self.db_output_cache_lock = threading.Lock()
467 self.db_output_cache_lock = threading.Lock()
468 if self.enabled and self.hist_file != ':memory:':
468 if self.enabled and self.hist_file != ':memory:':
469 self.save_thread = HistorySavingThread(self)
469 self.save_thread = HistorySavingThread(self)
470 self.save_thread.start()
470 self.save_thread.start()
471
471
472 self.new_session()
472 self.new_session()
473
473
474 def _get_hist_file_name(self, profile=None):
474 def _get_hist_file_name(self, profile=None):
475 """Get default history file name based on the Shell's profile.
475 """Get default history file name based on the Shell's profile.
476
476
477 The profile parameter is ignored, but must exist for compatibility with
477 The profile parameter is ignored, but must exist for compatibility with
478 the parent class."""
478 the parent class."""
479 profile_dir = self.shell.profile_dir.location
479 profile_dir = self.shell.profile_dir.location
480 return os.path.join(profile_dir, 'history.sqlite')
480 return os.path.join(profile_dir, 'history.sqlite')
481
481
482 @needs_sqlite
482 @needs_sqlite
483 def new_session(self, conn=None):
483 def new_session(self, conn=None):
484 """Get a new session number."""
484 """Get a new session number."""
485 if conn is None:
485 if conn is None:
486 conn = self.db
486 conn = self.db
487
487
488 with conn:
488 with conn:
489 cur = conn.execute("""INSERT INTO sessions VALUES (NULL, ?, NULL,
489 cur = conn.execute("""INSERT INTO sessions VALUES (NULL, ?, NULL,
490 NULL, "") """, (datetime.datetime.now(),))
490 NULL, "") """, (datetime.datetime.now(),))
491 self.session_number = cur.lastrowid
491 self.session_number = cur.lastrowid
492
492
493 def end_session(self):
493 def end_session(self):
494 """Close the database session, filling in the end time and line count."""
494 """Close the database session, filling in the end time and line count."""
495 self.writeout_cache()
495 self.writeout_cache()
496 with self.db:
496 with self.db:
497 self.db.execute("""UPDATE sessions SET end=?, num_cmds=? WHERE
497 self.db.execute("""UPDATE sessions SET end=?, num_cmds=? WHERE
498 session==?""", (datetime.datetime.now(),
498 session==?""", (datetime.datetime.now(),
499 len(self.input_hist_parsed)-1, self.session_number))
499 len(self.input_hist_parsed)-1, self.session_number))
500 self.session_number = 0
500 self.session_number = 0
501
501
502 def name_session(self, name):
502 def name_session(self, name):
503 """Give the current session a name in the history database."""
503 """Give the current session a name in the history database."""
504 with self.db:
504 with self.db:
505 self.db.execute("UPDATE sessions SET remark=? WHERE session==?",
505 self.db.execute("UPDATE sessions SET remark=? WHERE session==?",
506 (name, self.session_number))
506 (name, self.session_number))
507
507
508 def reset(self, new_session=True):
508 def reset(self, new_session=True):
509 """Clear the session history, releasing all object references, and
509 """Clear the session history, releasing all object references, and
510 optionally open a new session."""
510 optionally open a new session."""
511 self.output_hist.clear()
511 self.output_hist.clear()
512 # The directory history can't be completely empty
512 # The directory history can't be completely empty
513 self.dir_hist[:] = [os.getcwdu()]
513 self.dir_hist[:] = [os.getcwdu()]
514
514
515 if new_session:
515 if new_session:
516 if self.session_number:
516 if self.session_number:
517 self.end_session()
517 self.end_session()
518 self.input_hist_parsed[:] = [""]
518 self.input_hist_parsed[:] = [""]
519 self.input_hist_raw[:] = [""]
519 self.input_hist_raw[:] = [""]
520 self.new_session()
520 self.new_session()
521
521
522 # ------------------------------
522 # ------------------------------
523 # Methods for retrieving history
523 # Methods for retrieving history
524 # ------------------------------
524 # ------------------------------
525 def _get_range_session(self, start=1, stop=None, raw=True, output=False):
525 def _get_range_session(self, start=1, stop=None, raw=True, output=False):
526 """Get input and output history from the current session. Called by
526 """Get input and output history from the current session. Called by
527 get_range, and takes similar parameters."""
527 get_range, and takes similar parameters."""
528 input_hist = self.input_hist_raw if raw else self.input_hist_parsed
528 input_hist = self.input_hist_raw if raw else self.input_hist_parsed
529
529
530 n = len(input_hist)
530 n = len(input_hist)
531 if start < 0:
531 if start < 0:
532 start += n
532 start += n
533 if not stop or (stop > n):
533 if not stop or (stop > n):
534 stop = n
534 stop = n
535 elif stop < 0:
535 elif stop < 0:
536 stop += n
536 stop += n
537
537
538 for i in range(start, stop):
538 for i in range(start, stop):
539 if output:
539 if output:
540 line = (input_hist[i], self.output_hist_reprs.get(i))
540 line = (input_hist[i], self.output_hist_reprs.get(i))
541 else:
541 else:
542 line = input_hist[i]
542 line = input_hist[i]
543 yield (0, i, line)
543 yield (0, i, line)
544
544
545 def get_range(self, session=0, start=1, stop=None, raw=True,output=False):
545 def get_range(self, session=0, start=1, stop=None, raw=True,output=False):
546 """Retrieve input by session.
546 """Retrieve input by session.
547
547
548 Parameters
548 Parameters
549 ----------
549 ----------
550 session : int
550 session : int
551 Session number to retrieve. The current session is 0, and negative
551 Session number to retrieve. The current session is 0, and negative
552 numbers count back from current session, so -1 is previous session.
552 numbers count back from current session, so -1 is previous session.
553 start : int
553 start : int
554 First line to retrieve.
554 First line to retrieve.
555 stop : int
555 stop : int
556 End of line range (excluded from output itself). If None, retrieve
556 End of line range (excluded from output itself). If None, retrieve
557 to the end of the session.
557 to the end of the session.
558 raw : bool
558 raw : bool
559 If True, return untranslated input
559 If True, return untranslated input
560 output : bool
560 output : bool
561 If True, attempt to include output. This will be 'real' Python
561 If True, attempt to include output. This will be 'real' Python
562 objects for the current session, or text reprs from previous
562 objects for the current session, or text reprs from previous
563 sessions if db_log_output was enabled at the time. Where no output
563 sessions if db_log_output was enabled at the time. Where no output
564 is found, None is used.
564 is found, None is used.
565
565
566 Returns
566 Returns
567 -------
567 -------
568 An iterator over the desired lines. Each line is a 3-tuple, either
568 An iterator over the desired lines. Each line is a 3-tuple, either
569 (session, line, input) if output is False, or
569 (session, line, input) if output is False, or
570 (session, line, (input, output)) if output is True.
570 (session, line, (input, output)) if output is True.
571 """
571 """
572 if session <= 0:
572 if session <= 0:
573 session += self.session_number
573 session += self.session_number
574 if session==self.session_number: # Current session
574 if session==self.session_number: # Current session
575 return self._get_range_session(start, stop, raw, output)
575 return self._get_range_session(start, stop, raw, output)
576 return super(HistoryManager, self).get_range(session, start, stop, raw,
576 return super(HistoryManager, self).get_range(session, start, stop, raw,
577 output)
577 output)
578
578
579 ## ----------------------------
579 ## ----------------------------
580 ## Methods for storing history:
580 ## Methods for storing history:
581 ## ----------------------------
581 ## ----------------------------
582 def store_inputs(self, line_num, source, source_raw=None):
582 def store_inputs(self, line_num, source, source_raw=None):
583 """Store source and raw input in history and create input cache
583 """Store source and raw input in history and create input cache
584 variables _i*.
584 variables _i*.
585
585
586 Parameters
586 Parameters
587 ----------
587 ----------
588 line_num : int
588 line_num : int
589 The prompt number of this input.
589 The prompt number of this input.
590
590
591 source : str
591 source : str
592 Python input.
592 Python input.
593
593
594 source_raw : str, optional
594 source_raw : str, optional
595 If given, this is the raw input without any IPython transformations
595 If given, this is the raw input without any IPython transformations
596 applied to it. If not given, ``source`` is used.
596 applied to it. If not given, ``source`` is used.
597 """
597 """
598 if source_raw is None:
598 if source_raw is None:
599 source_raw = source
599 source_raw = source
600 source = source.rstrip('\n')
600 source = source.rstrip('\n')
601 source_raw = source_raw.rstrip('\n')
601 source_raw = source_raw.rstrip('\n')
602
602
603 # do not store exit/quit commands
603 # do not store exit/quit commands
604 if self._exit_re.match(source_raw.strip()):
604 if self._exit_re.match(source_raw.strip()):
605 return
605 return
606
606
607 self.input_hist_parsed.append(source)
607 self.input_hist_parsed.append(source)
608 self.input_hist_raw.append(source_raw)
608 self.input_hist_raw.append(source_raw)
609
609
610 with self.db_input_cache_lock:
610 with self.db_input_cache_lock:
611 self.db_input_cache.append((line_num, source, source_raw))
611 self.db_input_cache.append((line_num, source, source_raw))
612 # Trigger to flush cache and write to DB.
612 # Trigger to flush cache and write to DB.
613 if len(self.db_input_cache) >= self.db_cache_size:
613 if len(self.db_input_cache) >= self.db_cache_size:
614 self.save_flag.set()
614 self.save_flag.set()
615
615
616 # update the auto _i variables
616 # update the auto _i variables
617 self._iii = self._ii
617 self._iii = self._ii
618 self._ii = self._i
618 self._ii = self._i
619 self._i = self._i00
619 self._i = self._i00
620 self._i00 = source_raw
620 self._i00 = source_raw
621
621
622 # hackish access to user namespace to create _i1,_i2... dynamically
622 # hackish access to user namespace to create _i1,_i2... dynamically
623 new_i = '_i%s' % line_num
623 new_i = '_i%s' % line_num
624 to_main = {'_i': self._i,
624 to_main = {'_i': self._i,
625 '_ii': self._ii,
625 '_ii': self._ii,
626 '_iii': self._iii,
626 '_iii': self._iii,
627 new_i : self._i00 }
627 new_i : self._i00 }
628
628
629 self.shell.push(to_main, interactive=False)
629 self.shell.push(to_main, interactive=False)
630
630
631 def store_output(self, line_num):
631 def store_output(self, line_num):
632 """If database output logging is enabled, this saves all the
632 """If database output logging is enabled, this saves all the
633 outputs from the indicated prompt number to the database. It's
633 outputs from the indicated prompt number to the database. It's
634 called by run_cell after code has been executed.
634 called by run_cell after code has been executed.
635
635
636 Parameters
636 Parameters
637 ----------
637 ----------
638 line_num : int
638 line_num : int
639 The line number from which to save outputs
639 The line number from which to save outputs
640 """
640 """
641 if (not self.db_log_output) or (line_num not in self.output_hist_reprs):
641 if (not self.db_log_output) or (line_num not in self.output_hist_reprs):
642 return
642 return
643 output = self.output_hist_reprs[line_num]
643 output = self.output_hist_reprs[line_num]
644
644
645 with self.db_output_cache_lock:
645 with self.db_output_cache_lock:
646 self.db_output_cache.append((line_num, output))
646 self.db_output_cache.append((line_num, output))
647 if self.db_cache_size <= 1:
647 if self.db_cache_size <= 1:
648 self.save_flag.set()
648 self.save_flag.set()
649
649
650 def _writeout_input_cache(self, conn):
650 def _writeout_input_cache(self, conn):
651 with conn:
651 with conn:
652 for line in self.db_input_cache:
652 for line in self.db_input_cache:
653 conn.execute("INSERT INTO history VALUES (?, ?, ?, ?)",
653 conn.execute("INSERT INTO history VALUES (?, ?, ?, ?)",
654 (self.session_number,)+line)
654 (self.session_number,)+line)
655
655
656 def _writeout_output_cache(self, conn):
656 def _writeout_output_cache(self, conn):
657 with conn:
657 with conn:
658 for line in self.db_output_cache:
658 for line in self.db_output_cache:
659 conn.execute("INSERT INTO output_history VALUES (?, ?, ?)",
659 conn.execute("INSERT INTO output_history VALUES (?, ?, ?)",
660 (self.session_number,)+line)
660 (self.session_number,)+line)
661
661
662 @needs_sqlite
662 @needs_sqlite
663 def writeout_cache(self, conn=None):
663 def writeout_cache(self, conn=None):
664 """Write any entries in the cache to the database."""
664 """Write any entries in the cache to the database."""
665 if conn is None:
665 if conn is None:
666 conn = self.db
666 conn = self.db
667
667
668 with self.db_input_cache_lock:
668 with self.db_input_cache_lock:
669 try:
669 try:
670 self._writeout_input_cache(conn)
670 self._writeout_input_cache(conn)
671 except sqlite3.IntegrityError:
671 except sqlite3.IntegrityError:
672 self.new_session(conn)
672 self.new_session(conn)
673 print("ERROR! Session/line number was not unique in",
673 print("ERROR! Session/line number was not unique in",
674 "database. History logging moved to new session",
674 "database. History logging moved to new session",
675 self.session_number)
675 self.session_number)
676 try:
676 try:
677 # Try writing to the new session. If this fails, don't
677 # Try writing to the new session. If this fails, don't
678 # recurse
678 # recurse
679 self._writeout_input_cache(conn)
679 self._writeout_input_cache(conn)
680 except sqlite3.IntegrityError:
680 except sqlite3.IntegrityError:
681 pass
681 pass
682 finally:
682 finally:
683 self.db_input_cache = []
683 self.db_input_cache = []
684
684
685 with self.db_output_cache_lock:
685 with self.db_output_cache_lock:
686 try:
686 try:
687 self._writeout_output_cache(conn)
687 self._writeout_output_cache(conn)
688 except sqlite3.IntegrityError:
688 except sqlite3.IntegrityError:
689 print("!! Session/line number for output was not unique",
689 print("!! Session/line number for output was not unique",
690 "in database. Output will not be stored.")
690 "in database. Output will not be stored.")
691 finally:
691 finally:
692 self.db_output_cache = []
692 self.db_output_cache = []
693
693
694
694
695 class HistorySavingThread(threading.Thread):
695 class HistorySavingThread(threading.Thread):
696 """This thread takes care of writing history to the database, so that
696 """This thread takes care of writing history to the database, so that
697 the UI isn't held up while that happens.
697 the UI isn't held up while that happens.
698
698
699 It waits for the HistoryManager's save_flag to be set, then writes out
699 It waits for the HistoryManager's save_flag to be set, then writes out
700 the history cache. The main thread is responsible for setting the flag when
700 the history cache. The main thread is responsible for setting the flag when
701 the cache size reaches a defined threshold."""
701 the cache size reaches a defined threshold."""
702 daemon = True
702 daemon = True
703 stop_now = False
703 stop_now = False
704 enabled = True
704 enabled = True
705 def __init__(self, history_manager):
705 def __init__(self, history_manager):
706 super(HistorySavingThread, self).__init__()
706 super(HistorySavingThread, self).__init__()
707 self.history_manager = history_manager
707 self.history_manager = history_manager
708 self.enabled = history_manager.enabled
708 self.enabled = history_manager.enabled
709 atexit.register(self.stop)
709 atexit.register(self.stop)
710
710
711 @needs_sqlite
711 @needs_sqlite
712 def run(self):
712 def run(self):
713 # We need a separate db connection per thread:
713 # We need a separate db connection per thread:
714 try:
714 try:
715 self.db = sqlite3.connect(self.history_manager.hist_file,
715 self.db = sqlite3.connect(self.history_manager.hist_file,
716 **self.history_manager.connection_options
716 **self.history_manager.connection_options
717 )
717 )
718 while True:
718 while True:
719 self.history_manager.save_flag.wait()
719 self.history_manager.save_flag.wait()
720 if self.stop_now:
720 if self.stop_now:
721 return
721 return
722 self.history_manager.save_flag.clear()
722 self.history_manager.save_flag.clear()
723 self.history_manager.writeout_cache(self.db)
723 self.history_manager.writeout_cache(self.db)
724 except Exception as e:
724 except Exception as e:
725 print(("The history saving thread hit an unexpected error (%s)."
725 print(("The history saving thread hit an unexpected error (%s)."
726 "History will not be written to the database.") % repr(e))
726 "History will not be written to the database.") % repr(e))
727
727
728 def stop(self):
728 def stop(self):
729 """This can be called from the main thread to safely stop this thread.
729 """This can be called from the main thread to safely stop this thread.
730
730
731 Note that it does not attempt to write out remaining history before
731 Note that it does not attempt to write out remaining history before
732 exiting. That should be done by calling the HistoryManager's
732 exiting. That should be done by calling the HistoryManager's
733 end_session method."""
733 end_session method."""
734 self.stop_now = True
734 self.stop_now = True
735 self.history_manager.save_flag.set()
735 self.history_manager.save_flag.set()
736 self.join()
736 self.join()
737
737
738
738
739 # To match, e.g. ~5/8-~2/3
739 # To match, e.g. ~5/8-~2/3
740 range_re = re.compile(r"""
740 range_re = re.compile(r"""
741 ((?P<startsess>~?\d+)/)?
741 ((?P<startsess>~?\d+)/)?
742 (?P<start>\d+) # Only the start line num is compulsory
742 (?P<start>\d+) # Only the start line num is compulsory
743 ((?P<sep>[\-:])
743 ((?P<sep>[\-:])
744 ((?P<endsess>~?\d+)/)?
744 ((?P<endsess>~?\d+)/)?
745 (?P<end>\d+))?
745 (?P<end>\d+))?
746 $""", re.VERBOSE)
746 $""", re.VERBOSE)
747
747
748
748
749 def extract_hist_ranges(ranges_str):
749 def extract_hist_ranges(ranges_str):
750 """Turn a string of history ranges into 3-tuples of (session, start, stop).
750 """Turn a string of history ranges into 3-tuples of (session, start, stop).
751
751
752 Examples
752 Examples
753 --------
753 --------
754 list(extract_input_ranges("~8/5-~7/4 2"))
754 list(extract_input_ranges("~8/5-~7/4 2"))
755 [(-8, 5, None), (-7, 1, 4), (0, 2, 3)]
755 [(-8, 5, None), (-7, 1, 4), (0, 2, 3)]
756 """
756 """
757 for range_str in ranges_str.split():
757 for range_str in ranges_str.split():
758 rmatch = range_re.match(range_str)
758 rmatch = range_re.match(range_str)
759 if not rmatch:
759 if not rmatch:
760 continue
760 continue
761 start = int(rmatch.group("start"))
761 start = int(rmatch.group("start"))
762 end = rmatch.group("end")
762 end = rmatch.group("end")
763 end = int(end) if end else start+1 # If no end specified, get (a, a+1)
763 end = int(end) if end else start+1 # If no end specified, get (a, a+1)
764 if rmatch.group("sep") == "-": # 1-3 == 1:4 --> [1, 2, 3]
764 if rmatch.group("sep") == "-": # 1-3 == 1:4 --> [1, 2, 3]
765 end += 1
765 end += 1
766 startsess = rmatch.group("startsess") or "0"
766 startsess = rmatch.group("startsess") or "0"
767 endsess = rmatch.group("endsess") or startsess
767 endsess = rmatch.group("endsess") or startsess
768 startsess = int(startsess.replace("~","-"))
768 startsess = int(startsess.replace("~","-"))
769 endsess = int(endsess.replace("~","-"))
769 endsess = int(endsess.replace("~","-"))
770 assert endsess >= startsess
770 assert endsess >= startsess
771
771
772 if endsess == startsess:
772 if endsess == startsess:
773 yield (startsess, start, end)
773 yield (startsess, start, end)
774 continue
774 continue
775 # Multiple sessions in one range:
775 # Multiple sessions in one range:
776 yield (startsess, start, None)
776 yield (startsess, start, None)
777 for sess in range(startsess+1, endsess):
777 for sess in range(startsess+1, endsess):
778 yield (sess, 1, None)
778 yield (sess, 1, None)
779 yield (endsess, 1, end)
779 yield (endsess, 1, end)
780
780
781
781
782 def _format_lineno(session, line):
782 def _format_lineno(session, line):
783 """Helper function to format line numbers properly."""
783 """Helper function to format line numbers properly."""
784 if session == 0:
784 if session == 0:
785 return str(line)
785 return str(line)
786 return "%s#%s" % (session, line)
786 return "%s#%s" % (session, line)
787
787
788
788
@@ -1,3010 +1,3044 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Main IPython class."""
2 """Main IPython class."""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2008-2011 The IPython Development Team
7 # Copyright (C) 2008-2011 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 from __future__ import with_statement
17 from __future__ import with_statement
18 from __future__ import absolute_import
18 from __future__ import absolute_import
19 from __future__ import print_function
19 from __future__ import print_function
20
20
21 import __builtin__ as builtin_mod
21 import __builtin__ as builtin_mod
22 import __future__
22 import __future__
23 import abc
23 import abc
24 import ast
24 import ast
25 import atexit
25 import atexit
26 import os
26 import os
27 import re
27 import re
28 import runpy
28 import runpy
29 import sys
29 import sys
30 import tempfile
30 import tempfile
31 import types
31 import types
32 import urllib
32 import urllib
33 from io import open as io_open
33 from io import open as io_open
34
34
35 from IPython.config.configurable import SingletonConfigurable
35 from IPython.config.configurable import SingletonConfigurable
36 from IPython.core import debugger, oinspect
36 from IPython.core import debugger, oinspect
37 from IPython.core import magic
37 from IPython.core import magic
38 from IPython.core import page
38 from IPython.core import page
39 from IPython.core import prefilter
39 from IPython.core import prefilter
40 from IPython.core import shadowns
40 from IPython.core import shadowns
41 from IPython.core import ultratb
41 from IPython.core import ultratb
42 from IPython.core.alias import AliasManager, AliasError
42 from IPython.core.alias import AliasManager, AliasError
43 from IPython.core.autocall import ExitAutocall
43 from IPython.core.autocall import ExitAutocall
44 from IPython.core.builtin_trap import BuiltinTrap
44 from IPython.core.builtin_trap import BuiltinTrap
45 from IPython.core.compilerop import CachingCompiler
45 from IPython.core.compilerop import CachingCompiler
46 from IPython.core.display_trap import DisplayTrap
46 from IPython.core.display_trap import DisplayTrap
47 from IPython.core.displayhook import DisplayHook
47 from IPython.core.displayhook import DisplayHook
48 from IPython.core.displaypub import DisplayPublisher
48 from IPython.core.displaypub import DisplayPublisher
49 from IPython.core.error import UsageError
49 from IPython.core.error import UsageError
50 from IPython.core.extensions import ExtensionManager
50 from IPython.core.extensions import ExtensionManager
51 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
51 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
52 from IPython.core.formatters import DisplayFormatter
52 from IPython.core.formatters import DisplayFormatter
53 from IPython.core.history import HistoryManager
53 from IPython.core.history import HistoryManager
54 from IPython.core.inputsplitter import IPythonInputSplitter, ESC_MAGIC, ESC_MAGIC2
54 from IPython.core.inputsplitter import IPythonInputSplitter, ESC_MAGIC, ESC_MAGIC2
55 from IPython.core.logger import Logger
55 from IPython.core.logger import Logger
56 from IPython.core.macro import Macro
56 from IPython.core.macro import Macro
57 from IPython.core.payload import PayloadManager
57 from IPython.core.payload import PayloadManager
58 from IPython.core.prefilter import PrefilterManager
58 from IPython.core.prefilter import PrefilterManager
59 from IPython.core.profiledir import ProfileDir
59 from IPython.core.profiledir import ProfileDir
60 from IPython.core.pylabtools import pylab_activate
60 from IPython.core.pylabtools import pylab_activate
61 from IPython.core.prompts import PromptManager
61 from IPython.core.prompts import PromptManager
62 from IPython.lib.latextools import LaTeXTool
62 from IPython.lib.latextools import LaTeXTool
63 from IPython.utils import PyColorize
63 from IPython.utils import PyColorize
64 from IPython.utils import io
64 from IPython.utils import io
65 from IPython.utils import py3compat
65 from IPython.utils import py3compat
66 from IPython.utils import openpy
66 from IPython.utils import openpy
67 from IPython.utils.decorators import undoc
67 from IPython.utils.decorators import undoc
68 from IPython.utils.doctestreload import doctest_reload
68 from IPython.utils.doctestreload import doctest_reload
69 from IPython.utils.io import ask_yes_no
69 from IPython.utils.io import ask_yes_no
70 from IPython.utils.ipstruct import Struct
70 from IPython.utils.ipstruct import Struct
71 from IPython.utils.path import get_home_dir, get_ipython_dir, get_py_filename, unquote_filename
71 from IPython.utils.path import get_home_dir, get_ipython_dir, get_py_filename, unquote_filename
72 from IPython.utils.pickleshare import PickleShareDB
72 from IPython.utils.pickleshare import PickleShareDB
73 from IPython.utils.process import system, getoutput
73 from IPython.utils.process import system, getoutput
74 from IPython.utils.strdispatch import StrDispatch
74 from IPython.utils.strdispatch import StrDispatch
75 from IPython.utils.syspathcontext import prepended_to_syspath
75 from IPython.utils.syspathcontext import prepended_to_syspath
76 from IPython.utils.text import (format_screen, LSString, SList,
76 from IPython.utils.text import (format_screen, LSString, SList,
77 DollarFormatter)
77 DollarFormatter)
78 from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum,
78 from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum,
79 List, Unicode, Instance, Type)
79 List, Unicode, Instance, Type)
80 from IPython.utils.warn import warn, error
80 from IPython.utils.warn import warn, error
81 import IPython.core.hooks
81 import IPython.core.hooks
82
82
83 #-----------------------------------------------------------------------------
83 #-----------------------------------------------------------------------------
84 # Globals
84 # Globals
85 #-----------------------------------------------------------------------------
85 #-----------------------------------------------------------------------------
86
86
87 # compiled regexps for autoindent management
87 # compiled regexps for autoindent management
88 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
88 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
89
89
90 #-----------------------------------------------------------------------------
90 #-----------------------------------------------------------------------------
91 # Utilities
91 # Utilities
92 #-----------------------------------------------------------------------------
92 #-----------------------------------------------------------------------------
93
93
94 @undoc
94 @undoc
95 def softspace(file, newvalue):
95 def softspace(file, newvalue):
96 """Copied from code.py, to remove the dependency"""
96 """Copied from code.py, to remove the dependency"""
97
97
98 oldvalue = 0
98 oldvalue = 0
99 try:
99 try:
100 oldvalue = file.softspace
100 oldvalue = file.softspace
101 except AttributeError:
101 except AttributeError:
102 pass
102 pass
103 try:
103 try:
104 file.softspace = newvalue
104 file.softspace = newvalue
105 except (AttributeError, TypeError):
105 except (AttributeError, TypeError):
106 # "attribute-less object" or "read-only attributes"
106 # "attribute-less object" or "read-only attributes"
107 pass
107 pass
108 return oldvalue
108 return oldvalue
109
109
110 @undoc
110 @undoc
111 def no_op(*a, **kw): pass
111 def no_op(*a, **kw): pass
112
112
113 @undoc
113 @undoc
114 class NoOpContext(object):
114 class NoOpContext(object):
115 def __enter__(self): pass
115 def __enter__(self): pass
116 def __exit__(self, type, value, traceback): pass
116 def __exit__(self, type, value, traceback): pass
117 no_op_context = NoOpContext()
117 no_op_context = NoOpContext()
118
118
119 class SpaceInInput(Exception): pass
119 class SpaceInInput(Exception): pass
120
120
121 @undoc
121 @undoc
122 class Bunch: pass
122 class Bunch: pass
123
123
124
124
125 def get_default_colors():
125 def get_default_colors():
126 if sys.platform=='darwin':
126 if sys.platform=='darwin':
127 return "LightBG"
127 return "LightBG"
128 elif os.name=='nt':
128 elif os.name=='nt':
129 return 'Linux'
129 return 'Linux'
130 else:
130 else:
131 return 'Linux'
131 return 'Linux'
132
132
133
133
134 class SeparateUnicode(Unicode):
134 class SeparateUnicode(Unicode):
135 """A Unicode subclass to validate separate_in, separate_out, etc.
135 """A Unicode subclass to validate separate_in, separate_out, etc.
136
136
137 This is a Unicode based trait that converts '0'->'' and '\\n'->'\n'.
137 This is a Unicode based trait that converts '0'->'' and '\\n'->'\n'.
138 """
138 """
139
139
140 def validate(self, obj, value):
140 def validate(self, obj, value):
141 if value == '0': value = ''
141 if value == '0': value = ''
142 value = value.replace('\\n','\n')
142 value = value.replace('\\n','\n')
143 return super(SeparateUnicode, self).validate(obj, value)
143 return super(SeparateUnicode, self).validate(obj, value)
144
144
145
145
146 class ReadlineNoRecord(object):
146 class ReadlineNoRecord(object):
147 """Context manager to execute some code, then reload readline history
147 """Context manager to execute some code, then reload readline history
148 so that interactive input to the code doesn't appear when pressing up."""
148 so that interactive input to the code doesn't appear when pressing up."""
149 def __init__(self, shell):
149 def __init__(self, shell):
150 self.shell = shell
150 self.shell = shell
151 self._nested_level = 0
151 self._nested_level = 0
152
152
153 def __enter__(self):
153 def __enter__(self):
154 if self._nested_level == 0:
154 if self._nested_level == 0:
155 try:
155 try:
156 self.orig_length = self.current_length()
156 self.orig_length = self.current_length()
157 self.readline_tail = self.get_readline_tail()
157 self.readline_tail = self.get_readline_tail()
158 except (AttributeError, IndexError): # Can fail with pyreadline
158 except (AttributeError, IndexError): # Can fail with pyreadline
159 self.orig_length, self.readline_tail = 999999, []
159 self.orig_length, self.readline_tail = 999999, []
160 self._nested_level += 1
160 self._nested_level += 1
161
161
162 def __exit__(self, type, value, traceback):
162 def __exit__(self, type, value, traceback):
163 self._nested_level -= 1
163 self._nested_level -= 1
164 if self._nested_level == 0:
164 if self._nested_level == 0:
165 # Try clipping the end if it's got longer
165 # Try clipping the end if it's got longer
166 try:
166 try:
167 e = self.current_length() - self.orig_length
167 e = self.current_length() - self.orig_length
168 if e > 0:
168 if e > 0:
169 for _ in range(e):
169 for _ in range(e):
170 self.shell.readline.remove_history_item(self.orig_length)
170 self.shell.readline.remove_history_item(self.orig_length)
171
171
172 # If it still doesn't match, just reload readline history.
172 # If it still doesn't match, just reload readline history.
173 if self.current_length() != self.orig_length \
173 if self.current_length() != self.orig_length \
174 or self.get_readline_tail() != self.readline_tail:
174 or self.get_readline_tail() != self.readline_tail:
175 self.shell.refill_readline_hist()
175 self.shell.refill_readline_hist()
176 except (AttributeError, IndexError):
176 except (AttributeError, IndexError):
177 pass
177 pass
178 # Returning False will cause exceptions to propagate
178 # Returning False will cause exceptions to propagate
179 return False
179 return False
180
180
181 def current_length(self):
181 def current_length(self):
182 return self.shell.readline.get_current_history_length()
182 return self.shell.readline.get_current_history_length()
183
183
184 def get_readline_tail(self, n=10):
184 def get_readline_tail(self, n=10):
185 """Get the last n items in readline history."""
185 """Get the last n items in readline history."""
186 end = self.shell.readline.get_current_history_length() + 1
186 end = self.shell.readline.get_current_history_length() + 1
187 start = max(end-n, 1)
187 start = max(end-n, 1)
188 ghi = self.shell.readline.get_history_item
188 ghi = self.shell.readline.get_history_item
189 return [ghi(x) for x in range(start, end)]
189 return [ghi(x) for x in range(start, end)]
190
190
191 #-----------------------------------------------------------------------------
191 #-----------------------------------------------------------------------------
192 # Main IPython class
192 # Main IPython class
193 #-----------------------------------------------------------------------------
193 #-----------------------------------------------------------------------------
194
194
195 class InteractiveShell(SingletonConfigurable):
195 class InteractiveShell(SingletonConfigurable):
196 """An enhanced, interactive shell for Python."""
196 """An enhanced, interactive shell for Python."""
197
197
198 _instance = None
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 autocall = Enum((0,1,2), default_value=0, config=True, help=
207 autocall = Enum((0,1,2), default_value=0, config=True, help=
201 """
208 """
202 Make IPython automatically call any callable object even if you didn't
209 Make IPython automatically call any callable object even if you didn't
203 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
210 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
204 automatically. The value can be '0' to disable the feature, '1' for
211 automatically. The value can be '0' to disable the feature, '1' for
205 'smart' autocall, where it is not applied if there are no more
212 'smart' autocall, where it is not applied if there are no more
206 arguments on the line, and '2' for 'full' autocall, where all callable
213 arguments on the line, and '2' for 'full' autocall, where all callable
207 objects are automatically called (even if no arguments are present).
214 objects are automatically called (even if no arguments are present).
208 """
215 """
209 )
216 )
210 # TODO: remove all autoindent logic and put into frontends.
217 # TODO: remove all autoindent logic and put into frontends.
211 # We can't do this yet because even runlines uses the autoindent.
218 # We can't do this yet because even runlines uses the autoindent.
212 autoindent = CBool(True, config=True, help=
219 autoindent = CBool(True, config=True, help=
213 """
220 """
214 Autoindent IPython code entered interactively.
221 Autoindent IPython code entered interactively.
215 """
222 """
216 )
223 )
217 automagic = CBool(True, config=True, help=
224 automagic = CBool(True, config=True, help=
218 """
225 """
219 Enable magic commands to be called without the leading %.
226 Enable magic commands to be called without the leading %.
220 """
227 """
221 )
228 )
222 cache_size = Integer(1000, config=True, help=
229 cache_size = Integer(1000, config=True, help=
223 """
230 """
224 Set the size of the output cache. The default is 1000, you can
231 Set the size of the output cache. The default is 1000, you can
225 change it permanently in your config file. Setting it to 0 completely
232 change it permanently in your config file. Setting it to 0 completely
226 disables the caching system, and the minimum value accepted is 20 (if
233 disables the caching system, and the minimum value accepted is 20 (if
227 you provide a value less than 20, it is reset to 0 and a warning is
234 you provide a value less than 20, it is reset to 0 and a warning is
228 issued). This limit is defined because otherwise you'll spend more
235 issued). This limit is defined because otherwise you'll spend more
229 time re-flushing a too small cache than working
236 time re-flushing a too small cache than working
230 """
237 """
231 )
238 )
232 color_info = CBool(True, config=True, help=
239 color_info = CBool(True, config=True, help=
233 """
240 """
234 Use colors for displaying information about objects. Because this
241 Use colors for displaying information about objects. Because this
235 information is passed through a pager (like 'less'), and some pagers
242 information is passed through a pager (like 'less'), and some pagers
236 get confused with color codes, this capability can be turned off.
243 get confused with color codes, this capability can be turned off.
237 """
244 """
238 )
245 )
239 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
246 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
240 default_value=get_default_colors(), config=True,
247 default_value=get_default_colors(), config=True,
241 help="Set the color scheme (NoColor, Linux, or LightBG)."
248 help="Set the color scheme (NoColor, Linux, or LightBG)."
242 )
249 )
243 colors_force = CBool(False, help=
250 colors_force = CBool(False, help=
244 """
251 """
245 Force use of ANSI color codes, regardless of OS and readline
252 Force use of ANSI color codes, regardless of OS and readline
246 availability.
253 availability.
247 """
254 """
248 # FIXME: This is essentially a hack to allow ZMQShell to show colors
255 # FIXME: This is essentially a hack to allow ZMQShell to show colors
249 # without readline on Win32. When the ZMQ formatting system is
256 # without readline on Win32. When the ZMQ formatting system is
250 # refactored, this should be removed.
257 # refactored, this should be removed.
251 )
258 )
252 debug = CBool(False, config=True)
259 debug = CBool(False, config=True)
253 deep_reload = CBool(False, config=True, help=
260 deep_reload = CBool(False, config=True, help=
254 """
261 """
255 Enable deep (recursive) reloading by default. IPython can use the
262 Enable deep (recursive) reloading by default. IPython can use the
256 deep_reload module which reloads changes in modules recursively (it
263 deep_reload module which reloads changes in modules recursively (it
257 replaces the reload() function, so you don't need to change anything to
264 replaces the reload() function, so you don't need to change anything to
258 use it). deep_reload() forces a full reload of modules whose code may
265 use it). deep_reload() forces a full reload of modules whose code may
259 have changed, which the default reload() function does not. When
266 have changed, which the default reload() function does not. When
260 deep_reload is off, IPython will use the normal reload(), but
267 deep_reload is off, IPython will use the normal reload(), but
261 deep_reload will still be available as dreload().
268 deep_reload will still be available as dreload().
262 """
269 """
263 )
270 )
264 disable_failing_post_execute = CBool(False, config=True,
271 disable_failing_post_execute = CBool(False, config=True,
265 help="Don't call post-execute functions that have failed in the past."
272 help="Don't call post-execute functions that have failed in the past."
266 )
273 )
267 display_formatter = Instance(DisplayFormatter)
274 display_formatter = Instance(DisplayFormatter)
268 displayhook_class = Type(DisplayHook)
275 displayhook_class = Type(DisplayHook)
269 display_pub_class = Type(DisplayPublisher)
276 display_pub_class = Type(DisplayPublisher)
270 data_pub_class = None
277 data_pub_class = None
271
278
272 exit_now = CBool(False)
279 exit_now = CBool(False)
273 exiter = Instance(ExitAutocall)
280 exiter = Instance(ExitAutocall)
274 def _exiter_default(self):
281 def _exiter_default(self):
275 return ExitAutocall(self)
282 return ExitAutocall(self)
276 # Monotonically increasing execution counter
283 # Monotonically increasing execution counter
277 execution_count = Integer(1)
284 execution_count = Integer(1)
278 filename = Unicode("<ipython console>")
285 filename = Unicode("<ipython console>")
279 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
286 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
280
287
281 # Input splitter, to split entire cells of input into either individual
288 # Input splitter, to split entire cells of input into either individual
282 # interactive statements or whole blocks.
289 # interactive statements or whole blocks.
283 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
290 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
284 (), {})
291 (), {})
285 logstart = CBool(False, config=True, help=
292 logstart = CBool(False, config=True, help=
286 """
293 """
287 Start logging to the default log file.
294 Start logging to the default log file.
288 """
295 """
289 )
296 )
290 logfile = Unicode('', config=True, help=
297 logfile = Unicode('', config=True, help=
291 """
298 """
292 The name of the logfile to use.
299 The name of the logfile to use.
293 """
300 """
294 )
301 )
295 logappend = Unicode('', config=True, help=
302 logappend = Unicode('', config=True, help=
296 """
303 """
297 Start logging to the given file in append mode.
304 Start logging to the given file in append mode.
298 """
305 """
299 )
306 )
300 object_info_string_level = Enum((0,1,2), default_value=0,
307 object_info_string_level = Enum((0,1,2), default_value=0,
301 config=True)
308 config=True)
302 pdb = CBool(False, config=True, help=
309 pdb = CBool(False, config=True, help=
303 """
310 """
304 Automatically call the pdb debugger after every exception.
311 Automatically call the pdb debugger after every exception.
305 """
312 """
306 )
313 )
307 multiline_history = CBool(sys.platform != 'win32', config=True,
314 multiline_history = CBool(sys.platform != 'win32', config=True,
308 help="Save multi-line entries as one entry in readline history"
315 help="Save multi-line entries as one entry in readline history"
309 )
316 )
310
317
311 # deprecated prompt traits:
318 # deprecated prompt traits:
312
319
313 prompt_in1 = Unicode('In [\\#]: ', config=True,
320 prompt_in1 = Unicode('In [\\#]: ', config=True,
314 help="Deprecated, use PromptManager.in_template")
321 help="Deprecated, use PromptManager.in_template")
315 prompt_in2 = Unicode(' .\\D.: ', config=True,
322 prompt_in2 = Unicode(' .\\D.: ', config=True,
316 help="Deprecated, use PromptManager.in2_template")
323 help="Deprecated, use PromptManager.in2_template")
317 prompt_out = Unicode('Out[\\#]: ', config=True,
324 prompt_out = Unicode('Out[\\#]: ', config=True,
318 help="Deprecated, use PromptManager.out_template")
325 help="Deprecated, use PromptManager.out_template")
319 prompts_pad_left = CBool(True, config=True,
326 prompts_pad_left = CBool(True, config=True,
320 help="Deprecated, use PromptManager.justify")
327 help="Deprecated, use PromptManager.justify")
321
328
322 def _prompt_trait_changed(self, name, old, new):
329 def _prompt_trait_changed(self, name, old, new):
323 table = {
330 table = {
324 'prompt_in1' : 'in_template',
331 'prompt_in1' : 'in_template',
325 'prompt_in2' : 'in2_template',
332 'prompt_in2' : 'in2_template',
326 'prompt_out' : 'out_template',
333 'prompt_out' : 'out_template',
327 'prompts_pad_left' : 'justify',
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 name=name, newname=table[name])
337 name=name, newname=table[name])
331 )
338 )
332 # protect against weird cases where self.config may not exist:
339 # protect against weird cases where self.config may not exist:
333 if self.config is not None:
340 if self.config is not None:
334 # propagate to corresponding PromptManager trait
341 # propagate to corresponding PromptManager trait
335 setattr(self.config.PromptManager, table[name], new)
342 setattr(self.config.PromptManager, table[name], new)
336
343
337 _prompt_in1_changed = _prompt_trait_changed
344 _prompt_in1_changed = _prompt_trait_changed
338 _prompt_in2_changed = _prompt_trait_changed
345 _prompt_in2_changed = _prompt_trait_changed
339 _prompt_out_changed = _prompt_trait_changed
346 _prompt_out_changed = _prompt_trait_changed
340 _prompt_pad_left_changed = _prompt_trait_changed
347 _prompt_pad_left_changed = _prompt_trait_changed
341
348
342 show_rewritten_input = CBool(True, config=True,
349 show_rewritten_input = CBool(True, config=True,
343 help="Show rewritten input, e.g. for autocall."
350 help="Show rewritten input, e.g. for autocall."
344 )
351 )
345
352
346 quiet = CBool(False, config=True)
353 quiet = CBool(False, config=True)
347
354
348 history_length = Integer(10000, config=True)
355 history_length = Integer(10000, config=True)
349
356
350 # The readline stuff will eventually be moved to the terminal subclass
357 # The readline stuff will eventually be moved to the terminal subclass
351 # but for now, we can't do that as readline is welded in everywhere.
358 # but for now, we can't do that as readline is welded in everywhere.
352 readline_use = CBool(True, config=True)
359 readline_use = CBool(True, config=True)
353 readline_remove_delims = Unicode('-/~', config=True)
360 readline_remove_delims = Unicode('-/~', config=True)
354 # don't use \M- bindings by default, because they
361 # don't use \M- bindings by default, because they
355 # conflict with 8-bit encodings. See gh-58,gh-88
362 # conflict with 8-bit encodings. See gh-58,gh-88
356 readline_parse_and_bind = List([
363 readline_parse_and_bind = List([
357 'tab: complete',
364 'tab: complete',
358 '"\C-l": clear-screen',
365 '"\C-l": clear-screen',
359 'set show-all-if-ambiguous on',
366 'set show-all-if-ambiguous on',
360 '"\C-o": tab-insert',
367 '"\C-o": tab-insert',
361 '"\C-r": reverse-search-history',
368 '"\C-r": reverse-search-history',
362 '"\C-s": forward-search-history',
369 '"\C-s": forward-search-history',
363 '"\C-p": history-search-backward',
370 '"\C-p": history-search-backward',
364 '"\C-n": history-search-forward',
371 '"\C-n": history-search-forward',
365 '"\e[A": history-search-backward',
372 '"\e[A": history-search-backward',
366 '"\e[B": history-search-forward',
373 '"\e[B": history-search-forward',
367 '"\C-k": kill-line',
374 '"\C-k": kill-line',
368 '"\C-u": unix-line-discard',
375 '"\C-u": unix-line-discard',
369 ], allow_none=False, config=True)
376 ], allow_none=False, config=True)
370
377
371 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
378 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
372 default_value='last_expr', config=True,
379 default_value='last_expr', config=True,
373 help="""
380 help="""
374 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
381 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
375 run interactively (displaying output from expressions).""")
382 run interactively (displaying output from expressions).""")
376
383
377 # TODO: this part of prompt management should be moved to the frontends.
384 # TODO: this part of prompt management should be moved to the frontends.
378 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
385 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
379 separate_in = SeparateUnicode('\n', config=True)
386 separate_in = SeparateUnicode('\n', config=True)
380 separate_out = SeparateUnicode('', config=True)
387 separate_out = SeparateUnicode('', config=True)
381 separate_out2 = SeparateUnicode('', config=True)
388 separate_out2 = SeparateUnicode('', config=True)
382 wildcards_case_sensitive = CBool(True, config=True)
389 wildcards_case_sensitive = CBool(True, config=True)
383 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
390 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
384 default_value='Context', config=True)
391 default_value='Context', config=True)
385
392
386 # Subcomponents of InteractiveShell
393 # Subcomponents of InteractiveShell
387 alias_manager = Instance('IPython.core.alias.AliasManager')
394 alias_manager = Instance('IPython.core.alias.AliasManager')
388 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
395 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
389 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
396 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
390 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
397 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
391 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
398 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
392 payload_manager = Instance('IPython.core.payload.PayloadManager')
399 payload_manager = Instance('IPython.core.payload.PayloadManager')
393 history_manager = Instance('IPython.core.history.HistoryManager')
400 history_manager = Instance('IPython.core.history.HistoryManager')
394 magics_manager = Instance('IPython.core.magic.MagicsManager')
401 magics_manager = Instance('IPython.core.magic.MagicsManager')
395
402
396 profile_dir = Instance('IPython.core.application.ProfileDir')
403 profile_dir = Instance('IPython.core.application.ProfileDir')
397 @property
404 @property
398 def profile(self):
405 def profile(self):
399 if self.profile_dir is not None:
406 if self.profile_dir is not None:
400 name = os.path.basename(self.profile_dir.location)
407 name = os.path.basename(self.profile_dir.location)
401 return name.replace('profile_','')
408 return name.replace('profile_','')
402
409
403
410
404 # Private interface
411 # Private interface
405 _post_execute = Instance(dict)
412 _post_execute = Instance(dict)
406
413
407 # Tracks any GUI loop loaded for pylab
414 # Tracks any GUI loop loaded for pylab
408 pylab_gui_select = None
415 pylab_gui_select = None
409
416
410 def __init__(self, config=None, ipython_dir=None, profile_dir=None,
417 def __init__(self, config=None, ipython_dir=None, profile_dir=None,
411 user_module=None, user_ns=None,
418 user_module=None, user_ns=None,
412 custom_exceptions=((), None)):
419 custom_exceptions=((), None)):
413
420
414 # This is where traits with a config_key argument are updated
421 # This is where traits with a config_key argument are updated
415 # from the values on config.
422 # from the values on config.
416 super(InteractiveShell, self).__init__(config=config)
423 super(InteractiveShell, self).__init__(config=config)
417 self.configurables = [self]
424 self.configurables = [self]
418
425
419 # These are relatively independent and stateless
426 # These are relatively independent and stateless
420 self.init_ipython_dir(ipython_dir)
427 self.init_ipython_dir(ipython_dir)
421 self.init_profile_dir(profile_dir)
428 self.init_profile_dir(profile_dir)
422 self.init_instance_attrs()
429 self.init_instance_attrs()
423 self.init_environment()
430 self.init_environment()
424
431
425 # Check if we're in a virtualenv, and set up sys.path.
432 # Check if we're in a virtualenv, and set up sys.path.
426 self.init_virtualenv()
433 self.init_virtualenv()
427
434
428 # Create namespaces (user_ns, user_global_ns, etc.)
435 # Create namespaces (user_ns, user_global_ns, etc.)
429 self.init_create_namespaces(user_module, user_ns)
436 self.init_create_namespaces(user_module, user_ns)
430 # This has to be done after init_create_namespaces because it uses
437 # This has to be done after init_create_namespaces because it uses
431 # something in self.user_ns, but before init_sys_modules, which
438 # something in self.user_ns, but before init_sys_modules, which
432 # is the first thing to modify sys.
439 # is the first thing to modify sys.
433 # TODO: When we override sys.stdout and sys.stderr before this class
440 # TODO: When we override sys.stdout and sys.stderr before this class
434 # is created, we are saving the overridden ones here. Not sure if this
441 # is created, we are saving the overridden ones here. Not sure if this
435 # is what we want to do.
442 # is what we want to do.
436 self.save_sys_module_state()
443 self.save_sys_module_state()
437 self.init_sys_modules()
444 self.init_sys_modules()
438
445
439 # While we're trying to have each part of the code directly access what
446 # While we're trying to have each part of the code directly access what
440 # it needs without keeping redundant references to objects, we have too
447 # it needs without keeping redundant references to objects, we have too
441 # much legacy code that expects ip.db to exist.
448 # much legacy code that expects ip.db to exist.
442 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
449 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
443
450
444 self.init_history()
451 self.init_history()
445 self.init_encoding()
452 self.init_encoding()
446 self.init_prefilter()
453 self.init_prefilter()
447
454
448 self.init_syntax_highlighting()
455 self.init_syntax_highlighting()
449 self.init_hooks()
456 self.init_hooks()
450 self.init_pushd_popd_magic()
457 self.init_pushd_popd_magic()
451 # self.init_traceback_handlers use to be here, but we moved it below
458 # self.init_traceback_handlers use to be here, but we moved it below
452 # because it and init_io have to come after init_readline.
459 # because it and init_io have to come after init_readline.
453 self.init_user_ns()
460 self.init_user_ns()
454 self.init_logger()
461 self.init_logger()
455 self.init_alias()
462 self.init_alias()
456 self.init_builtins()
463 self.init_builtins()
457
464
458 # The following was in post_config_initialization
465 # The following was in post_config_initialization
459 self.init_inspector()
466 self.init_inspector()
460 # init_readline() must come before init_io(), because init_io uses
467 # init_readline() must come before init_io(), because init_io uses
461 # readline related things.
468 # readline related things.
462 self.init_readline()
469 self.init_readline()
463 # We save this here in case user code replaces raw_input, but it needs
470 # We save this here in case user code replaces raw_input, but it needs
464 # to be after init_readline(), because PyPy's readline works by replacing
471 # to be after init_readline(), because PyPy's readline works by replacing
465 # raw_input.
472 # raw_input.
466 if py3compat.PY3:
473 if py3compat.PY3:
467 self.raw_input_original = input
474 self.raw_input_original = input
468 else:
475 else:
469 self.raw_input_original = raw_input
476 self.raw_input_original = raw_input
470 # init_completer must come after init_readline, because it needs to
477 # init_completer must come after init_readline, because it needs to
471 # know whether readline is present or not system-wide to configure the
478 # know whether readline is present or not system-wide to configure the
472 # completers, since the completion machinery can now operate
479 # completers, since the completion machinery can now operate
473 # independently of readline (e.g. over the network)
480 # independently of readline (e.g. over the network)
474 self.init_completer()
481 self.init_completer()
475 # TODO: init_io() needs to happen before init_traceback handlers
482 # TODO: init_io() needs to happen before init_traceback handlers
476 # because the traceback handlers hardcode the stdout/stderr streams.
483 # because the traceback handlers hardcode the stdout/stderr streams.
477 # This logic in in debugger.Pdb and should eventually be changed.
484 # This logic in in debugger.Pdb and should eventually be changed.
478 self.init_io()
485 self.init_io()
479 self.init_traceback_handlers(custom_exceptions)
486 self.init_traceback_handlers(custom_exceptions)
480 self.init_prompts()
487 self.init_prompts()
481 self.init_display_formatter()
488 self.init_display_formatter()
482 self.init_display_pub()
489 self.init_display_pub()
483 self.init_data_pub()
490 self.init_data_pub()
484 self.init_displayhook()
491 self.init_displayhook()
485 self.init_reload_doctest()
492 self.init_reload_doctest()
486 self.init_latextool()
493 self.init_latextool()
487 self.init_magics()
494 self.init_magics()
488 self.init_logstart()
495 self.init_logstart()
489 self.init_pdb()
496 self.init_pdb()
490 self.init_extension_manager()
497 self.init_extension_manager()
491 self.init_payload()
498 self.init_payload()
492 self.hooks.late_startup_hook()
499 self.hooks.late_startup_hook()
493 atexit.register(self.atexit_operations)
500 atexit.register(self.atexit_operations)
494
501
495 def get_ipython(self):
502 def get_ipython(self):
496 """Return the currently running IPython instance."""
503 """Return the currently running IPython instance."""
497 return self
504 return self
498
505
499 #-------------------------------------------------------------------------
506 #-------------------------------------------------------------------------
500 # Trait changed handlers
507 # Trait changed handlers
501 #-------------------------------------------------------------------------
508 #-------------------------------------------------------------------------
502
509
503 def _ipython_dir_changed(self, name, new):
510 def _ipython_dir_changed(self, name, new):
504 if not os.path.isdir(new):
511 if not os.path.isdir(new):
505 os.makedirs(new, mode = 0o777)
512 os.makedirs(new, mode = 0o777)
506
513
507 def set_autoindent(self,value=None):
514 def set_autoindent(self,value=None):
508 """Set the autoindent flag, checking for readline support.
515 """Set the autoindent flag, checking for readline support.
509
516
510 If called with no arguments, it acts as a toggle."""
517 If called with no arguments, it acts as a toggle."""
511
518
512 if value != 0 and not self.has_readline:
519 if value != 0 and not self.has_readline:
513 if os.name == 'posix':
520 if os.name == 'posix':
514 warn("The auto-indent feature requires the readline library")
521 warn("The auto-indent feature requires the readline library")
515 self.autoindent = 0
522 self.autoindent = 0
516 return
523 return
517 if value is None:
524 if value is None:
518 self.autoindent = not self.autoindent
525 self.autoindent = not self.autoindent
519 else:
526 else:
520 self.autoindent = value
527 self.autoindent = value
521
528
522 #-------------------------------------------------------------------------
529 #-------------------------------------------------------------------------
523 # init_* methods called by __init__
530 # init_* methods called by __init__
524 #-------------------------------------------------------------------------
531 #-------------------------------------------------------------------------
525
532
526 def init_ipython_dir(self, ipython_dir):
533 def init_ipython_dir(self, ipython_dir):
527 if ipython_dir is not None:
534 if ipython_dir is not None:
528 self.ipython_dir = ipython_dir
535 self.ipython_dir = ipython_dir
529 return
536 return
530
537
531 self.ipython_dir = get_ipython_dir()
538 self.ipython_dir = get_ipython_dir()
532
539
533 def init_profile_dir(self, profile_dir):
540 def init_profile_dir(self, profile_dir):
534 if profile_dir is not None:
541 if profile_dir is not None:
535 self.profile_dir = profile_dir
542 self.profile_dir = profile_dir
536 return
543 return
537 self.profile_dir =\
544 self.profile_dir =\
538 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
545 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
539
546
540 def init_instance_attrs(self):
547 def init_instance_attrs(self):
541 self.more = False
548 self.more = False
542
549
543 # command compiler
550 # command compiler
544 self.compile = CachingCompiler()
551 self.compile = CachingCompiler()
545
552
546 # Make an empty namespace, which extension writers can rely on both
553 # Make an empty namespace, which extension writers can rely on both
547 # existing and NEVER being used by ipython itself. This gives them a
554 # existing and NEVER being used by ipython itself. This gives them a
548 # convenient location for storing additional information and state
555 # convenient location for storing additional information and state
549 # their extensions may require, without fear of collisions with other
556 # their extensions may require, without fear of collisions with other
550 # ipython names that may develop later.
557 # ipython names that may develop later.
551 self.meta = Struct()
558 self.meta = Struct()
552
559
553 # Temporary files used for various purposes. Deleted at exit.
560 # Temporary files used for various purposes. Deleted at exit.
554 self.tempfiles = []
561 self.tempfiles = []
555
562
556 # Keep track of readline usage (later set by init_readline)
563 # Keep track of readline usage (later set by init_readline)
557 self.has_readline = False
564 self.has_readline = False
558
565
559 # keep track of where we started running (mainly for crash post-mortem)
566 # keep track of where we started running (mainly for crash post-mortem)
560 # This is not being used anywhere currently.
567 # This is not being used anywhere currently.
561 self.starting_dir = os.getcwdu()
568 self.starting_dir = os.getcwdu()
562
569
563 # Indentation management
570 # Indentation management
564 self.indent_current_nsp = 0
571 self.indent_current_nsp = 0
565
572
566 # Dict to track post-execution functions that have been registered
573 # Dict to track post-execution functions that have been registered
567 self._post_execute = {}
574 self._post_execute = {}
568
575
569 def init_environment(self):
576 def init_environment(self):
570 """Any changes we need to make to the user's environment."""
577 """Any changes we need to make to the user's environment."""
571 pass
578 pass
572
579
573 def init_encoding(self):
580 def init_encoding(self):
574 # Get system encoding at startup time. Certain terminals (like Emacs
581 # Get system encoding at startup time. Certain terminals (like Emacs
575 # under Win32 have it set to None, and we need to have a known valid
582 # under Win32 have it set to None, and we need to have a known valid
576 # encoding to use in the raw_input() method
583 # encoding to use in the raw_input() method
577 try:
584 try:
578 self.stdin_encoding = sys.stdin.encoding or 'ascii'
585 self.stdin_encoding = sys.stdin.encoding or 'ascii'
579 except AttributeError:
586 except AttributeError:
580 self.stdin_encoding = 'ascii'
587 self.stdin_encoding = 'ascii'
581
588
582 def init_syntax_highlighting(self):
589 def init_syntax_highlighting(self):
583 # Python source parser/formatter for syntax highlighting
590 # Python source parser/formatter for syntax highlighting
584 pyformat = PyColorize.Parser().format
591 pyformat = PyColorize.Parser().format
585 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
592 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
586
593
587 def init_pushd_popd_magic(self):
594 def init_pushd_popd_magic(self):
588 # for pushd/popd management
595 # for pushd/popd management
589 self.home_dir = get_home_dir()
596 self.home_dir = get_home_dir()
590
597
591 self.dir_stack = []
598 self.dir_stack = []
592
599
593 def init_logger(self):
600 def init_logger(self):
594 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
601 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
595 logmode='rotate')
602 logmode='rotate')
596
603
597 def init_logstart(self):
604 def init_logstart(self):
598 """Initialize logging in case it was requested at the command line.
605 """Initialize logging in case it was requested at the command line.
599 """
606 """
600 if self.logappend:
607 if self.logappend:
601 self.magic('logstart %s append' % self.logappend)
608 self.magic('logstart %s append' % self.logappend)
602 elif self.logfile:
609 elif self.logfile:
603 self.magic('logstart %s' % self.logfile)
610 self.magic('logstart %s' % self.logfile)
604 elif self.logstart:
611 elif self.logstart:
605 self.magic('logstart')
612 self.magic('logstart')
606
613
607 def init_builtins(self):
614 def init_builtins(self):
608 # A single, static flag that we set to True. Its presence indicates
615 # A single, static flag that we set to True. Its presence indicates
609 # that an IPython shell has been created, and we make no attempts at
616 # that an IPython shell has been created, and we make no attempts at
610 # removing on exit or representing the existence of more than one
617 # removing on exit or representing the existence of more than one
611 # IPython at a time.
618 # IPython at a time.
612 builtin_mod.__dict__['__IPYTHON__'] = True
619 builtin_mod.__dict__['__IPYTHON__'] = True
613
620
614 # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to
621 # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to
615 # manage on enter/exit, but with all our shells it's virtually
622 # manage on enter/exit, but with all our shells it's virtually
616 # impossible to get all the cases right. We're leaving the name in for
623 # impossible to get all the cases right. We're leaving the name in for
617 # those who adapted their codes to check for this flag, but will
624 # those who adapted their codes to check for this flag, but will
618 # eventually remove it after a few more releases.
625 # eventually remove it after a few more releases.
619 builtin_mod.__dict__['__IPYTHON__active'] = \
626 builtin_mod.__dict__['__IPYTHON__active'] = \
620 'Deprecated, check for __IPYTHON__'
627 'Deprecated, check for __IPYTHON__'
621
628
622 self.builtin_trap = BuiltinTrap(shell=self)
629 self.builtin_trap = BuiltinTrap(shell=self)
623
630
624 def init_inspector(self):
631 def init_inspector(self):
625 # Object inspector
632 # Object inspector
626 self.inspector = oinspect.Inspector(oinspect.InspectColors,
633 self.inspector = oinspect.Inspector(oinspect.InspectColors,
627 PyColorize.ANSICodeColors,
634 PyColorize.ANSICodeColors,
628 'NoColor',
635 'NoColor',
629 self.object_info_string_level)
636 self.object_info_string_level)
630
637
631 def init_io(self):
638 def init_io(self):
632 # This will just use sys.stdout and sys.stderr. If you want to
639 # This will just use sys.stdout and sys.stderr. If you want to
633 # override sys.stdout and sys.stderr themselves, you need to do that
640 # override sys.stdout and sys.stderr themselves, you need to do that
634 # *before* instantiating this class, because io holds onto
641 # *before* instantiating this class, because io holds onto
635 # references to the underlying streams.
642 # references to the underlying streams.
636 if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline:
643 if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline:
637 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
644 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
638 else:
645 else:
639 io.stdout = io.IOStream(sys.stdout)
646 io.stdout = io.IOStream(sys.stdout)
640 io.stderr = io.IOStream(sys.stderr)
647 io.stderr = io.IOStream(sys.stderr)
641
648
642 def init_prompts(self):
649 def init_prompts(self):
643 self.prompt_manager = PromptManager(shell=self, config=self.config)
650 self.prompt_manager = PromptManager(shell=self, config=self.config)
644 self.configurables.append(self.prompt_manager)
651 self.configurables.append(self.prompt_manager)
645 # Set system prompts, so that scripts can decide if they are running
652 # Set system prompts, so that scripts can decide if they are running
646 # interactively.
653 # interactively.
647 sys.ps1 = 'In : '
654 sys.ps1 = 'In : '
648 sys.ps2 = '...: '
655 sys.ps2 = '...: '
649 sys.ps3 = 'Out: '
656 sys.ps3 = 'Out: '
650
657
651 def init_display_formatter(self):
658 def init_display_formatter(self):
652 self.display_formatter = DisplayFormatter(config=self.config)
659 self.display_formatter = DisplayFormatter(config=self.config)
653 self.configurables.append(self.display_formatter)
660 self.configurables.append(self.display_formatter)
654
661
655 def init_display_pub(self):
662 def init_display_pub(self):
656 self.display_pub = self.display_pub_class(config=self.config)
663 self.display_pub = self.display_pub_class(config=self.config)
657 self.configurables.append(self.display_pub)
664 self.configurables.append(self.display_pub)
658
665
659 def init_data_pub(self):
666 def init_data_pub(self):
660 if not self.data_pub_class:
667 if not self.data_pub_class:
661 self.data_pub = None
668 self.data_pub = None
662 return
669 return
663 self.data_pub = self.data_pub_class(config=self.config)
670 self.data_pub = self.data_pub_class(config=self.config)
664 self.configurables.append(self.data_pub)
671 self.configurables.append(self.data_pub)
665
672
666 def init_displayhook(self):
673 def init_displayhook(self):
667 # Initialize displayhook, set in/out prompts and printing system
674 # Initialize displayhook, set in/out prompts and printing system
668 self.displayhook = self.displayhook_class(
675 self.displayhook = self.displayhook_class(
669 config=self.config,
676 config=self.config,
670 shell=self,
677 shell=self,
671 cache_size=self.cache_size,
678 cache_size=self.cache_size,
672 )
679 )
673 self.configurables.append(self.displayhook)
680 self.configurables.append(self.displayhook)
674 # This is a context manager that installs/revmoes the displayhook at
681 # This is a context manager that installs/revmoes the displayhook at
675 # the appropriate time.
682 # the appropriate time.
676 self.display_trap = DisplayTrap(hook=self.displayhook)
683 self.display_trap = DisplayTrap(hook=self.displayhook)
677
684
678 def init_reload_doctest(self):
685 def init_reload_doctest(self):
679 # Do a proper resetting of doctest, including the necessary displayhook
686 # Do a proper resetting of doctest, including the necessary displayhook
680 # monkeypatching
687 # monkeypatching
681 try:
688 try:
682 doctest_reload()
689 doctest_reload()
683 except ImportError:
690 except ImportError:
684 warn("doctest module does not exist.")
691 warn("doctest module does not exist.")
685
692
686 def init_latextool(self):
693 def init_latextool(self):
687 """Configure LaTeXTool."""
694 """Configure LaTeXTool."""
688 cfg = LaTeXTool.instance(config=self.config)
695 cfg = LaTeXTool.instance(config=self.config)
689 if cfg not in self.configurables:
696 if cfg not in self.configurables:
690 self.configurables.append(cfg)
697 self.configurables.append(cfg)
691
698
692 def init_virtualenv(self):
699 def init_virtualenv(self):
693 """Add a virtualenv to sys.path so the user can import modules from it.
700 """Add a virtualenv to sys.path so the user can import modules from it.
694 This isn't perfect: it doesn't use the Python interpreter with which the
701 This isn't perfect: it doesn't use the Python interpreter with which the
695 virtualenv was built, and it ignores the --no-site-packages option. A
702 virtualenv was built, and it ignores the --no-site-packages option. A
696 warning will appear suggesting the user installs IPython in the
703 warning will appear suggesting the user installs IPython in the
697 virtualenv, but for many cases, it probably works well enough.
704 virtualenv, but for many cases, it probably works well enough.
698
705
699 Adapted from code snippets online.
706 Adapted from code snippets online.
700
707
701 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
708 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
702 """
709 """
703 if 'VIRTUAL_ENV' not in os.environ:
710 if 'VIRTUAL_ENV' not in os.environ:
704 # Not in a virtualenv
711 # Not in a virtualenv
705 return
712 return
706
713
707 if sys.executable.startswith(os.environ['VIRTUAL_ENV']):
714 if sys.executable.startswith(os.environ['VIRTUAL_ENV']):
708 # Running properly in the virtualenv, don't need to do anything
715 # Running properly in the virtualenv, don't need to do anything
709 return
716 return
710
717
711 warn("Attempting to work in a virtualenv. If you encounter problems, please "
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 if sys.platform == "win32":
720 if sys.platform == "win32":
714 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
721 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
715 else:
722 else:
716 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
723 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
717 'python%d.%d' % sys.version_info[:2], 'site-packages')
724 'python%d.%d' % sys.version_info[:2], 'site-packages')
718
725
719 import site
726 import site
720 sys.path.insert(0, virtual_env)
727 sys.path.insert(0, virtual_env)
721 site.addsitedir(virtual_env)
728 site.addsitedir(virtual_env)
722
729
723 #-------------------------------------------------------------------------
730 #-------------------------------------------------------------------------
724 # Things related to injections into the sys module
731 # Things related to injections into the sys module
725 #-------------------------------------------------------------------------
732 #-------------------------------------------------------------------------
726
733
727 def save_sys_module_state(self):
734 def save_sys_module_state(self):
728 """Save the state of hooks in the sys module.
735 """Save the state of hooks in the sys module.
729
736
730 This has to be called after self.user_module is created.
737 This has to be called after self.user_module is created.
731 """
738 """
732 self._orig_sys_module_state = {}
739 self._orig_sys_module_state = {}
733 self._orig_sys_module_state['stdin'] = sys.stdin
740 self._orig_sys_module_state['stdin'] = sys.stdin
734 self._orig_sys_module_state['stdout'] = sys.stdout
741 self._orig_sys_module_state['stdout'] = sys.stdout
735 self._orig_sys_module_state['stderr'] = sys.stderr
742 self._orig_sys_module_state['stderr'] = sys.stderr
736 self._orig_sys_module_state['excepthook'] = sys.excepthook
743 self._orig_sys_module_state['excepthook'] = sys.excepthook
737 self._orig_sys_modules_main_name = self.user_module.__name__
744 self._orig_sys_modules_main_name = self.user_module.__name__
738 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
745 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
739
746
740 def restore_sys_module_state(self):
747 def restore_sys_module_state(self):
741 """Restore the state of the sys module."""
748 """Restore the state of the sys module."""
742 try:
749 try:
743 for k, v in self._orig_sys_module_state.iteritems():
750 for k, v in self._orig_sys_module_state.iteritems():
744 setattr(sys, k, v)
751 setattr(sys, k, v)
745 except AttributeError:
752 except AttributeError:
746 pass
753 pass
747 # Reset what what done in self.init_sys_modules
754 # Reset what what done in self.init_sys_modules
748 if self._orig_sys_modules_main_mod is not None:
755 if self._orig_sys_modules_main_mod is not None:
749 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
756 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
750
757
751 #-------------------------------------------------------------------------
758 #-------------------------------------------------------------------------
752 # Things related to hooks
759 # Things related to hooks
753 #-------------------------------------------------------------------------
760 #-------------------------------------------------------------------------
754
761
755 def init_hooks(self):
762 def init_hooks(self):
756 # hooks holds pointers used for user-side customizations
763 # hooks holds pointers used for user-side customizations
757 self.hooks = Struct()
764 self.hooks = Struct()
758
765
759 self.strdispatchers = {}
766 self.strdispatchers = {}
760
767
761 # Set all default hooks, defined in the IPython.hooks module.
768 # Set all default hooks, defined in the IPython.hooks module.
762 hooks = IPython.core.hooks
769 hooks = IPython.core.hooks
763 for hook_name in hooks.__all__:
770 for hook_name in hooks.__all__:
764 # default hooks have priority 100, i.e. low; user hooks should have
771 # default hooks have priority 100, i.e. low; user hooks should have
765 # 0-100 priority
772 # 0-100 priority
766 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
773 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
767
774
768 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
775 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
769 """set_hook(name,hook) -> sets an internal IPython hook.
776 """set_hook(name,hook) -> sets an internal IPython hook.
770
777
771 IPython exposes some of its internal API as user-modifiable hooks. By
778 IPython exposes some of its internal API as user-modifiable hooks. By
772 adding your function to one of these hooks, you can modify IPython's
779 adding your function to one of these hooks, you can modify IPython's
773 behavior to call at runtime your own routines."""
780 behavior to call at runtime your own routines."""
774
781
775 # At some point in the future, this should validate the hook before it
782 # At some point in the future, this should validate the hook before it
776 # accepts it. Probably at least check that the hook takes the number
783 # accepts it. Probably at least check that the hook takes the number
777 # of args it's supposed to.
784 # of args it's supposed to.
778
785
779 f = types.MethodType(hook,self)
786 f = types.MethodType(hook,self)
780
787
781 # check if the hook is for strdispatcher first
788 # check if the hook is for strdispatcher first
782 if str_key is not None:
789 if str_key is not None:
783 sdp = self.strdispatchers.get(name, StrDispatch())
790 sdp = self.strdispatchers.get(name, StrDispatch())
784 sdp.add_s(str_key, f, priority )
791 sdp.add_s(str_key, f, priority )
785 self.strdispatchers[name] = sdp
792 self.strdispatchers[name] = sdp
786 return
793 return
787 if re_key is not None:
794 if re_key is not None:
788 sdp = self.strdispatchers.get(name, StrDispatch())
795 sdp = self.strdispatchers.get(name, StrDispatch())
789 sdp.add_re(re.compile(re_key), f, priority )
796 sdp.add_re(re.compile(re_key), f, priority )
790 self.strdispatchers[name] = sdp
797 self.strdispatchers[name] = sdp
791 return
798 return
792
799
793 dp = getattr(self.hooks, name, None)
800 dp = getattr(self.hooks, name, None)
794 if name not in IPython.core.hooks.__all__:
801 if name not in IPython.core.hooks.__all__:
795 print("Warning! Hook '%s' is not one of %s" % \
802 print("Warning! Hook '%s' is not one of %s" % \
796 (name, IPython.core.hooks.__all__ ))
803 (name, IPython.core.hooks.__all__ ))
797 if not dp:
804 if not dp:
798 dp = IPython.core.hooks.CommandChainDispatcher()
805 dp = IPython.core.hooks.CommandChainDispatcher()
799
806
800 try:
807 try:
801 dp.add(f,priority)
808 dp.add(f,priority)
802 except AttributeError:
809 except AttributeError:
803 # it was not commandchain, plain old func - replace
810 # it was not commandchain, plain old func - replace
804 dp = f
811 dp = f
805
812
806 setattr(self.hooks,name, dp)
813 setattr(self.hooks,name, dp)
807
814
808 def register_post_execute(self, func):
815 def register_post_execute(self, func):
809 """Register a function for calling after code execution.
816 """Register a function for calling after code execution.
810 """
817 """
811 if not callable(func):
818 if not callable(func):
812 raise ValueError('argument %s must be callable' % func)
819 raise ValueError('argument %s must be callable' % func)
813 self._post_execute[func] = True
820 self._post_execute[func] = True
814
821
815 #-------------------------------------------------------------------------
822 #-------------------------------------------------------------------------
816 # Things related to the "main" module
823 # Things related to the "main" module
817 #-------------------------------------------------------------------------
824 #-------------------------------------------------------------------------
818
825
819 def new_main_mod(self,ns=None):
826 def new_main_mod(self,ns=None):
820 """Return a new 'main' module object for user code execution.
827 """Return a new 'main' module object for user code execution.
821 """
828 """
822 main_mod = self._user_main_module
829 main_mod = self._user_main_module
823 init_fakemod_dict(main_mod,ns)
830 init_fakemod_dict(main_mod,ns)
824 return main_mod
831 return main_mod
825
832
826 def cache_main_mod(self,ns,fname):
833 def cache_main_mod(self,ns,fname):
827 """Cache a main module's namespace.
834 """Cache a main module's namespace.
828
835
829 When scripts are executed via %run, we must keep a reference to the
836 When scripts are executed via %run, we must keep a reference to the
830 namespace of their __main__ module (a FakeModule instance) around so
837 namespace of their __main__ module (a FakeModule instance) around so
831 that Python doesn't clear it, rendering objects defined therein
838 that Python doesn't clear it, rendering objects defined therein
832 useless.
839 useless.
833
840
834 This method keeps said reference in a private dict, keyed by the
841 This method keeps said reference in a private dict, keyed by the
835 absolute path of the module object (which corresponds to the script
842 absolute path of the module object (which corresponds to the script
836 path). This way, for multiple executions of the same script we only
843 path). This way, for multiple executions of the same script we only
837 keep one copy of the namespace (the last one), thus preventing memory
844 keep one copy of the namespace (the last one), thus preventing memory
838 leaks from old references while allowing the objects from the last
845 leaks from old references while allowing the objects from the last
839 execution to be accessible.
846 execution to be accessible.
840
847
841 Note: we can not allow the actual FakeModule instances to be deleted,
848 Note: we can not allow the actual FakeModule instances to be deleted,
842 because of how Python tears down modules (it hard-sets all their
849 because of how Python tears down modules (it hard-sets all their
843 references to None without regard for reference counts). This method
850 references to None without regard for reference counts). This method
844 must therefore make a *copy* of the given namespace, to allow the
851 must therefore make a *copy* of the given namespace, to allow the
845 original module's __dict__ to be cleared and reused.
852 original module's __dict__ to be cleared and reused.
846
853
847
854
848 Parameters
855 Parameters
849 ----------
856 ----------
850 ns : a namespace (a dict, typically)
857 ns : a namespace (a dict, typically)
851
858
852 fname : str
859 fname : str
853 Filename associated with the namespace.
860 Filename associated with the namespace.
854
861
855 Examples
862 Examples
856 --------
863 --------
857
864
858 In [10]: import IPython
865 In [10]: import IPython
859
866
860 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
867 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
861
868
862 In [12]: IPython.__file__ in _ip._main_ns_cache
869 In [12]: IPython.__file__ in _ip._main_ns_cache
863 Out[12]: True
870 Out[12]: True
864 """
871 """
865 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
872 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
866
873
867 def clear_main_mod_cache(self):
874 def clear_main_mod_cache(self):
868 """Clear the cache of main modules.
875 """Clear the cache of main modules.
869
876
870 Mainly for use by utilities like %reset.
877 Mainly for use by utilities like %reset.
871
878
872 Examples
879 Examples
873 --------
880 --------
874
881
875 In [15]: import IPython
882 In [15]: import IPython
876
883
877 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
884 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
878
885
879 In [17]: len(_ip._main_ns_cache) > 0
886 In [17]: len(_ip._main_ns_cache) > 0
880 Out[17]: True
887 Out[17]: True
881
888
882 In [18]: _ip.clear_main_mod_cache()
889 In [18]: _ip.clear_main_mod_cache()
883
890
884 In [19]: len(_ip._main_ns_cache) == 0
891 In [19]: len(_ip._main_ns_cache) == 0
885 Out[19]: True
892 Out[19]: True
886 """
893 """
887 self._main_ns_cache.clear()
894 self._main_ns_cache.clear()
888
895
889 #-------------------------------------------------------------------------
896 #-------------------------------------------------------------------------
890 # Things related to debugging
897 # Things related to debugging
891 #-------------------------------------------------------------------------
898 #-------------------------------------------------------------------------
892
899
893 def init_pdb(self):
900 def init_pdb(self):
894 # Set calling of pdb on exceptions
901 # Set calling of pdb on exceptions
895 # self.call_pdb is a property
902 # self.call_pdb is a property
896 self.call_pdb = self.pdb
903 self.call_pdb = self.pdb
897
904
898 def _get_call_pdb(self):
905 def _get_call_pdb(self):
899 return self._call_pdb
906 return self._call_pdb
900
907
901 def _set_call_pdb(self,val):
908 def _set_call_pdb(self,val):
902
909
903 if val not in (0,1,False,True):
910 if val not in (0,1,False,True):
904 raise ValueError('new call_pdb value must be boolean')
911 raise ValueError('new call_pdb value must be boolean')
905
912
906 # store value in instance
913 # store value in instance
907 self._call_pdb = val
914 self._call_pdb = val
908
915
909 # notify the actual exception handlers
916 # notify the actual exception handlers
910 self.InteractiveTB.call_pdb = val
917 self.InteractiveTB.call_pdb = val
911
918
912 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
919 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
913 'Control auto-activation of pdb at exceptions')
920 'Control auto-activation of pdb at exceptions')
914
921
915 def debugger(self,force=False):
922 def debugger(self,force=False):
916 """Call the pydb/pdb debugger.
923 """Call the pydb/pdb debugger.
917
924
918 Keywords:
925 Keywords:
919
926
920 - force(False): by default, this routine checks the instance call_pdb
927 - force(False): by default, this routine checks the instance call_pdb
921 flag and does not actually invoke the debugger if the flag is false.
928 flag and does not actually invoke the debugger if the flag is false.
922 The 'force' option forces the debugger to activate even if the flag
929 The 'force' option forces the debugger to activate even if the flag
923 is false.
930 is false.
924 """
931 """
925
932
926 if not (force or self.call_pdb):
933 if not (force or self.call_pdb):
927 return
934 return
928
935
929 if not hasattr(sys,'last_traceback'):
936 if not hasattr(sys,'last_traceback'):
930 error('No traceback has been produced, nothing to debug.')
937 error('No traceback has been produced, nothing to debug.')
931 return
938 return
932
939
933 # use pydb if available
940 # use pydb if available
934 if debugger.has_pydb:
941 if debugger.has_pydb:
935 from pydb import pm
942 from pydb import pm
936 else:
943 else:
937 # fallback to our internal debugger
944 # fallback to our internal debugger
938 pm = lambda : self.InteractiveTB.debugger(force=True)
945 pm = lambda : self.InteractiveTB.debugger(force=True)
939
946
940 with self.readline_no_record:
947 with self.readline_no_record:
941 pm()
948 pm()
942
949
943 #-------------------------------------------------------------------------
950 #-------------------------------------------------------------------------
944 # Things related to IPython's various namespaces
951 # Things related to IPython's various namespaces
945 #-------------------------------------------------------------------------
952 #-------------------------------------------------------------------------
946 default_user_namespaces = True
953 default_user_namespaces = True
947
954
948 def init_create_namespaces(self, user_module=None, user_ns=None):
955 def init_create_namespaces(self, user_module=None, user_ns=None):
949 # Create the namespace where the user will operate. user_ns is
956 # Create the namespace where the user will operate. user_ns is
950 # normally the only one used, and it is passed to the exec calls as
957 # normally the only one used, and it is passed to the exec calls as
951 # the locals argument. But we do carry a user_global_ns namespace
958 # the locals argument. But we do carry a user_global_ns namespace
952 # given as the exec 'globals' argument, This is useful in embedding
959 # given as the exec 'globals' argument, This is useful in embedding
953 # situations where the ipython shell opens in a context where the
960 # situations where the ipython shell opens in a context where the
954 # distinction between locals and globals is meaningful. For
961 # distinction between locals and globals is meaningful. For
955 # non-embedded contexts, it is just the same object as the user_ns dict.
962 # non-embedded contexts, it is just the same object as the user_ns dict.
956
963
957 # FIXME. For some strange reason, __builtins__ is showing up at user
964 # FIXME. For some strange reason, __builtins__ is showing up at user
958 # level as a dict instead of a module. This is a manual fix, but I
965 # level as a dict instead of a module. This is a manual fix, but I
959 # should really track down where the problem is coming from. Alex
966 # should really track down where the problem is coming from. Alex
960 # Schmolck reported this problem first.
967 # Schmolck reported this problem first.
961
968
962 # A useful post by Alex Martelli on this topic:
969 # A useful post by Alex Martelli on this topic:
963 # Re: inconsistent value from __builtins__
970 # Re: inconsistent value from __builtins__
964 # Von: Alex Martelli <aleaxit@yahoo.com>
971 # Von: Alex Martelli <aleaxit@yahoo.com>
965 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
972 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
966 # Gruppen: comp.lang.python
973 # Gruppen: comp.lang.python
967
974
968 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
975 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
969 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
976 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
970 # > <type 'dict'>
977 # > <type 'dict'>
971 # > >>> print type(__builtins__)
978 # > >>> print type(__builtins__)
972 # > <type 'module'>
979 # > <type 'module'>
973 # > Is this difference in return value intentional?
980 # > Is this difference in return value intentional?
974
981
975 # Well, it's documented that '__builtins__' can be either a dictionary
982 # Well, it's documented that '__builtins__' can be either a dictionary
976 # or a module, and it's been that way for a long time. Whether it's
983 # or a module, and it's been that way for a long time. Whether it's
977 # intentional (or sensible), I don't know. In any case, the idea is
984 # intentional (or sensible), I don't know. In any case, the idea is
978 # that if you need to access the built-in namespace directly, you
985 # that if you need to access the built-in namespace directly, you
979 # should start with "import __builtin__" (note, no 's') which will
986 # should start with "import __builtin__" (note, no 's') which will
980 # definitely give you a module. Yeah, it's somewhat confusing:-(.
987 # definitely give you a module. Yeah, it's somewhat confusing:-(.
981
988
982 # These routines return a properly built module and dict as needed by
989 # These routines return a properly built module and dict as needed by
983 # the rest of the code, and can also be used by extension writers to
990 # the rest of the code, and can also be used by extension writers to
984 # generate properly initialized namespaces.
991 # generate properly initialized namespaces.
985 if (user_ns is not None) or (user_module is not None):
992 if (user_ns is not None) or (user_module is not None):
986 self.default_user_namespaces = False
993 self.default_user_namespaces = False
987 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
994 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
988
995
989 # A record of hidden variables we have added to the user namespace, so
996 # A record of hidden variables we have added to the user namespace, so
990 # we can list later only variables defined in actual interactive use.
997 # we can list later only variables defined in actual interactive use.
991 self.user_ns_hidden = set()
998 self.user_ns_hidden = set()
992
999
993 # Now that FakeModule produces a real module, we've run into a nasty
1000 # Now that FakeModule produces a real module, we've run into a nasty
994 # problem: after script execution (via %run), the module where the user
1001 # problem: after script execution (via %run), the module where the user
995 # code ran is deleted. Now that this object is a true module (needed
1002 # code ran is deleted. Now that this object is a true module (needed
996 # so docetst and other tools work correctly), the Python module
1003 # so docetst and other tools work correctly), the Python module
997 # teardown mechanism runs over it, and sets to None every variable
1004 # teardown mechanism runs over it, and sets to None every variable
998 # present in that module. Top-level references to objects from the
1005 # present in that module. Top-level references to objects from the
999 # script survive, because the user_ns is updated with them. However,
1006 # script survive, because the user_ns is updated with them. However,
1000 # calling functions defined in the script that use other things from
1007 # calling functions defined in the script that use other things from
1001 # the script will fail, because the function's closure had references
1008 # the script will fail, because the function's closure had references
1002 # to the original objects, which are now all None. So we must protect
1009 # to the original objects, which are now all None. So we must protect
1003 # these modules from deletion by keeping a cache.
1010 # these modules from deletion by keeping a cache.
1004 #
1011 #
1005 # To avoid keeping stale modules around (we only need the one from the
1012 # To avoid keeping stale modules around (we only need the one from the
1006 # last run), we use a dict keyed with the full path to the script, so
1013 # last run), we use a dict keyed with the full path to the script, so
1007 # only the last version of the module is held in the cache. Note,
1014 # only the last version of the module is held in the cache. Note,
1008 # however, that we must cache the module *namespace contents* (their
1015 # however, that we must cache the module *namespace contents* (their
1009 # __dict__). Because if we try to cache the actual modules, old ones
1016 # __dict__). Because if we try to cache the actual modules, old ones
1010 # (uncached) could be destroyed while still holding references (such as
1017 # (uncached) could be destroyed while still holding references (such as
1011 # those held by GUI objects that tend to be long-lived)>
1018 # those held by GUI objects that tend to be long-lived)>
1012 #
1019 #
1013 # The %reset command will flush this cache. See the cache_main_mod()
1020 # The %reset command will flush this cache. See the cache_main_mod()
1014 # and clear_main_mod_cache() methods for details on use.
1021 # and clear_main_mod_cache() methods for details on use.
1015
1022
1016 # This is the cache used for 'main' namespaces
1023 # This is the cache used for 'main' namespaces
1017 self._main_ns_cache = {}
1024 self._main_ns_cache = {}
1018 # And this is the single instance of FakeModule whose __dict__ we keep
1025 # And this is the single instance of FakeModule whose __dict__ we keep
1019 # copying and clearing for reuse on each %run
1026 # copying and clearing for reuse on each %run
1020 self._user_main_module = FakeModule()
1027 self._user_main_module = FakeModule()
1021
1028
1022 # A table holding all the namespaces IPython deals with, so that
1029 # A table holding all the namespaces IPython deals with, so that
1023 # introspection facilities can search easily.
1030 # introspection facilities can search easily.
1024 self.ns_table = {'user_global':self.user_module.__dict__,
1031 self.ns_table = {'user_global':self.user_module.__dict__,
1025 'user_local':self.user_ns,
1032 'user_local':self.user_ns,
1026 'builtin':builtin_mod.__dict__
1033 'builtin':builtin_mod.__dict__
1027 }
1034 }
1028
1035
1029 @property
1036 @property
1030 def user_global_ns(self):
1037 def user_global_ns(self):
1031 return self.user_module.__dict__
1038 return self.user_module.__dict__
1032
1039
1033 def prepare_user_module(self, user_module=None, user_ns=None):
1040 def prepare_user_module(self, user_module=None, user_ns=None):
1034 """Prepare the module and namespace in which user code will be run.
1041 """Prepare the module and namespace in which user code will be run.
1035
1042
1036 When IPython is started normally, both parameters are None: a new module
1043 When IPython is started normally, both parameters are None: a new module
1037 is created automatically, and its __dict__ used as the namespace.
1044 is created automatically, and its __dict__ used as the namespace.
1038
1045
1039 If only user_module is provided, its __dict__ is used as the namespace.
1046 If only user_module is provided, its __dict__ is used as the namespace.
1040 If only user_ns is provided, a dummy module is created, and user_ns
1047 If only user_ns is provided, a dummy module is created, and user_ns
1041 becomes the global namespace. If both are provided (as they may be
1048 becomes the global namespace. If both are provided (as they may be
1042 when embedding), user_ns is the local namespace, and user_module
1049 when embedding), user_ns is the local namespace, and user_module
1043 provides the global namespace.
1050 provides the global namespace.
1044
1051
1045 Parameters
1052 Parameters
1046 ----------
1053 ----------
1047 user_module : module, optional
1054 user_module : module, optional
1048 The current user module in which IPython is being run. If None,
1055 The current user module in which IPython is being run. If None,
1049 a clean module will be created.
1056 a clean module will be created.
1050 user_ns : dict, optional
1057 user_ns : dict, optional
1051 A namespace in which to run interactive commands.
1058 A namespace in which to run interactive commands.
1052
1059
1053 Returns
1060 Returns
1054 -------
1061 -------
1055 A tuple of user_module and user_ns, each properly initialised.
1062 A tuple of user_module and user_ns, each properly initialised.
1056 """
1063 """
1057 if user_module is None and user_ns is not None:
1064 if user_module is None and user_ns is not None:
1058 user_ns.setdefault("__name__", "__main__")
1065 user_ns.setdefault("__name__", "__main__")
1059 class DummyMod(object):
1066 class DummyMod(object):
1060 "A dummy module used for IPython's interactive namespace."
1067 "A dummy module used for IPython's interactive namespace."
1061 pass
1068 pass
1062 user_module = DummyMod()
1069 user_module = DummyMod()
1063 user_module.__dict__ = user_ns
1070 user_module.__dict__ = user_ns
1064
1071
1065 if user_module is None:
1072 if user_module is None:
1066 user_module = types.ModuleType("__main__",
1073 user_module = types.ModuleType("__main__",
1067 doc="Automatically created module for IPython interactive environment")
1074 doc="Automatically created module for IPython interactive environment")
1068
1075
1069 # We must ensure that __builtin__ (without the final 's') is always
1076 # We must ensure that __builtin__ (without the final 's') is always
1070 # available and pointing to the __builtin__ *module*. For more details:
1077 # available and pointing to the __builtin__ *module*. For more details:
1071 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1078 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1072 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1079 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1073 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1080 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1074
1081
1075 if user_ns is None:
1082 if user_ns is None:
1076 user_ns = user_module.__dict__
1083 user_ns = user_module.__dict__
1077
1084
1078 return user_module, user_ns
1085 return user_module, user_ns
1079
1086
1080 def init_sys_modules(self):
1087 def init_sys_modules(self):
1081 # We need to insert into sys.modules something that looks like a
1088 # We need to insert into sys.modules something that looks like a
1082 # module but which accesses the IPython namespace, for shelve and
1089 # module but which accesses the IPython namespace, for shelve and
1083 # pickle to work interactively. Normally they rely on getting
1090 # pickle to work interactively. Normally they rely on getting
1084 # everything out of __main__, but for embedding purposes each IPython
1091 # everything out of __main__, but for embedding purposes each IPython
1085 # instance has its own private namespace, so we can't go shoving
1092 # instance has its own private namespace, so we can't go shoving
1086 # everything into __main__.
1093 # everything into __main__.
1087
1094
1088 # note, however, that we should only do this for non-embedded
1095 # note, however, that we should only do this for non-embedded
1089 # ipythons, which really mimic the __main__.__dict__ with their own
1096 # ipythons, which really mimic the __main__.__dict__ with their own
1090 # namespace. Embedded instances, on the other hand, should not do
1097 # namespace. Embedded instances, on the other hand, should not do
1091 # this because they need to manage the user local/global namespaces
1098 # this because they need to manage the user local/global namespaces
1092 # only, but they live within a 'normal' __main__ (meaning, they
1099 # only, but they live within a 'normal' __main__ (meaning, they
1093 # shouldn't overtake the execution environment of the script they're
1100 # shouldn't overtake the execution environment of the script they're
1094 # embedded in).
1101 # embedded in).
1095
1102
1096 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1103 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1097 main_name = self.user_module.__name__
1104 main_name = self.user_module.__name__
1098 sys.modules[main_name] = self.user_module
1105 sys.modules[main_name] = self.user_module
1099
1106
1100 def init_user_ns(self):
1107 def init_user_ns(self):
1101 """Initialize all user-visible namespaces to their minimum defaults.
1108 """Initialize all user-visible namespaces to their minimum defaults.
1102
1109
1103 Certain history lists are also initialized here, as they effectively
1110 Certain history lists are also initialized here, as they effectively
1104 act as user namespaces.
1111 act as user namespaces.
1105
1112
1106 Notes
1113 Notes
1107 -----
1114 -----
1108 All data structures here are only filled in, they are NOT reset by this
1115 All data structures here are only filled in, they are NOT reset by this
1109 method. If they were not empty before, data will simply be added to
1116 method. If they were not empty before, data will simply be added to
1110 therm.
1117 therm.
1111 """
1118 """
1112 # This function works in two parts: first we put a few things in
1119 # This function works in two parts: first we put a few things in
1113 # user_ns, and we sync that contents into user_ns_hidden so that these
1120 # user_ns, and we sync that contents into user_ns_hidden so that these
1114 # initial variables aren't shown by %who. After the sync, we add the
1121 # initial variables aren't shown by %who. After the sync, we add the
1115 # rest of what we *do* want the user to see with %who even on a new
1122 # rest of what we *do* want the user to see with %who even on a new
1116 # session (probably nothing, so theye really only see their own stuff)
1123 # session (probably nothing, so theye really only see their own stuff)
1117
1124
1118 # The user dict must *always* have a __builtin__ reference to the
1125 # The user dict must *always* have a __builtin__ reference to the
1119 # Python standard __builtin__ namespace, which must be imported.
1126 # Python standard __builtin__ namespace, which must be imported.
1120 # This is so that certain operations in prompt evaluation can be
1127 # This is so that certain operations in prompt evaluation can be
1121 # reliably executed with builtins. Note that we can NOT use
1128 # reliably executed with builtins. Note that we can NOT use
1122 # __builtins__ (note the 's'), because that can either be a dict or a
1129 # __builtins__ (note the 's'), because that can either be a dict or a
1123 # module, and can even mutate at runtime, depending on the context
1130 # module, and can even mutate at runtime, depending on the context
1124 # (Python makes no guarantees on it). In contrast, __builtin__ is
1131 # (Python makes no guarantees on it). In contrast, __builtin__ is
1125 # always a module object, though it must be explicitly imported.
1132 # always a module object, though it must be explicitly imported.
1126
1133
1127 # For more details:
1134 # For more details:
1128 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1135 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1129 ns = dict()
1136 ns = dict()
1130
1137
1131 # Put 'help' in the user namespace
1138 # Put 'help' in the user namespace
1132 try:
1139 try:
1133 from site import _Helper
1140 from site import _Helper
1134 ns['help'] = _Helper()
1141 ns['help'] = _Helper()
1135 except ImportError:
1142 except ImportError:
1136 warn('help() not available - check site.py')
1143 warn('help() not available - check site.py')
1137
1144
1138 # make global variables for user access to the histories
1145 # make global variables for user access to the histories
1139 ns['_ih'] = self.history_manager.input_hist_parsed
1146 ns['_ih'] = self.history_manager.input_hist_parsed
1140 ns['_oh'] = self.history_manager.output_hist
1147 ns['_oh'] = self.history_manager.output_hist
1141 ns['_dh'] = self.history_manager.dir_hist
1148 ns['_dh'] = self.history_manager.dir_hist
1142
1149
1143 ns['_sh'] = shadowns
1150 ns['_sh'] = shadowns
1144
1151
1145 # user aliases to input and output histories. These shouldn't show up
1152 # user aliases to input and output histories. These shouldn't show up
1146 # in %who, as they can have very large reprs.
1153 # in %who, as they can have very large reprs.
1147 ns['In'] = self.history_manager.input_hist_parsed
1154 ns['In'] = self.history_manager.input_hist_parsed
1148 ns['Out'] = self.history_manager.output_hist
1155 ns['Out'] = self.history_manager.output_hist
1149
1156
1150 # Store myself as the public api!!!
1157 # Store myself as the public api!!!
1151 ns['get_ipython'] = self.get_ipython
1158 ns['get_ipython'] = self.get_ipython
1152
1159
1153 ns['exit'] = self.exiter
1160 ns['exit'] = self.exiter
1154 ns['quit'] = self.exiter
1161 ns['quit'] = self.exiter
1155
1162
1156 # Sync what we've added so far to user_ns_hidden so these aren't seen
1163 # Sync what we've added so far to user_ns_hidden so these aren't seen
1157 # by %who
1164 # by %who
1158 self.user_ns_hidden.update(ns)
1165 self.user_ns_hidden.update(ns)
1159
1166
1160 # Anything put into ns now would show up in %who. Think twice before
1167 # Anything put into ns now would show up in %who. Think twice before
1161 # putting anything here, as we really want %who to show the user their
1168 # putting anything here, as we really want %who to show the user their
1162 # stuff, not our variables.
1169 # stuff, not our variables.
1163
1170
1164 # Finally, update the real user's namespace
1171 # Finally, update the real user's namespace
1165 self.user_ns.update(ns)
1172 self.user_ns.update(ns)
1166
1173
1167 @property
1174 @property
1168 def all_ns_refs(self):
1175 def all_ns_refs(self):
1169 """Get a list of references to all the namespace dictionaries in which
1176 """Get a list of references to all the namespace dictionaries in which
1170 IPython might store a user-created object.
1177 IPython might store a user-created object.
1171
1178
1172 Note that this does not include the displayhook, which also caches
1179 Note that this does not include the displayhook, which also caches
1173 objects from the output."""
1180 objects from the output."""
1174 return [self.user_ns, self.user_global_ns,
1181 return [self.user_ns, self.user_global_ns,
1175 self._user_main_module.__dict__] + self._main_ns_cache.values()
1182 self._user_main_module.__dict__] + self._main_ns_cache.values()
1176
1183
1177 def reset(self, new_session=True):
1184 def reset(self, new_session=True):
1178 """Clear all internal namespaces, and attempt to release references to
1185 """Clear all internal namespaces, and attempt to release references to
1179 user objects.
1186 user objects.
1180
1187
1181 If new_session is True, a new history session will be opened.
1188 If new_session is True, a new history session will be opened.
1182 """
1189 """
1183 # Clear histories
1190 # Clear histories
1184 self.history_manager.reset(new_session)
1191 self.history_manager.reset(new_session)
1185 # Reset counter used to index all histories
1192 # Reset counter used to index all histories
1186 if new_session:
1193 if new_session:
1187 self.execution_count = 1
1194 self.execution_count = 1
1188
1195
1189 # Flush cached output items
1196 # Flush cached output items
1190 if self.displayhook.do_full_cache:
1197 if self.displayhook.do_full_cache:
1191 self.displayhook.flush()
1198 self.displayhook.flush()
1192
1199
1193 # The main execution namespaces must be cleared very carefully,
1200 # The main execution namespaces must be cleared very carefully,
1194 # skipping the deletion of the builtin-related keys, because doing so
1201 # skipping the deletion of the builtin-related keys, because doing so
1195 # would cause errors in many object's __del__ methods.
1202 # would cause errors in many object's __del__ methods.
1196 if self.user_ns is not self.user_global_ns:
1203 if self.user_ns is not self.user_global_ns:
1197 self.user_ns.clear()
1204 self.user_ns.clear()
1198 ns = self.user_global_ns
1205 ns = self.user_global_ns
1199 drop_keys = set(ns.keys())
1206 drop_keys = set(ns.keys())
1200 drop_keys.discard('__builtin__')
1207 drop_keys.discard('__builtin__')
1201 drop_keys.discard('__builtins__')
1208 drop_keys.discard('__builtins__')
1202 drop_keys.discard('__name__')
1209 drop_keys.discard('__name__')
1203 for k in drop_keys:
1210 for k in drop_keys:
1204 del ns[k]
1211 del ns[k]
1205
1212
1206 self.user_ns_hidden.clear()
1213 self.user_ns_hidden.clear()
1207
1214
1208 # Restore the user namespaces to minimal usability
1215 # Restore the user namespaces to minimal usability
1209 self.init_user_ns()
1216 self.init_user_ns()
1210
1217
1211 # Restore the default and user aliases
1218 # Restore the default and user aliases
1212 self.alias_manager.clear_aliases()
1219 self.alias_manager.clear_aliases()
1213 self.alias_manager.init_aliases()
1220 self.alias_manager.init_aliases()
1214
1221
1215 # Flush the private list of module references kept for script
1222 # Flush the private list of module references kept for script
1216 # execution protection
1223 # execution protection
1217 self.clear_main_mod_cache()
1224 self.clear_main_mod_cache()
1218
1225
1219 # Clear out the namespace from the last %run
1226 # Clear out the namespace from the last %run
1220 self.new_main_mod()
1227 self.new_main_mod()
1221
1228
1222 def del_var(self, varname, by_name=False):
1229 def del_var(self, varname, by_name=False):
1223 """Delete a variable from the various namespaces, so that, as
1230 """Delete a variable from the various namespaces, so that, as
1224 far as possible, we're not keeping any hidden references to it.
1231 far as possible, we're not keeping any hidden references to it.
1225
1232
1226 Parameters
1233 Parameters
1227 ----------
1234 ----------
1228 varname : str
1235 varname : str
1229 The name of the variable to delete.
1236 The name of the variable to delete.
1230 by_name : bool
1237 by_name : bool
1231 If True, delete variables with the given name in each
1238 If True, delete variables with the given name in each
1232 namespace. If False (default), find the variable in the user
1239 namespace. If False (default), find the variable in the user
1233 namespace, and delete references to it.
1240 namespace, and delete references to it.
1234 """
1241 """
1235 if varname in ('__builtin__', '__builtins__'):
1242 if varname in ('__builtin__', '__builtins__'):
1236 raise ValueError("Refusing to delete %s" % varname)
1243 raise ValueError("Refusing to delete %s" % varname)
1237
1244
1238 ns_refs = self.all_ns_refs
1245 ns_refs = self.all_ns_refs
1239
1246
1240 if by_name: # Delete by name
1247 if by_name: # Delete by name
1241 for ns in ns_refs:
1248 for ns in ns_refs:
1242 try:
1249 try:
1243 del ns[varname]
1250 del ns[varname]
1244 except KeyError:
1251 except KeyError:
1245 pass
1252 pass
1246 else: # Delete by object
1253 else: # Delete by object
1247 try:
1254 try:
1248 obj = self.user_ns[varname]
1255 obj = self.user_ns[varname]
1249 except KeyError:
1256 except KeyError:
1250 raise NameError("name '%s' is not defined" % varname)
1257 raise NameError("name '%s' is not defined" % varname)
1251 # Also check in output history
1258 # Also check in output history
1252 ns_refs.append(self.history_manager.output_hist)
1259 ns_refs.append(self.history_manager.output_hist)
1253 for ns in ns_refs:
1260 for ns in ns_refs:
1254 to_delete = [n for n, o in ns.iteritems() if o is obj]
1261 to_delete = [n for n, o in ns.iteritems() if o is obj]
1255 for name in to_delete:
1262 for name in to_delete:
1256 del ns[name]
1263 del ns[name]
1257
1264
1258 # displayhook keeps extra references, but not in a dictionary
1265 # displayhook keeps extra references, but not in a dictionary
1259 for name in ('_', '__', '___'):
1266 for name in ('_', '__', '___'):
1260 if getattr(self.displayhook, name) is obj:
1267 if getattr(self.displayhook, name) is obj:
1261 setattr(self.displayhook, name, None)
1268 setattr(self.displayhook, name, None)
1262
1269
1263 def reset_selective(self, regex=None):
1270 def reset_selective(self, regex=None):
1264 """Clear selective variables from internal namespaces based on a
1271 """Clear selective variables from internal namespaces based on a
1265 specified regular expression.
1272 specified regular expression.
1266
1273
1267 Parameters
1274 Parameters
1268 ----------
1275 ----------
1269 regex : string or compiled pattern, optional
1276 regex : string or compiled pattern, optional
1270 A regular expression pattern that will be used in searching
1277 A regular expression pattern that will be used in searching
1271 variable names in the users namespaces.
1278 variable names in the users namespaces.
1272 """
1279 """
1273 if regex is not None:
1280 if regex is not None:
1274 try:
1281 try:
1275 m = re.compile(regex)
1282 m = re.compile(regex)
1276 except TypeError:
1283 except TypeError:
1277 raise TypeError('regex must be a string or compiled pattern')
1284 raise TypeError('regex must be a string or compiled pattern')
1278 # Search for keys in each namespace that match the given regex
1285 # Search for keys in each namespace that match the given regex
1279 # If a match is found, delete the key/value pair.
1286 # If a match is found, delete the key/value pair.
1280 for ns in self.all_ns_refs:
1287 for ns in self.all_ns_refs:
1281 for var in ns:
1288 for var in ns:
1282 if m.search(var):
1289 if m.search(var):
1283 del ns[var]
1290 del ns[var]
1284
1291
1285 def push(self, variables, interactive=True):
1292 def push(self, variables, interactive=True):
1286 """Inject a group of variables into the IPython user namespace.
1293 """Inject a group of variables into the IPython user namespace.
1287
1294
1288 Parameters
1295 Parameters
1289 ----------
1296 ----------
1290 variables : dict, str or list/tuple of str
1297 variables : dict, str or list/tuple of str
1291 The variables to inject into the user's namespace. If a dict, a
1298 The variables to inject into the user's namespace. If a dict, a
1292 simple update is done. If a str, the string is assumed to have
1299 simple update is done. If a str, the string is assumed to have
1293 variable names separated by spaces. A list/tuple of str can also
1300 variable names separated by spaces. A list/tuple of str can also
1294 be used to give the variable names. If just the variable names are
1301 be used to give the variable names. If just the variable names are
1295 give (list/tuple/str) then the variable values looked up in the
1302 give (list/tuple/str) then the variable values looked up in the
1296 callers frame.
1303 callers frame.
1297 interactive : bool
1304 interactive : bool
1298 If True (default), the variables will be listed with the ``who``
1305 If True (default), the variables will be listed with the ``who``
1299 magic.
1306 magic.
1300 """
1307 """
1301 vdict = None
1308 vdict = None
1302
1309
1303 # We need a dict of name/value pairs to do namespace updates.
1310 # We need a dict of name/value pairs to do namespace updates.
1304 if isinstance(variables, dict):
1311 if isinstance(variables, dict):
1305 vdict = variables
1312 vdict = variables
1306 elif isinstance(variables, (basestring, list, tuple)):
1313 elif isinstance(variables, (basestring, list, tuple)):
1307 if isinstance(variables, basestring):
1314 if isinstance(variables, basestring):
1308 vlist = variables.split()
1315 vlist = variables.split()
1309 else:
1316 else:
1310 vlist = variables
1317 vlist = variables
1311 vdict = {}
1318 vdict = {}
1312 cf = sys._getframe(1)
1319 cf = sys._getframe(1)
1313 for name in vlist:
1320 for name in vlist:
1314 try:
1321 try:
1315 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1322 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1316 except:
1323 except:
1317 print('Could not get variable %s from %s' %
1324 print('Could not get variable %s from %s' %
1318 (name,cf.f_code.co_name))
1325 (name,cf.f_code.co_name))
1319 else:
1326 else:
1320 raise ValueError('variables must be a dict/str/list/tuple')
1327 raise ValueError('variables must be a dict/str/list/tuple')
1321
1328
1322 # Propagate variables to user namespace
1329 # Propagate variables to user namespace
1323 self.user_ns.update(vdict)
1330 self.user_ns.update(vdict)
1324
1331
1325 # And configure interactive visibility
1332 # And configure interactive visibility
1326 user_ns_hidden = self.user_ns_hidden
1333 user_ns_hidden = self.user_ns_hidden
1327 if interactive:
1334 if interactive:
1328 user_ns_hidden.difference_update(vdict)
1335 user_ns_hidden.difference_update(vdict)
1329 else:
1336 else:
1330 user_ns_hidden.update(vdict)
1337 user_ns_hidden.update(vdict)
1331
1338
1332 def drop_by_id(self, variables):
1339 def drop_by_id(self, variables):
1333 """Remove a dict of variables from the user namespace, if they are the
1340 """Remove a dict of variables from the user namespace, if they are the
1334 same as the values in the dictionary.
1341 same as the values in the dictionary.
1335
1342
1336 This is intended for use by extensions: variables that they've added can
1343 This is intended for use by extensions: variables that they've added can
1337 be taken back out if they are unloaded, without removing any that the
1344 be taken back out if they are unloaded, without removing any that the
1338 user has overwritten.
1345 user has overwritten.
1339
1346
1340 Parameters
1347 Parameters
1341 ----------
1348 ----------
1342 variables : dict
1349 variables : dict
1343 A dictionary mapping object names (as strings) to the objects.
1350 A dictionary mapping object names (as strings) to the objects.
1344 """
1351 """
1345 for name, obj in variables.iteritems():
1352 for name, obj in variables.iteritems():
1346 if name in self.user_ns and self.user_ns[name] is obj:
1353 if name in self.user_ns and self.user_ns[name] is obj:
1347 del self.user_ns[name]
1354 del self.user_ns[name]
1348 self.user_ns_hidden.discard(name)
1355 self.user_ns_hidden.discard(name)
1349
1356
1350 #-------------------------------------------------------------------------
1357 #-------------------------------------------------------------------------
1351 # Things related to object introspection
1358 # Things related to object introspection
1352 #-------------------------------------------------------------------------
1359 #-------------------------------------------------------------------------
1353
1360
1354 def _ofind(self, oname, namespaces=None):
1361 def _ofind(self, oname, namespaces=None):
1355 """Find an object in the available namespaces.
1362 """Find an object in the available namespaces.
1356
1363
1357 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1364 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1358
1365
1359 Has special code to detect magic functions.
1366 Has special code to detect magic functions.
1360 """
1367 """
1361 oname = oname.strip()
1368 oname = oname.strip()
1362 #print '1- oname: <%r>' % oname # dbg
1369 #print '1- oname: <%r>' % oname # dbg
1363 if not oname.startswith(ESC_MAGIC) and \
1370 if not oname.startswith(ESC_MAGIC) and \
1364 not oname.startswith(ESC_MAGIC2) and \
1371 not oname.startswith(ESC_MAGIC2) and \
1365 not py3compat.isidentifier(oname, dotted=True):
1372 not py3compat.isidentifier(oname, dotted=True):
1366 return dict(found=False)
1373 return dict(found=False)
1367
1374
1368 alias_ns = None
1375 alias_ns = None
1369 if namespaces is None:
1376 if namespaces is None:
1370 # Namespaces to search in:
1377 # Namespaces to search in:
1371 # Put them in a list. The order is important so that we
1378 # Put them in a list. The order is important so that we
1372 # find things in the same order that Python finds them.
1379 # find things in the same order that Python finds them.
1373 namespaces = [ ('Interactive', self.user_ns),
1380 namespaces = [ ('Interactive', self.user_ns),
1374 ('Interactive (global)', self.user_global_ns),
1381 ('Interactive (global)', self.user_global_ns),
1375 ('Python builtin', builtin_mod.__dict__),
1382 ('Python builtin', builtin_mod.__dict__),
1376 ('Alias', self.alias_manager.alias_table),
1383 ('Alias', self.alias_manager.alias_table),
1377 ]
1384 ]
1378 alias_ns = self.alias_manager.alias_table
1385 alias_ns = self.alias_manager.alias_table
1379
1386
1380 # initialize results to 'null'
1387 # initialize results to 'null'
1381 found = False; obj = None; ospace = None; ds = None;
1388 found = False; obj = None; ospace = None; ds = None;
1382 ismagic = False; isalias = False; parent = None
1389 ismagic = False; isalias = False; parent = None
1383
1390
1384 # We need to special-case 'print', which as of python2.6 registers as a
1391 # We need to special-case 'print', which as of python2.6 registers as a
1385 # function but should only be treated as one if print_function was
1392 # function but should only be treated as one if print_function was
1386 # loaded with a future import. In this case, just bail.
1393 # loaded with a future import. In this case, just bail.
1387 if (oname == 'print' and not py3compat.PY3 and not \
1394 if (oname == 'print' and not py3compat.PY3 and not \
1388 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1395 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1389 return {'found':found, 'obj':obj, 'namespace':ospace,
1396 return {'found':found, 'obj':obj, 'namespace':ospace,
1390 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1397 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1391
1398
1392 # Look for the given name by splitting it in parts. If the head is
1399 # Look for the given name by splitting it in parts. If the head is
1393 # found, then we look for all the remaining parts as members, and only
1400 # found, then we look for all the remaining parts as members, and only
1394 # declare success if we can find them all.
1401 # declare success if we can find them all.
1395 oname_parts = oname.split('.')
1402 oname_parts = oname.split('.')
1396 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1403 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1397 for nsname,ns in namespaces:
1404 for nsname,ns in namespaces:
1398 try:
1405 try:
1399 obj = ns[oname_head]
1406 obj = ns[oname_head]
1400 except KeyError:
1407 except KeyError:
1401 continue
1408 continue
1402 else:
1409 else:
1403 #print 'oname_rest:', oname_rest # dbg
1410 #print 'oname_rest:', oname_rest # dbg
1404 for part in oname_rest:
1411 for part in oname_rest:
1405 try:
1412 try:
1406 parent = obj
1413 parent = obj
1407 obj = getattr(obj,part)
1414 obj = getattr(obj,part)
1408 except:
1415 except:
1409 # Blanket except b/c some badly implemented objects
1416 # Blanket except b/c some badly implemented objects
1410 # allow __getattr__ to raise exceptions other than
1417 # allow __getattr__ to raise exceptions other than
1411 # AttributeError, which then crashes IPython.
1418 # AttributeError, which then crashes IPython.
1412 break
1419 break
1413 else:
1420 else:
1414 # If we finish the for loop (no break), we got all members
1421 # If we finish the for loop (no break), we got all members
1415 found = True
1422 found = True
1416 ospace = nsname
1423 ospace = nsname
1417 if ns == alias_ns:
1424 if ns == alias_ns:
1418 isalias = True
1425 isalias = True
1419 break # namespace loop
1426 break # namespace loop
1420
1427
1421 # Try to see if it's magic
1428 # Try to see if it's magic
1422 if not found:
1429 if not found:
1423 obj = None
1430 obj = None
1424 if oname.startswith(ESC_MAGIC2):
1431 if oname.startswith(ESC_MAGIC2):
1425 oname = oname.lstrip(ESC_MAGIC2)
1432 oname = oname.lstrip(ESC_MAGIC2)
1426 obj = self.find_cell_magic(oname)
1433 obj = self.find_cell_magic(oname)
1427 elif oname.startswith(ESC_MAGIC):
1434 elif oname.startswith(ESC_MAGIC):
1428 oname = oname.lstrip(ESC_MAGIC)
1435 oname = oname.lstrip(ESC_MAGIC)
1429 obj = self.find_line_magic(oname)
1436 obj = self.find_line_magic(oname)
1430 else:
1437 else:
1431 # search without prefix, so run? will find %run?
1438 # search without prefix, so run? will find %run?
1432 obj = self.find_line_magic(oname)
1439 obj = self.find_line_magic(oname)
1433 if obj is None:
1440 if obj is None:
1434 obj = self.find_cell_magic(oname)
1441 obj = self.find_cell_magic(oname)
1435 if obj is not None:
1442 if obj is not None:
1436 found = True
1443 found = True
1437 ospace = 'IPython internal'
1444 ospace = 'IPython internal'
1438 ismagic = True
1445 ismagic = True
1439
1446
1440 # Last try: special-case some literals like '', [], {}, etc:
1447 # Last try: special-case some literals like '', [], {}, etc:
1441 if not found and oname_head in ["''",'""','[]','{}','()']:
1448 if not found and oname_head in ["''",'""','[]','{}','()']:
1442 obj = eval(oname_head)
1449 obj = eval(oname_head)
1443 found = True
1450 found = True
1444 ospace = 'Interactive'
1451 ospace = 'Interactive'
1445
1452
1446 return {'found':found, 'obj':obj, 'namespace':ospace,
1453 return {'found':found, 'obj':obj, 'namespace':ospace,
1447 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1454 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1448
1455
1449 def _ofind_property(self, oname, info):
1456 def _ofind_property(self, oname, info):
1450 """Second part of object finding, to look for property details."""
1457 """Second part of object finding, to look for property details."""
1451 if info.found:
1458 if info.found:
1452 # Get the docstring of the class property if it exists.
1459 # Get the docstring of the class property if it exists.
1453 path = oname.split('.')
1460 path = oname.split('.')
1454 root = '.'.join(path[:-1])
1461 root = '.'.join(path[:-1])
1455 if info.parent is not None:
1462 if info.parent is not None:
1456 try:
1463 try:
1457 target = getattr(info.parent, '__class__')
1464 target = getattr(info.parent, '__class__')
1458 # The object belongs to a class instance.
1465 # The object belongs to a class instance.
1459 try:
1466 try:
1460 target = getattr(target, path[-1])
1467 target = getattr(target, path[-1])
1461 # The class defines the object.
1468 # The class defines the object.
1462 if isinstance(target, property):
1469 if isinstance(target, property):
1463 oname = root + '.__class__.' + path[-1]
1470 oname = root + '.__class__.' + path[-1]
1464 info = Struct(self._ofind(oname))
1471 info = Struct(self._ofind(oname))
1465 except AttributeError: pass
1472 except AttributeError: pass
1466 except AttributeError: pass
1473 except AttributeError: pass
1467
1474
1468 # We return either the new info or the unmodified input if the object
1475 # We return either the new info or the unmodified input if the object
1469 # hadn't been found
1476 # hadn't been found
1470 return info
1477 return info
1471
1478
1472 def _object_find(self, oname, namespaces=None):
1479 def _object_find(self, oname, namespaces=None):
1473 """Find an object and return a struct with info about it."""
1480 """Find an object and return a struct with info about it."""
1474 inf = Struct(self._ofind(oname, namespaces))
1481 inf = Struct(self._ofind(oname, namespaces))
1475 return Struct(self._ofind_property(oname, inf))
1482 return Struct(self._ofind_property(oname, inf))
1476
1483
1477 def _inspect(self, meth, oname, namespaces=None, **kw):
1484 def _inspect(self, meth, oname, namespaces=None, **kw):
1478 """Generic interface to the inspector system.
1485 """Generic interface to the inspector system.
1479
1486
1480 This function is meant to be called by pdef, pdoc & friends."""
1487 This function is meant to be called by pdef, pdoc & friends."""
1481 info = self._object_find(oname, namespaces)
1488 info = self._object_find(oname, namespaces)
1482 if info.found:
1489 if info.found:
1483 pmethod = getattr(self.inspector, meth)
1490 pmethod = getattr(self.inspector, meth)
1484 formatter = format_screen if info.ismagic else None
1491 formatter = format_screen if info.ismagic else None
1485 if meth == 'pdoc':
1492 if meth == 'pdoc':
1486 pmethod(info.obj, oname, formatter)
1493 pmethod(info.obj, oname, formatter)
1487 elif meth == 'pinfo':
1494 elif meth == 'pinfo':
1488 pmethod(info.obj, oname, formatter, info, **kw)
1495 pmethod(info.obj, oname, formatter, info, **kw)
1489 else:
1496 else:
1490 pmethod(info.obj, oname)
1497 pmethod(info.obj, oname)
1491 else:
1498 else:
1492 print('Object `%s` not found.' % oname)
1499 print('Object `%s` not found.' % oname)
1493 return 'not found' # so callers can take other action
1500 return 'not found' # so callers can take other action
1494
1501
1495 def object_inspect(self, oname, detail_level=0):
1502 def object_inspect(self, oname, detail_level=0):
1496 with self.builtin_trap:
1503 with self.builtin_trap:
1497 info = self._object_find(oname)
1504 info = self._object_find(oname)
1498 if info.found:
1505 if info.found:
1499 return self.inspector.info(info.obj, oname, info=info,
1506 return self.inspector.info(info.obj, oname, info=info,
1500 detail_level=detail_level
1507 detail_level=detail_level
1501 )
1508 )
1502 else:
1509 else:
1503 return oinspect.object_info(name=oname, found=False)
1510 return oinspect.object_info(name=oname, found=False)
1504
1511
1505 #-------------------------------------------------------------------------
1512 #-------------------------------------------------------------------------
1506 # Things related to history management
1513 # Things related to history management
1507 #-------------------------------------------------------------------------
1514 #-------------------------------------------------------------------------
1508
1515
1509 def init_history(self):
1516 def init_history(self):
1510 """Sets up the command history, and starts regular autosaves."""
1517 """Sets up the command history, and starts regular autosaves."""
1511 self.history_manager = HistoryManager(shell=self, config=self.config)
1518 self.history_manager = HistoryManager(shell=self, config=self.config)
1512 self.configurables.append(self.history_manager)
1519 self.configurables.append(self.history_manager)
1513
1520
1514 #-------------------------------------------------------------------------
1521 #-------------------------------------------------------------------------
1515 # Things related to exception handling and tracebacks (not debugging)
1522 # Things related to exception handling and tracebacks (not debugging)
1516 #-------------------------------------------------------------------------
1523 #-------------------------------------------------------------------------
1517
1524
1518 def init_traceback_handlers(self, custom_exceptions):
1525 def init_traceback_handlers(self, custom_exceptions):
1519 # Syntax error handler.
1526 # Syntax error handler.
1520 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1527 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1521
1528
1522 # The interactive one is initialized with an offset, meaning we always
1529 # The interactive one is initialized with an offset, meaning we always
1523 # want to remove the topmost item in the traceback, which is our own
1530 # want to remove the topmost item in the traceback, which is our own
1524 # internal code. Valid modes: ['Plain','Context','Verbose']
1531 # internal code. Valid modes: ['Plain','Context','Verbose']
1525 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1532 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1526 color_scheme='NoColor',
1533 color_scheme='NoColor',
1527 tb_offset = 1,
1534 tb_offset = 1,
1528 check_cache=self.compile.check_cache)
1535 check_cache=self.compile.check_cache)
1529
1536
1530 # The instance will store a pointer to the system-wide exception hook,
1537 # The instance will store a pointer to the system-wide exception hook,
1531 # so that runtime code (such as magics) can access it. This is because
1538 # so that runtime code (such as magics) can access it. This is because
1532 # during the read-eval loop, it may get temporarily overwritten.
1539 # during the read-eval loop, it may get temporarily overwritten.
1533 self.sys_excepthook = sys.excepthook
1540 self.sys_excepthook = sys.excepthook
1534
1541
1535 # and add any custom exception handlers the user may have specified
1542 # and add any custom exception handlers the user may have specified
1536 self.set_custom_exc(*custom_exceptions)
1543 self.set_custom_exc(*custom_exceptions)
1537
1544
1538 # Set the exception mode
1545 # Set the exception mode
1539 self.InteractiveTB.set_mode(mode=self.xmode)
1546 self.InteractiveTB.set_mode(mode=self.xmode)
1540
1547
1541 def set_custom_exc(self, exc_tuple, handler):
1548 def set_custom_exc(self, exc_tuple, handler):
1542 """set_custom_exc(exc_tuple,handler)
1549 """set_custom_exc(exc_tuple,handler)
1543
1550
1544 Set a custom exception handler, which will be called if any of the
1551 Set a custom exception handler, which will be called if any of the
1545 exceptions in exc_tuple occur in the mainloop (specifically, in the
1552 exceptions in exc_tuple occur in the mainloop (specifically, in the
1546 run_code() method).
1553 run_code() method).
1547
1554
1548 Parameters
1555 Parameters
1549 ----------
1556 ----------
1550
1557
1551 exc_tuple : tuple of exception classes
1558 exc_tuple : tuple of exception classes
1552 A *tuple* of exception classes, for which to call the defined
1559 A *tuple* of exception classes, for which to call the defined
1553 handler. It is very important that you use a tuple, and NOT A
1560 handler. It is very important that you use a tuple, and NOT A
1554 LIST here, because of the way Python's except statement works. If
1561 LIST here, because of the way Python's except statement works. If
1555 you only want to trap a single exception, use a singleton tuple::
1562 you only want to trap a single exception, use a singleton tuple::
1556
1563
1557 exc_tuple == (MyCustomException,)
1564 exc_tuple == (MyCustomException,)
1558
1565
1559 handler : callable
1566 handler : callable
1560 handler must have the following signature::
1567 handler must have the following signature::
1561
1568
1562 def my_handler(self, etype, value, tb, tb_offset=None):
1569 def my_handler(self, etype, value, tb, tb_offset=None):
1563 ...
1570 ...
1564 return structured_traceback
1571 return structured_traceback
1565
1572
1566 Your handler must return a structured traceback (a list of strings),
1573 Your handler must return a structured traceback (a list of strings),
1567 or None.
1574 or None.
1568
1575
1569 This will be made into an instance method (via types.MethodType)
1576 This will be made into an instance method (via types.MethodType)
1570 of IPython itself, and it will be called if any of the exceptions
1577 of IPython itself, and it will be called if any of the exceptions
1571 listed in the exc_tuple are caught. If the handler is None, an
1578 listed in the exc_tuple are caught. If the handler is None, an
1572 internal basic one is used, which just prints basic info.
1579 internal basic one is used, which just prints basic info.
1573
1580
1574 To protect IPython from crashes, if your handler ever raises an
1581 To protect IPython from crashes, if your handler ever raises an
1575 exception or returns an invalid result, it will be immediately
1582 exception or returns an invalid result, it will be immediately
1576 disabled.
1583 disabled.
1577
1584
1578 WARNING: by putting in your own exception handler into IPython's main
1585 WARNING: by putting in your own exception handler into IPython's main
1579 execution loop, you run a very good chance of nasty crashes. This
1586 execution loop, you run a very good chance of nasty crashes. This
1580 facility should only be used if you really know what you are doing."""
1587 facility should only be used if you really know what you are doing."""
1581
1588
1582 assert type(exc_tuple)==type(()) , \
1589 assert type(exc_tuple)==type(()) , \
1583 "The custom exceptions must be given AS A TUPLE."
1590 "The custom exceptions must be given AS A TUPLE."
1584
1591
1585 def dummy_handler(self,etype,value,tb,tb_offset=None):
1592 def dummy_handler(self,etype,value,tb,tb_offset=None):
1586 print('*** Simple custom exception handler ***')
1593 print('*** Simple custom exception handler ***')
1587 print('Exception type :',etype)
1594 print('Exception type :',etype)
1588 print('Exception value:',value)
1595 print('Exception value:',value)
1589 print('Traceback :',tb)
1596 print('Traceback :',tb)
1590 #print 'Source code :','\n'.join(self.buffer)
1597 #print 'Source code :','\n'.join(self.buffer)
1591
1598
1592 def validate_stb(stb):
1599 def validate_stb(stb):
1593 """validate structured traceback return type
1600 """validate structured traceback return type
1594
1601
1595 return type of CustomTB *should* be a list of strings, but allow
1602 return type of CustomTB *should* be a list of strings, but allow
1596 single strings or None, which are harmless.
1603 single strings or None, which are harmless.
1597
1604
1598 This function will *always* return a list of strings,
1605 This function will *always* return a list of strings,
1599 and will raise a TypeError if stb is inappropriate.
1606 and will raise a TypeError if stb is inappropriate.
1600 """
1607 """
1601 msg = "CustomTB must return list of strings, not %r" % stb
1608 msg = "CustomTB must return list of strings, not %r" % stb
1602 if stb is None:
1609 if stb is None:
1603 return []
1610 return []
1604 elif isinstance(stb, basestring):
1611 elif isinstance(stb, basestring):
1605 return [stb]
1612 return [stb]
1606 elif not isinstance(stb, list):
1613 elif not isinstance(stb, list):
1607 raise TypeError(msg)
1614 raise TypeError(msg)
1608 # it's a list
1615 # it's a list
1609 for line in stb:
1616 for line in stb:
1610 # check every element
1617 # check every element
1611 if not isinstance(line, basestring):
1618 if not isinstance(line, basestring):
1612 raise TypeError(msg)
1619 raise TypeError(msg)
1613 return stb
1620 return stb
1614
1621
1615 if handler is None:
1622 if handler is None:
1616 wrapped = dummy_handler
1623 wrapped = dummy_handler
1617 else:
1624 else:
1618 def wrapped(self,etype,value,tb,tb_offset=None):
1625 def wrapped(self,etype,value,tb,tb_offset=None):
1619 """wrap CustomTB handler, to protect IPython from user code
1626 """wrap CustomTB handler, to protect IPython from user code
1620
1627
1621 This makes it harder (but not impossible) for custom exception
1628 This makes it harder (but not impossible) for custom exception
1622 handlers to crash IPython.
1629 handlers to crash IPython.
1623 """
1630 """
1624 try:
1631 try:
1625 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1632 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1626 return validate_stb(stb)
1633 return validate_stb(stb)
1627 except:
1634 except:
1628 # clear custom handler immediately
1635 # clear custom handler immediately
1629 self.set_custom_exc((), None)
1636 self.set_custom_exc((), None)
1630 print("Custom TB Handler failed, unregistering", file=io.stderr)
1637 print("Custom TB Handler failed, unregistering", file=io.stderr)
1631 # show the exception in handler first
1638 # show the exception in handler first
1632 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1639 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1633 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1640 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1634 print("The original exception:", file=io.stdout)
1641 print("The original exception:", file=io.stdout)
1635 stb = self.InteractiveTB.structured_traceback(
1642 stb = self.InteractiveTB.structured_traceback(
1636 (etype,value,tb), tb_offset=tb_offset
1643 (etype,value,tb), tb_offset=tb_offset
1637 )
1644 )
1638 return stb
1645 return stb
1639
1646
1640 self.CustomTB = types.MethodType(wrapped,self)
1647 self.CustomTB = types.MethodType(wrapped,self)
1641 self.custom_exceptions = exc_tuple
1648 self.custom_exceptions = exc_tuple
1642
1649
1643 def excepthook(self, etype, value, tb):
1650 def excepthook(self, etype, value, tb):
1644 """One more defense for GUI apps that call sys.excepthook.
1651 """One more defense for GUI apps that call sys.excepthook.
1645
1652
1646 GUI frameworks like wxPython trap exceptions and call
1653 GUI frameworks like wxPython trap exceptions and call
1647 sys.excepthook themselves. I guess this is a feature that
1654 sys.excepthook themselves. I guess this is a feature that
1648 enables them to keep running after exceptions that would
1655 enables them to keep running after exceptions that would
1649 otherwise kill their mainloop. This is a bother for IPython
1656 otherwise kill their mainloop. This is a bother for IPython
1650 which excepts to catch all of the program exceptions with a try:
1657 which excepts to catch all of the program exceptions with a try:
1651 except: statement.
1658 except: statement.
1652
1659
1653 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1660 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1654 any app directly invokes sys.excepthook, it will look to the user like
1661 any app directly invokes sys.excepthook, it will look to the user like
1655 IPython crashed. In order to work around this, we can disable the
1662 IPython crashed. In order to work around this, we can disable the
1656 CrashHandler and replace it with this excepthook instead, which prints a
1663 CrashHandler and replace it with this excepthook instead, which prints a
1657 regular traceback using our InteractiveTB. In this fashion, apps which
1664 regular traceback using our InteractiveTB. In this fashion, apps which
1658 call sys.excepthook will generate a regular-looking exception from
1665 call sys.excepthook will generate a regular-looking exception from
1659 IPython, and the CrashHandler will only be triggered by real IPython
1666 IPython, and the CrashHandler will only be triggered by real IPython
1660 crashes.
1667 crashes.
1661
1668
1662 This hook should be used sparingly, only in places which are not likely
1669 This hook should be used sparingly, only in places which are not likely
1663 to be true IPython errors.
1670 to be true IPython errors.
1664 """
1671 """
1665 self.showtraceback((etype,value,tb),tb_offset=0)
1672 self.showtraceback((etype,value,tb),tb_offset=0)
1666
1673
1667 def _get_exc_info(self, exc_tuple=None):
1674 def _get_exc_info(self, exc_tuple=None):
1668 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1675 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1669
1676
1670 Ensures sys.last_type,value,traceback hold the exc_info we found,
1677 Ensures sys.last_type,value,traceback hold the exc_info we found,
1671 from whichever source.
1678 from whichever source.
1672
1679
1673 raises ValueError if none of these contain any information
1680 raises ValueError if none of these contain any information
1674 """
1681 """
1675 if exc_tuple is None:
1682 if exc_tuple is None:
1676 etype, value, tb = sys.exc_info()
1683 etype, value, tb = sys.exc_info()
1677 else:
1684 else:
1678 etype, value, tb = exc_tuple
1685 etype, value, tb = exc_tuple
1679
1686
1680 if etype is None:
1687 if etype is None:
1681 if hasattr(sys, 'last_type'):
1688 if hasattr(sys, 'last_type'):
1682 etype, value, tb = sys.last_type, sys.last_value, \
1689 etype, value, tb = sys.last_type, sys.last_value, \
1683 sys.last_traceback
1690 sys.last_traceback
1684
1691
1685 if etype is None:
1692 if etype is None:
1686 raise ValueError("No exception to find")
1693 raise ValueError("No exception to find")
1687
1694
1688 # Now store the exception info in sys.last_type etc.
1695 # Now store the exception info in sys.last_type etc.
1689 # WARNING: these variables are somewhat deprecated and not
1696 # WARNING: these variables are somewhat deprecated and not
1690 # necessarily safe to use in a threaded environment, but tools
1697 # necessarily safe to use in a threaded environment, but tools
1691 # like pdb depend on their existence, so let's set them. If we
1698 # like pdb depend on their existence, so let's set them. If we
1692 # find problems in the field, we'll need to revisit their use.
1699 # find problems in the field, we'll need to revisit their use.
1693 sys.last_type = etype
1700 sys.last_type = etype
1694 sys.last_value = value
1701 sys.last_value = value
1695 sys.last_traceback = tb
1702 sys.last_traceback = tb
1696
1703
1697 return etype, value, tb
1704 return etype, value, tb
1698
1705
1699
1706
1700 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1707 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1701 exception_only=False):
1708 exception_only=False):
1702 """Display the exception that just occurred.
1709 """Display the exception that just occurred.
1703
1710
1704 If nothing is known about the exception, this is the method which
1711 If nothing is known about the exception, this is the method which
1705 should be used throughout the code for presenting user tracebacks,
1712 should be used throughout the code for presenting user tracebacks,
1706 rather than directly invoking the InteractiveTB object.
1713 rather than directly invoking the InteractiveTB object.
1707
1714
1708 A specific showsyntaxerror() also exists, but this method can take
1715 A specific showsyntaxerror() also exists, but this method can take
1709 care of calling it if needed, so unless you are explicitly catching a
1716 care of calling it if needed, so unless you are explicitly catching a
1710 SyntaxError exception, don't try to analyze the stack manually and
1717 SyntaxError exception, don't try to analyze the stack manually and
1711 simply call this method."""
1718 simply call this method."""
1712
1719
1713 try:
1720 try:
1714 try:
1721 try:
1715 etype, value, tb = self._get_exc_info(exc_tuple)
1722 etype, value, tb = self._get_exc_info(exc_tuple)
1716 except ValueError:
1723 except ValueError:
1717 self.write_err('No traceback available to show.\n')
1724 self.write_err('No traceback available to show.\n')
1718 return
1725 return
1719
1726
1720 if issubclass(etype, SyntaxError):
1727 if issubclass(etype, SyntaxError):
1721 # Though this won't be called by syntax errors in the input
1728 # Though this won't be called by syntax errors in the input
1722 # line, there may be SyntaxError cases with imported code.
1729 # line, there may be SyntaxError cases with imported code.
1723 self.showsyntaxerror(filename)
1730 self.showsyntaxerror(filename)
1724 elif etype is UsageError:
1731 elif etype is UsageError:
1725 self.write_err("UsageError: %s" % value)
1732 self.write_err("UsageError: %s" % value)
1726 else:
1733 else:
1727 if exception_only:
1734 if exception_only:
1728 stb = ['An exception has occurred, use %tb to see '
1735 stb = ['An exception has occurred, use %tb to see '
1729 'the full traceback.\n']
1736 'the full traceback.\n']
1730 stb.extend(self.InteractiveTB.get_exception_only(etype,
1737 stb.extend(self.InteractiveTB.get_exception_only(etype,
1731 value))
1738 value))
1732 else:
1739 else:
1733 try:
1740 try:
1734 # Exception classes can customise their traceback - we
1741 # Exception classes can customise their traceback - we
1735 # use this in IPython.parallel for exceptions occurring
1742 # use this in IPython.parallel for exceptions occurring
1736 # in the engines. This should return a list of strings.
1743 # in the engines. This should return a list of strings.
1737 stb = value._render_traceback_()
1744 stb = value._render_traceback_()
1738 except Exception:
1745 except Exception:
1739 stb = self.InteractiveTB.structured_traceback(etype,
1746 stb = self.InteractiveTB.structured_traceback(etype,
1740 value, tb, tb_offset=tb_offset)
1747 value, tb, tb_offset=tb_offset)
1741
1748
1742 self._showtraceback(etype, value, stb)
1749 self._showtraceback(etype, value, stb)
1743 if self.call_pdb:
1750 if self.call_pdb:
1744 # drop into debugger
1751 # drop into debugger
1745 self.debugger(force=True)
1752 self.debugger(force=True)
1746 return
1753 return
1747
1754
1748 # Actually show the traceback
1755 # Actually show the traceback
1749 self._showtraceback(etype, value, stb)
1756 self._showtraceback(etype, value, stb)
1750
1757
1751 except KeyboardInterrupt:
1758 except KeyboardInterrupt:
1752 self.write_err("\nKeyboardInterrupt\n")
1759 self.write_err("\nKeyboardInterrupt\n")
1753
1760
1754 def _showtraceback(self, etype, evalue, stb):
1761 def _showtraceback(self, etype, evalue, stb):
1755 """Actually show a traceback.
1762 """Actually show a traceback.
1756
1763
1757 Subclasses may override this method to put the traceback on a different
1764 Subclasses may override this method to put the traceback on a different
1758 place, like a side channel.
1765 place, like a side channel.
1759 """
1766 """
1760 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1767 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1761
1768
1762 def showsyntaxerror(self, filename=None):
1769 def showsyntaxerror(self, filename=None):
1763 """Display the syntax error that just occurred.
1770 """Display the syntax error that just occurred.
1764
1771
1765 This doesn't display a stack trace because there isn't one.
1772 This doesn't display a stack trace because there isn't one.
1766
1773
1767 If a filename is given, it is stuffed in the exception instead
1774 If a filename is given, it is stuffed in the exception instead
1768 of what was there before (because Python's parser always uses
1775 of what was there before (because Python's parser always uses
1769 "<string>" when reading from a string).
1776 "<string>" when reading from a string).
1770 """
1777 """
1771 etype, value, last_traceback = self._get_exc_info()
1778 etype, value, last_traceback = self._get_exc_info()
1772
1779
1773 if filename and issubclass(etype, SyntaxError):
1780 if filename and issubclass(etype, SyntaxError):
1774 try:
1781 try:
1775 value.filename = filename
1782 value.filename = filename
1776 except:
1783 except:
1777 # Not the format we expect; leave it alone
1784 # Not the format we expect; leave it alone
1778 pass
1785 pass
1779
1786
1780 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1787 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1781 self._showtraceback(etype, value, stb)
1788 self._showtraceback(etype, value, stb)
1782
1789
1783 # This is overridden in TerminalInteractiveShell to show a message about
1790 # This is overridden in TerminalInteractiveShell to show a message about
1784 # the %paste magic.
1791 # the %paste magic.
1785 def showindentationerror(self):
1792 def showindentationerror(self):
1786 """Called by run_cell when there's an IndentationError in code entered
1793 """Called by run_cell when there's an IndentationError in code entered
1787 at the prompt.
1794 at the prompt.
1788
1795
1789 This is overridden in TerminalInteractiveShell to show a message about
1796 This is overridden in TerminalInteractiveShell to show a message about
1790 the %paste magic."""
1797 the %paste magic."""
1791 self.showsyntaxerror()
1798 self.showsyntaxerror()
1792
1799
1793 #-------------------------------------------------------------------------
1800 #-------------------------------------------------------------------------
1794 # Things related to readline
1801 # Things related to readline
1795 #-------------------------------------------------------------------------
1802 #-------------------------------------------------------------------------
1796
1803
1797 def init_readline(self):
1804 def init_readline(self):
1798 """Command history completion/saving/reloading."""
1805 """Command history completion/saving/reloading."""
1799
1806
1800 if self.readline_use:
1807 if self.readline_use:
1801 import IPython.utils.rlineimpl as readline
1808 import IPython.utils.rlineimpl as readline
1802
1809
1803 self.rl_next_input = None
1810 self.rl_next_input = None
1804 self.rl_do_indent = False
1811 self.rl_do_indent = False
1805
1812
1806 if not self.readline_use or not readline.have_readline:
1813 if not self.readline_use or not readline.have_readline:
1807 self.has_readline = False
1814 self.has_readline = False
1808 self.readline = None
1815 self.readline = None
1809 # Set a number of methods that depend on readline to be no-op
1816 # Set a number of methods that depend on readline to be no-op
1810 self.readline_no_record = no_op_context
1817 self.readline_no_record = no_op_context
1811 self.set_readline_completer = no_op
1818 self.set_readline_completer = no_op
1812 self.set_custom_completer = no_op
1819 self.set_custom_completer = no_op
1813 if self.readline_use:
1820 if self.readline_use:
1814 warn('Readline services not available or not loaded.')
1821 warn('Readline services not available or not loaded.')
1815 else:
1822 else:
1816 self.has_readline = True
1823 self.has_readline = True
1817 self.readline = readline
1824 self.readline = readline
1818 sys.modules['readline'] = readline
1825 sys.modules['readline'] = readline
1819
1826
1820 # Platform-specific configuration
1827 # Platform-specific configuration
1821 if os.name == 'nt':
1828 if os.name == 'nt':
1822 # FIXME - check with Frederick to see if we can harmonize
1829 # FIXME - check with Frederick to see if we can harmonize
1823 # naming conventions with pyreadline to avoid this
1830 # naming conventions with pyreadline to avoid this
1824 # platform-dependent check
1831 # platform-dependent check
1825 self.readline_startup_hook = readline.set_pre_input_hook
1832 self.readline_startup_hook = readline.set_pre_input_hook
1826 else:
1833 else:
1827 self.readline_startup_hook = readline.set_startup_hook
1834 self.readline_startup_hook = readline.set_startup_hook
1828
1835
1829 # Load user's initrc file (readline config)
1836 # Load user's initrc file (readline config)
1830 # Or if libedit is used, load editrc.
1837 # Or if libedit is used, load editrc.
1831 inputrc_name = os.environ.get('INPUTRC')
1838 inputrc_name = os.environ.get('INPUTRC')
1832 if inputrc_name is None:
1839 if inputrc_name is None:
1833 inputrc_name = '.inputrc'
1840 inputrc_name = '.inputrc'
1834 if readline.uses_libedit:
1841 if readline.uses_libedit:
1835 inputrc_name = '.editrc'
1842 inputrc_name = '.editrc'
1836 inputrc_name = os.path.join(self.home_dir, inputrc_name)
1843 inputrc_name = os.path.join(self.home_dir, inputrc_name)
1837 if os.path.isfile(inputrc_name):
1844 if os.path.isfile(inputrc_name):
1838 try:
1845 try:
1839 readline.read_init_file(inputrc_name)
1846 readline.read_init_file(inputrc_name)
1840 except:
1847 except:
1841 warn('Problems reading readline initialization file <%s>'
1848 warn('Problems reading readline initialization file <%s>'
1842 % inputrc_name)
1849 % inputrc_name)
1843
1850
1844 # Configure readline according to user's prefs
1851 # Configure readline according to user's prefs
1845 # This is only done if GNU readline is being used. If libedit
1852 # This is only done if GNU readline is being used. If libedit
1846 # is being used (as on Leopard) the readline config is
1853 # is being used (as on Leopard) the readline config is
1847 # not run as the syntax for libedit is different.
1854 # not run as the syntax for libedit is different.
1848 if not readline.uses_libedit:
1855 if not readline.uses_libedit:
1849 for rlcommand in self.readline_parse_and_bind:
1856 for rlcommand in self.readline_parse_and_bind:
1850 #print "loading rl:",rlcommand # dbg
1857 #print "loading rl:",rlcommand # dbg
1851 readline.parse_and_bind(rlcommand)
1858 readline.parse_and_bind(rlcommand)
1852
1859
1853 # Remove some chars from the delimiters list. If we encounter
1860 # Remove some chars from the delimiters list. If we encounter
1854 # unicode chars, discard them.
1861 # unicode chars, discard them.
1855 delims = readline.get_completer_delims()
1862 delims = readline.get_completer_delims()
1856 if not py3compat.PY3:
1863 if not py3compat.PY3:
1857 delims = delims.encode("ascii", "ignore")
1864 delims = delims.encode("ascii", "ignore")
1858 for d in self.readline_remove_delims:
1865 for d in self.readline_remove_delims:
1859 delims = delims.replace(d, "")
1866 delims = delims.replace(d, "")
1860 delims = delims.replace(ESC_MAGIC, '')
1867 delims = delims.replace(ESC_MAGIC, '')
1861 readline.set_completer_delims(delims)
1868 readline.set_completer_delims(delims)
1862 # otherwise we end up with a monster history after a while:
1869 # otherwise we end up with a monster history after a while:
1863 readline.set_history_length(self.history_length)
1870 readline.set_history_length(self.history_length)
1864
1871
1865 self.refill_readline_hist()
1872 self.refill_readline_hist()
1866 self.readline_no_record = ReadlineNoRecord(self)
1873 self.readline_no_record = ReadlineNoRecord(self)
1867
1874
1868 # Configure auto-indent for all platforms
1875 # Configure auto-indent for all platforms
1869 self.set_autoindent(self.autoindent)
1876 self.set_autoindent(self.autoindent)
1870
1877
1871 def refill_readline_hist(self):
1878 def refill_readline_hist(self):
1872 # Load the last 1000 lines from history
1879 # Load the last 1000 lines from history
1873 self.readline.clear_history()
1880 self.readline.clear_history()
1874 stdin_encoding = sys.stdin.encoding or "utf-8"
1881 stdin_encoding = sys.stdin.encoding or "utf-8"
1875 last_cell = u""
1882 last_cell = u""
1876 for _, _, cell in self.history_manager.get_tail(1000,
1883 for _, _, cell in self.history_manager.get_tail(1000,
1877 include_latest=True):
1884 include_latest=True):
1878 # Ignore blank lines and consecutive duplicates
1885 # Ignore blank lines and consecutive duplicates
1879 cell = cell.rstrip()
1886 cell = cell.rstrip()
1880 if cell and (cell != last_cell):
1887 if cell and (cell != last_cell):
1881 if self.multiline_history:
1888 if self.multiline_history:
1882 self.readline.add_history(py3compat.unicode_to_str(cell,
1889 self.readline.add_history(py3compat.unicode_to_str(cell,
1883 stdin_encoding))
1890 stdin_encoding))
1884 else:
1891 else:
1885 for line in cell.splitlines():
1892 for line in cell.splitlines():
1886 self.readline.add_history(py3compat.unicode_to_str(line,
1893 self.readline.add_history(py3compat.unicode_to_str(line,
1887 stdin_encoding))
1894 stdin_encoding))
1888 last_cell = cell
1895 last_cell = cell
1889
1896
1890 def set_next_input(self, s):
1897 def set_next_input(self, s):
1891 """ Sets the 'default' input string for the next command line.
1898 """ Sets the 'default' input string for the next command line.
1892
1899
1893 Requires readline.
1900 Requires readline.
1894
1901
1895 Example:
1902 Example:
1896
1903
1897 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1904 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1898 [D:\ipython]|2> Hello Word_ # cursor is here
1905 [D:\ipython]|2> Hello Word_ # cursor is here
1899 """
1906 """
1900 self.rl_next_input = py3compat.cast_bytes_py2(s)
1907 self.rl_next_input = py3compat.cast_bytes_py2(s)
1901
1908
1902 # Maybe move this to the terminal subclass?
1909 # Maybe move this to the terminal subclass?
1903 def pre_readline(self):
1910 def pre_readline(self):
1904 """readline hook to be used at the start of each line.
1911 """readline hook to be used at the start of each line.
1905
1912
1906 Currently it handles auto-indent only."""
1913 Currently it handles auto-indent only."""
1907
1914
1908 if self.rl_do_indent:
1915 if self.rl_do_indent:
1909 self.readline.insert_text(self._indent_current_str())
1916 self.readline.insert_text(self._indent_current_str())
1910 if self.rl_next_input is not None:
1917 if self.rl_next_input is not None:
1911 self.readline.insert_text(self.rl_next_input)
1918 self.readline.insert_text(self.rl_next_input)
1912 self.rl_next_input = None
1919 self.rl_next_input = None
1913
1920
1914 def _indent_current_str(self):
1921 def _indent_current_str(self):
1915 """return the current level of indentation as a string"""
1922 """return the current level of indentation as a string"""
1916 return self.input_splitter.indent_spaces * ' '
1923 return self.input_splitter.indent_spaces * ' '
1917
1924
1918 #-------------------------------------------------------------------------
1925 #-------------------------------------------------------------------------
1919 # Things related to text completion
1926 # Things related to text completion
1920 #-------------------------------------------------------------------------
1927 #-------------------------------------------------------------------------
1921
1928
1922 def init_completer(self):
1929 def init_completer(self):
1923 """Initialize the completion machinery.
1930 """Initialize the completion machinery.
1924
1931
1925 This creates completion machinery that can be used by client code,
1932 This creates completion machinery that can be used by client code,
1926 either interactively in-process (typically triggered by the readline
1933 either interactively in-process (typically triggered by the readline
1927 library), programatically (such as in test suites) or out-of-prcess
1934 library), programatically (such as in test suites) or out-of-prcess
1928 (typically over the network by remote frontends).
1935 (typically over the network by remote frontends).
1929 """
1936 """
1930 from IPython.core.completer import IPCompleter
1937 from IPython.core.completer import IPCompleter
1931 from IPython.core.completerlib import (module_completer,
1938 from IPython.core.completerlib import (module_completer,
1932 magic_run_completer, cd_completer, reset_completer)
1939 magic_run_completer, cd_completer, reset_completer)
1933
1940
1934 self.Completer = IPCompleter(shell=self,
1941 self.Completer = IPCompleter(shell=self,
1935 namespace=self.user_ns,
1942 namespace=self.user_ns,
1936 global_namespace=self.user_global_ns,
1943 global_namespace=self.user_global_ns,
1937 alias_table=self.alias_manager.alias_table,
1944 alias_table=self.alias_manager.alias_table,
1938 use_readline=self.has_readline,
1945 use_readline=self.has_readline,
1939 config=self.config,
1946 config=self.config,
1940 )
1947 )
1941 self.configurables.append(self.Completer)
1948 self.configurables.append(self.Completer)
1942
1949
1943 # Add custom completers to the basic ones built into IPCompleter
1950 # Add custom completers to the basic ones built into IPCompleter
1944 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1951 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1945 self.strdispatchers['complete_command'] = sdisp
1952 self.strdispatchers['complete_command'] = sdisp
1946 self.Completer.custom_completers = sdisp
1953 self.Completer.custom_completers = sdisp
1947
1954
1948 self.set_hook('complete_command', module_completer, str_key = 'import')
1955 self.set_hook('complete_command', module_completer, str_key = 'import')
1949 self.set_hook('complete_command', module_completer, str_key = 'from')
1956 self.set_hook('complete_command', module_completer, str_key = 'from')
1950 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1957 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1951 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1958 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1952 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1959 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1953
1960
1954 # Only configure readline if we truly are using readline. IPython can
1961 # Only configure readline if we truly are using readline. IPython can
1955 # do tab-completion over the network, in GUIs, etc, where readline
1962 # do tab-completion over the network, in GUIs, etc, where readline
1956 # itself may be absent
1963 # itself may be absent
1957 if self.has_readline:
1964 if self.has_readline:
1958 self.set_readline_completer()
1965 self.set_readline_completer()
1959
1966
1960 def complete(self, text, line=None, cursor_pos=None):
1967 def complete(self, text, line=None, cursor_pos=None):
1961 """Return the completed text and a list of completions.
1968 """Return the completed text and a list of completions.
1962
1969
1963 Parameters
1970 Parameters
1964 ----------
1971 ----------
1965
1972
1966 text : string
1973 text : string
1967 A string of text to be completed on. It can be given as empty and
1974 A string of text to be completed on. It can be given as empty and
1968 instead a line/position pair are given. In this case, the
1975 instead a line/position pair are given. In this case, the
1969 completer itself will split the line like readline does.
1976 completer itself will split the line like readline does.
1970
1977
1971 line : string, optional
1978 line : string, optional
1972 The complete line that text is part of.
1979 The complete line that text is part of.
1973
1980
1974 cursor_pos : int, optional
1981 cursor_pos : int, optional
1975 The position of the cursor on the input line.
1982 The position of the cursor on the input line.
1976
1983
1977 Returns
1984 Returns
1978 -------
1985 -------
1979 text : string
1986 text : string
1980 The actual text that was completed.
1987 The actual text that was completed.
1981
1988
1982 matches : list
1989 matches : list
1983 A sorted list with all possible completions.
1990 A sorted list with all possible completions.
1984
1991
1985 The optional arguments allow the completion to take more context into
1992 The optional arguments allow the completion to take more context into
1986 account, and are part of the low-level completion API.
1993 account, and are part of the low-level completion API.
1987
1994
1988 This is a wrapper around the completion mechanism, similar to what
1995 This is a wrapper around the completion mechanism, similar to what
1989 readline does at the command line when the TAB key is hit. By
1996 readline does at the command line when the TAB key is hit. By
1990 exposing it as a method, it can be used by other non-readline
1997 exposing it as a method, it can be used by other non-readline
1991 environments (such as GUIs) for text completion.
1998 environments (such as GUIs) for text completion.
1992
1999
1993 Simple usage example:
2000 Simple usage example:
1994
2001
1995 In [1]: x = 'hello'
2002 In [1]: x = 'hello'
1996
2003
1997 In [2]: _ip.complete('x.l')
2004 In [2]: _ip.complete('x.l')
1998 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
2005 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1999 """
2006 """
2000
2007
2001 # Inject names into __builtin__ so we can complete on the added names.
2008 # Inject names into __builtin__ so we can complete on the added names.
2002 with self.builtin_trap:
2009 with self.builtin_trap:
2003 return self.Completer.complete(text, line, cursor_pos)
2010 return self.Completer.complete(text, line, cursor_pos)
2004
2011
2005 def set_custom_completer(self, completer, pos=0):
2012 def set_custom_completer(self, completer, pos=0):
2006 """Adds a new custom completer function.
2013 """Adds a new custom completer function.
2007
2014
2008 The position argument (defaults to 0) is the index in the completers
2015 The position argument (defaults to 0) is the index in the completers
2009 list where you want the completer to be inserted."""
2016 list where you want the completer to be inserted."""
2010
2017
2011 newcomp = types.MethodType(completer,self.Completer)
2018 newcomp = types.MethodType(completer,self.Completer)
2012 self.Completer.matchers.insert(pos,newcomp)
2019 self.Completer.matchers.insert(pos,newcomp)
2013
2020
2014 def set_readline_completer(self):
2021 def set_readline_completer(self):
2015 """Reset readline's completer to be our own."""
2022 """Reset readline's completer to be our own."""
2016 self.readline.set_completer(self.Completer.rlcomplete)
2023 self.readline.set_completer(self.Completer.rlcomplete)
2017
2024
2018 def set_completer_frame(self, frame=None):
2025 def set_completer_frame(self, frame=None):
2019 """Set the frame of the completer."""
2026 """Set the frame of the completer."""
2020 if frame:
2027 if frame:
2021 self.Completer.namespace = frame.f_locals
2028 self.Completer.namespace = frame.f_locals
2022 self.Completer.global_namespace = frame.f_globals
2029 self.Completer.global_namespace = frame.f_globals
2023 else:
2030 else:
2024 self.Completer.namespace = self.user_ns
2031 self.Completer.namespace = self.user_ns
2025 self.Completer.global_namespace = self.user_global_ns
2032 self.Completer.global_namespace = self.user_global_ns
2026
2033
2027 #-------------------------------------------------------------------------
2034 #-------------------------------------------------------------------------
2028 # Things related to magics
2035 # Things related to magics
2029 #-------------------------------------------------------------------------
2036 #-------------------------------------------------------------------------
2030
2037
2031 def init_magics(self):
2038 def init_magics(self):
2032 from IPython.core import magics as m
2039 from IPython.core import magics as m
2033 self.magics_manager = magic.MagicsManager(shell=self,
2040 self.magics_manager = magic.MagicsManager(shell=self,
2034 confg=self.config,
2041 confg=self.config,
2035 user_magics=m.UserMagics(self))
2042 user_magics=m.UserMagics(self))
2036 self.configurables.append(self.magics_manager)
2043 self.configurables.append(self.magics_manager)
2037
2044
2038 # Expose as public API from the magics manager
2045 # Expose as public API from the magics manager
2039 self.register_magics = self.magics_manager.register
2046 self.register_magics = self.magics_manager.register
2040 self.register_magic_function = self.magics_manager.register_function
2047 self.register_magic_function = self.magics_manager.register_function
2041 self.define_magic = self.magics_manager.define_magic
2048 self.define_magic = self.magics_manager.define_magic
2042
2049
2043 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2050 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2044 m.ConfigMagics, m.DeprecatedMagics, m.DisplayMagics, m.ExecutionMagics,
2051 m.ConfigMagics, m.DeprecatedMagics, m.DisplayMagics, m.ExecutionMagics,
2045 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2052 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2046 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2053 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2047 )
2054 )
2048
2055
2049 # Register Magic Aliases
2056 # Register Magic Aliases
2050 mman = self.magics_manager
2057 mman = self.magics_manager
2051 mman.register_alias('ed', 'edit')
2058 mman.register_alias('ed', 'edit')
2052 mman.register_alias('hist', 'history')
2059 mman.register_alias('hist', 'history')
2053 mman.register_alias('rep', 'recall')
2060 mman.register_alias('rep', 'recall')
2054
2061
2055 # FIXME: Move the color initialization to the DisplayHook, which
2062 # FIXME: Move the color initialization to the DisplayHook, which
2056 # should be split into a prompt manager and displayhook. We probably
2063 # should be split into a prompt manager and displayhook. We probably
2057 # even need a centralize colors management object.
2064 # even need a centralize colors management object.
2058 self.magic('colors %s' % self.colors)
2065 self.magic('colors %s' % self.colors)
2059
2066
2060 def run_line_magic(self, magic_name, line):
2067 def run_line_magic(self, magic_name, line):
2061 """Execute the given line magic.
2068 """Execute the given line magic.
2062
2069
2063 Parameters
2070 Parameters
2064 ----------
2071 ----------
2065 magic_name : str
2072 magic_name : str
2066 Name of the desired magic function, without '%' prefix.
2073 Name of the desired magic function, without '%' prefix.
2067
2074
2068 line : str
2075 line : str
2069 The rest of the input line as a single string.
2076 The rest of the input line as a single string.
2070 """
2077 """
2071 fn = self.find_line_magic(magic_name)
2078 fn = self.find_line_magic(magic_name)
2072 if fn is None:
2079 if fn is None:
2073 cm = self.find_cell_magic(magic_name)
2080 cm = self.find_cell_magic(magic_name)
2074 etpl = "Line magic function `%%%s` not found%s."
2081 etpl = "Line magic function `%%%s` not found%s."
2075 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2082 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2076 'did you mean that instead?)' % magic_name )
2083 'did you mean that instead?)' % magic_name )
2077 error(etpl % (magic_name, extra))
2084 error(etpl % (magic_name, extra))
2078 else:
2085 else:
2079 # Note: this is the distance in the stack to the user's frame.
2086 # Note: this is the distance in the stack to the user's frame.
2080 # This will need to be updated if the internal calling logic gets
2087 # This will need to be updated if the internal calling logic gets
2081 # refactored, or else we'll be expanding the wrong variables.
2088 # refactored, or else we'll be expanding the wrong variables.
2082 stack_depth = 2
2089 stack_depth = 2
2083 magic_arg_s = self.var_expand(line, stack_depth)
2090 magic_arg_s = self.var_expand(line, stack_depth)
2084 # Put magic args in a list so we can call with f(*a) syntax
2091 # Put magic args in a list so we can call with f(*a) syntax
2085 args = [magic_arg_s]
2092 args = [magic_arg_s]
2086 kwargs = {}
2093 kwargs = {}
2087 # Grab local namespace if we need it:
2094 # Grab local namespace if we need it:
2088 if getattr(fn, "needs_local_scope", False):
2095 if getattr(fn, "needs_local_scope", False):
2089 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2096 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2090 with self.builtin_trap:
2097 with self.builtin_trap:
2091 result = fn(*args,**kwargs)
2098 result = fn(*args,**kwargs)
2092 return result
2099 return result
2093
2100
2094 def run_cell_magic(self, magic_name, line, cell):
2101 def run_cell_magic(self, magic_name, line, cell):
2095 """Execute the given cell magic.
2102 """Execute the given cell magic.
2096
2103
2097 Parameters
2104 Parameters
2098 ----------
2105 ----------
2099 magic_name : str
2106 magic_name : str
2100 Name of the desired magic function, without '%' prefix.
2107 Name of the desired magic function, without '%' prefix.
2101
2108
2102 line : str
2109 line : str
2103 The rest of the first input line as a single string.
2110 The rest of the first input line as a single string.
2104
2111
2105 cell : str
2112 cell : str
2106 The body of the cell as a (possibly multiline) string.
2113 The body of the cell as a (possibly multiline) string.
2107 """
2114 """
2108 fn = self.find_cell_magic(magic_name)
2115 fn = self.find_cell_magic(magic_name)
2109 if fn is None:
2116 if fn is None:
2110 lm = self.find_line_magic(magic_name)
2117 lm = self.find_line_magic(magic_name)
2111 etpl = "Cell magic function `%%%%%s` not found%s."
2118 etpl = "Cell magic function `%%%%%s` not found%s."
2112 extra = '' if lm is None else (' (But line magic `%%%s` exists, '
2119 extra = '' if lm is None else (' (But line magic `%%%s` exists, '
2113 'did you mean that instead?)' % magic_name )
2120 'did you mean that instead?)' % magic_name )
2114 error(etpl % (magic_name, extra))
2121 error(etpl % (magic_name, extra))
2115 else:
2122 else:
2116 # Note: this is the distance in the stack to the user's frame.
2123 # Note: this is the distance in the stack to the user's frame.
2117 # This will need to be updated if the internal calling logic gets
2124 # This will need to be updated if the internal calling logic gets
2118 # refactored, or else we'll be expanding the wrong variables.
2125 # refactored, or else we'll be expanding the wrong variables.
2119 stack_depth = 2
2126 stack_depth = 2
2120 magic_arg_s = self.var_expand(line, stack_depth)
2127 magic_arg_s = self.var_expand(line, stack_depth)
2121 with self.builtin_trap:
2128 with self.builtin_trap:
2122 result = fn(magic_arg_s, cell)
2129 result = fn(magic_arg_s, cell)
2123 return result
2130 return result
2124
2131
2125 def find_line_magic(self, magic_name):
2132 def find_line_magic(self, magic_name):
2126 """Find and return a line magic by name.
2133 """Find and return a line magic by name.
2127
2134
2128 Returns None if the magic isn't found."""
2135 Returns None if the magic isn't found."""
2129 return self.magics_manager.magics['line'].get(magic_name)
2136 return self.magics_manager.magics['line'].get(magic_name)
2130
2137
2131 def find_cell_magic(self, magic_name):
2138 def find_cell_magic(self, magic_name):
2132 """Find and return a cell magic by name.
2139 """Find and return a cell magic by name.
2133
2140
2134 Returns None if the magic isn't found."""
2141 Returns None if the magic isn't found."""
2135 return self.magics_manager.magics['cell'].get(magic_name)
2142 return self.magics_manager.magics['cell'].get(magic_name)
2136
2143
2137 def find_magic(self, magic_name, magic_kind='line'):
2144 def find_magic(self, magic_name, magic_kind='line'):
2138 """Find and return a magic of the given type by name.
2145 """Find and return a magic of the given type by name.
2139
2146
2140 Returns None if the magic isn't found."""
2147 Returns None if the magic isn't found."""
2141 return self.magics_manager.magics[magic_kind].get(magic_name)
2148 return self.magics_manager.magics[magic_kind].get(magic_name)
2142
2149
2143 def magic(self, arg_s):
2150 def magic(self, arg_s):
2144 """DEPRECATED. Use run_line_magic() instead.
2151 """DEPRECATED. Use run_line_magic() instead.
2145
2152
2146 Call a magic function by name.
2153 Call a magic function by name.
2147
2154
2148 Input: a string containing the name of the magic function to call and
2155 Input: a string containing the name of the magic function to call and
2149 any additional arguments to be passed to the magic.
2156 any additional arguments to be passed to the magic.
2150
2157
2151 magic('name -opt foo bar') is equivalent to typing at the ipython
2158 magic('name -opt foo bar') is equivalent to typing at the ipython
2152 prompt:
2159 prompt:
2153
2160
2154 In[1]: %name -opt foo bar
2161 In[1]: %name -opt foo bar
2155
2162
2156 To call a magic without arguments, simply use magic('name').
2163 To call a magic without arguments, simply use magic('name').
2157
2164
2158 This provides a proper Python function to call IPython's magics in any
2165 This provides a proper Python function to call IPython's magics in any
2159 valid Python code you can type at the interpreter, including loops and
2166 valid Python code you can type at the interpreter, including loops and
2160 compound statements.
2167 compound statements.
2161 """
2168 """
2162 # TODO: should we issue a loud deprecation warning here?
2169 # TODO: should we issue a loud deprecation warning here?
2163 magic_name, _, magic_arg_s = arg_s.partition(' ')
2170 magic_name, _, magic_arg_s = arg_s.partition(' ')
2164 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2171 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2165 return self.run_line_magic(magic_name, magic_arg_s)
2172 return self.run_line_magic(magic_name, magic_arg_s)
2166
2173
2167 #-------------------------------------------------------------------------
2174 #-------------------------------------------------------------------------
2168 # Things related to macros
2175 # Things related to macros
2169 #-------------------------------------------------------------------------
2176 #-------------------------------------------------------------------------
2170
2177
2171 def define_macro(self, name, themacro):
2178 def define_macro(self, name, themacro):
2172 """Define a new macro
2179 """Define a new macro
2173
2180
2174 Parameters
2181 Parameters
2175 ----------
2182 ----------
2176 name : str
2183 name : str
2177 The name of the macro.
2184 The name of the macro.
2178 themacro : str or Macro
2185 themacro : str or Macro
2179 The action to do upon invoking the macro. If a string, a new
2186 The action to do upon invoking the macro. If a string, a new
2180 Macro object is created by passing the string to it.
2187 Macro object is created by passing the string to it.
2181 """
2188 """
2182
2189
2183 from IPython.core import macro
2190 from IPython.core import macro
2184
2191
2185 if isinstance(themacro, basestring):
2192 if isinstance(themacro, basestring):
2186 themacro = macro.Macro(themacro)
2193 themacro = macro.Macro(themacro)
2187 if not isinstance(themacro, macro.Macro):
2194 if not isinstance(themacro, macro.Macro):
2188 raise ValueError('A macro must be a string or a Macro instance.')
2195 raise ValueError('A macro must be a string or a Macro instance.')
2189 self.user_ns[name] = themacro
2196 self.user_ns[name] = themacro
2190
2197
2191 #-------------------------------------------------------------------------
2198 #-------------------------------------------------------------------------
2192 # Things related to the running of system commands
2199 # Things related to the running of system commands
2193 #-------------------------------------------------------------------------
2200 #-------------------------------------------------------------------------
2194
2201
2195 def system_piped(self, cmd):
2202 def system_piped(self, cmd):
2196 """Call the given cmd in a subprocess, piping stdout/err
2203 """Call the given cmd in a subprocess, piping stdout/err
2197
2204
2198 Parameters
2205 Parameters
2199 ----------
2206 ----------
2200 cmd : str
2207 cmd : str
2201 Command to execute (can not end in '&', as background processes are
2208 Command to execute (can not end in '&', as background processes are
2202 not supported. Should not be a command that expects input
2209 not supported. Should not be a command that expects input
2203 other than simple text.
2210 other than simple text.
2204 """
2211 """
2205 if cmd.rstrip().endswith('&'):
2212 if cmd.rstrip().endswith('&'):
2206 # this is *far* from a rigorous test
2213 # this is *far* from a rigorous test
2207 # We do not support backgrounding processes because we either use
2214 # We do not support backgrounding processes because we either use
2208 # pexpect or pipes to read from. Users can always just call
2215 # pexpect or pipes to read from. Users can always just call
2209 # os.system() or use ip.system=ip.system_raw
2216 # os.system() or use ip.system=ip.system_raw
2210 # if they really want a background process.
2217 # if they really want a background process.
2211 raise OSError("Background processes not supported.")
2218 raise OSError("Background processes not supported.")
2212
2219
2213 # we explicitly do NOT return the subprocess status code, because
2220 # we explicitly do NOT return the subprocess status code, because
2214 # a non-None value would trigger :func:`sys.displayhook` calls.
2221 # a non-None value would trigger :func:`sys.displayhook` calls.
2215 # Instead, we store the exit_code in user_ns.
2222 # Instead, we store the exit_code in user_ns.
2216 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2223 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2217
2224
2218 def system_raw(self, cmd):
2225 def system_raw(self, cmd):
2219 """Call the given cmd in a subprocess using os.system
2226 """Call the given cmd in a subprocess using os.system
2220
2227
2221 Parameters
2228 Parameters
2222 ----------
2229 ----------
2223 cmd : str
2230 cmd : str
2224 Command to execute.
2231 Command to execute.
2225 """
2232 """
2226 cmd = self.var_expand(cmd, depth=1)
2233 cmd = self.var_expand(cmd, depth=1)
2227 # protect os.system from UNC paths on Windows, which it can't handle:
2234 # protect os.system from UNC paths on Windows, which it can't handle:
2228 if sys.platform == 'win32':
2235 if sys.platform == 'win32':
2229 from IPython.utils._process_win32 import AvoidUNCPath
2236 from IPython.utils._process_win32 import AvoidUNCPath
2230 with AvoidUNCPath() as path:
2237 with AvoidUNCPath() as path:
2231 if path is not None:
2238 if path is not None:
2232 cmd = '"pushd %s &&"%s' % (path, cmd)
2239 cmd = '"pushd %s &&"%s' % (path, cmd)
2233 cmd = py3compat.unicode_to_str(cmd)
2240 cmd = py3compat.unicode_to_str(cmd)
2234 ec = os.system(cmd)
2241 ec = os.system(cmd)
2235 else:
2242 else:
2236 cmd = py3compat.unicode_to_str(cmd)
2243 cmd = py3compat.unicode_to_str(cmd)
2237 ec = os.system(cmd)
2244 ec = os.system(cmd)
2238
2245
2239 # We explicitly do NOT return the subprocess status code, because
2246 # We explicitly do NOT return the subprocess status code, because
2240 # a non-None value would trigger :func:`sys.displayhook` calls.
2247 # a non-None value would trigger :func:`sys.displayhook` calls.
2241 # Instead, we store the exit_code in user_ns.
2248 # Instead, we store the exit_code in user_ns.
2242 self.user_ns['_exit_code'] = ec
2249 self.user_ns['_exit_code'] = ec
2243
2250
2244 # use piped system by default, because it is better behaved
2251 # use piped system by default, because it is better behaved
2245 system = system_piped
2252 system = system_piped
2246
2253
2247 def getoutput(self, cmd, split=True, depth=0):
2254 def getoutput(self, cmd, split=True, depth=0):
2248 """Get output (possibly including stderr) from a subprocess.
2255 """Get output (possibly including stderr) from a subprocess.
2249
2256
2250 Parameters
2257 Parameters
2251 ----------
2258 ----------
2252 cmd : str
2259 cmd : str
2253 Command to execute (can not end in '&', as background processes are
2260 Command to execute (can not end in '&', as background processes are
2254 not supported.
2261 not supported.
2255 split : bool, optional
2262 split : bool, optional
2256 If True, split the output into an IPython SList. Otherwise, an
2263 If True, split the output into an IPython SList. Otherwise, an
2257 IPython LSString is returned. These are objects similar to normal
2264 IPython LSString is returned. These are objects similar to normal
2258 lists and strings, with a few convenience attributes for easier
2265 lists and strings, with a few convenience attributes for easier
2259 manipulation of line-based output. You can use '?' on them for
2266 manipulation of line-based output. You can use '?' on them for
2260 details.
2267 details.
2261 depth : int, optional
2268 depth : int, optional
2262 How many frames above the caller are the local variables which should
2269 How many frames above the caller are the local variables which should
2263 be expanded in the command string? The default (0) assumes that the
2270 be expanded in the command string? The default (0) assumes that the
2264 expansion variables are in the stack frame calling this function.
2271 expansion variables are in the stack frame calling this function.
2265 """
2272 """
2266 if cmd.rstrip().endswith('&'):
2273 if cmd.rstrip().endswith('&'):
2267 # this is *far* from a rigorous test
2274 # this is *far* from a rigorous test
2268 raise OSError("Background processes not supported.")
2275 raise OSError("Background processes not supported.")
2269 out = getoutput(self.var_expand(cmd, depth=depth+1))
2276 out = getoutput(self.var_expand(cmd, depth=depth+1))
2270 if split:
2277 if split:
2271 out = SList(out.splitlines())
2278 out = SList(out.splitlines())
2272 else:
2279 else:
2273 out = LSString(out)
2280 out = LSString(out)
2274 return out
2281 return out
2275
2282
2276 #-------------------------------------------------------------------------
2283 #-------------------------------------------------------------------------
2277 # Things related to aliases
2284 # Things related to aliases
2278 #-------------------------------------------------------------------------
2285 #-------------------------------------------------------------------------
2279
2286
2280 def init_alias(self):
2287 def init_alias(self):
2281 self.alias_manager = AliasManager(shell=self, config=self.config)
2288 self.alias_manager = AliasManager(shell=self, config=self.config)
2282 self.configurables.append(self.alias_manager)
2289 self.configurables.append(self.alias_manager)
2283 self.ns_table['alias'] = self.alias_manager.alias_table,
2290 self.ns_table['alias'] = self.alias_manager.alias_table,
2284
2291
2285 #-------------------------------------------------------------------------
2292 #-------------------------------------------------------------------------
2286 # Things related to extensions
2293 # Things related to extensions
2287 #-------------------------------------------------------------------------
2294 #-------------------------------------------------------------------------
2288
2295
2289 def init_extension_manager(self):
2296 def init_extension_manager(self):
2290 self.extension_manager = ExtensionManager(shell=self, config=self.config)
2297 self.extension_manager = ExtensionManager(shell=self, config=self.config)
2291 self.configurables.append(self.extension_manager)
2298 self.configurables.append(self.extension_manager)
2292
2299
2293 #-------------------------------------------------------------------------
2300 #-------------------------------------------------------------------------
2294 # Things related to payloads
2301 # Things related to payloads
2295 #-------------------------------------------------------------------------
2302 #-------------------------------------------------------------------------
2296
2303
2297 def init_payload(self):
2304 def init_payload(self):
2298 self.payload_manager = PayloadManager(config=self.config)
2305 self.payload_manager = PayloadManager(config=self.config)
2299 self.configurables.append(self.payload_manager)
2306 self.configurables.append(self.payload_manager)
2300
2307
2301 #-------------------------------------------------------------------------
2308 #-------------------------------------------------------------------------
2302 # Things related to the prefilter
2309 # Things related to the prefilter
2303 #-------------------------------------------------------------------------
2310 #-------------------------------------------------------------------------
2304
2311
2305 def init_prefilter(self):
2312 def init_prefilter(self):
2306 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
2313 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
2307 self.configurables.append(self.prefilter_manager)
2314 self.configurables.append(self.prefilter_manager)
2308 # Ultimately this will be refactored in the new interpreter code, but
2315 # Ultimately this will be refactored in the new interpreter code, but
2309 # for now, we should expose the main prefilter method (there's legacy
2316 # for now, we should expose the main prefilter method (there's legacy
2310 # code out there that may rely on this).
2317 # code out there that may rely on this).
2311 self.prefilter = self.prefilter_manager.prefilter_lines
2318 self.prefilter = self.prefilter_manager.prefilter_lines
2312
2319
2313 def auto_rewrite_input(self, cmd):
2320 def auto_rewrite_input(self, cmd):
2314 """Print to the screen the rewritten form of the user's command.
2321 """Print to the screen the rewritten form of the user's command.
2315
2322
2316 This shows visual feedback by rewriting input lines that cause
2323 This shows visual feedback by rewriting input lines that cause
2317 automatic calling to kick in, like::
2324 automatic calling to kick in, like::
2318
2325
2319 /f x
2326 /f x
2320
2327
2321 into::
2328 into::
2322
2329
2323 ------> f(x)
2330 ------> f(x)
2324
2331
2325 after the user's input prompt. This helps the user understand that the
2332 after the user's input prompt. This helps the user understand that the
2326 input line was transformed automatically by IPython.
2333 input line was transformed automatically by IPython.
2327 """
2334 """
2328 if not self.show_rewritten_input:
2335 if not self.show_rewritten_input:
2329 return
2336 return
2330
2337
2331 rw = self.prompt_manager.render('rewrite') + cmd
2338 rw = self.prompt_manager.render('rewrite') + cmd
2332
2339
2333 try:
2340 try:
2334 # plain ascii works better w/ pyreadline, on some machines, so
2341 # plain ascii works better w/ pyreadline, on some machines, so
2335 # we use it and only print uncolored rewrite if we have unicode
2342 # we use it and only print uncolored rewrite if we have unicode
2336 rw = str(rw)
2343 rw = str(rw)
2337 print(rw, file=io.stdout)
2344 print(rw, file=io.stdout)
2338 except UnicodeEncodeError:
2345 except UnicodeEncodeError:
2339 print("------> " + cmd)
2346 print("------> " + cmd)
2340
2347
2341 #-------------------------------------------------------------------------
2348 #-------------------------------------------------------------------------
2342 # Things related to extracting values/expressions from kernel and user_ns
2349 # Things related to extracting values/expressions from kernel and user_ns
2343 #-------------------------------------------------------------------------
2350 #-------------------------------------------------------------------------
2344
2351
2345 def _simple_error(self):
2352 def _simple_error(self):
2346 etype, value = sys.exc_info()[:2]
2353 etype, value = sys.exc_info()[:2]
2347 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
2354 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
2348
2355
2349 def user_variables(self, names):
2356 def user_variables(self, names):
2350 """Get a list of variable names from the user's namespace.
2357 """Get a list of variable names from the user's namespace.
2351
2358
2352 Parameters
2359 Parameters
2353 ----------
2360 ----------
2354 names : list of strings
2361 names : list of strings
2355 A list of names of variables to be read from the user namespace.
2362 A list of names of variables to be read from the user namespace.
2356
2363
2357 Returns
2364 Returns
2358 -------
2365 -------
2359 A dict, keyed by the input names and with the repr() of each value.
2366 A dict, keyed by the input names and with the repr() of each value.
2360 """
2367 """
2361 out = {}
2368 out = {}
2362 user_ns = self.user_ns
2369 user_ns = self.user_ns
2363 for varname in names:
2370 for varname in names:
2364 try:
2371 try:
2365 value = repr(user_ns[varname])
2372 value = repr(user_ns[varname])
2366 except:
2373 except:
2367 value = self._simple_error()
2374 value = self._simple_error()
2368 out[varname] = value
2375 out[varname] = value
2369 return out
2376 return out
2370
2377
2371 def user_expressions(self, expressions):
2378 def user_expressions(self, expressions):
2372 """Evaluate a dict of expressions in the user's namespace.
2379 """Evaluate a dict of expressions in the user's namespace.
2373
2380
2374 Parameters
2381 Parameters
2375 ----------
2382 ----------
2376 expressions : dict
2383 expressions : dict
2377 A dict with string keys and string values. The expression values
2384 A dict with string keys and string values. The expression values
2378 should be valid Python expressions, each of which will be evaluated
2385 should be valid Python expressions, each of which will be evaluated
2379 in the user namespace.
2386 in the user namespace.
2380
2387
2381 Returns
2388 Returns
2382 -------
2389 -------
2383 A dict, keyed like the input expressions dict, with the repr() of each
2390 A dict, keyed like the input expressions dict, with the repr() of each
2384 value.
2391 value.
2385 """
2392 """
2386 out = {}
2393 out = {}
2387 user_ns = self.user_ns
2394 user_ns = self.user_ns
2388 global_ns = self.user_global_ns
2395 global_ns = self.user_global_ns
2389 for key, expr in expressions.iteritems():
2396 for key, expr in expressions.iteritems():
2390 try:
2397 try:
2391 value = repr(eval(expr, global_ns, user_ns))
2398 value = repr(eval(expr, global_ns, user_ns))
2392 except:
2399 except:
2393 value = self._simple_error()
2400 value = self._simple_error()
2394 out[key] = value
2401 out[key] = value
2395 return out
2402 return out
2396
2403
2397 #-------------------------------------------------------------------------
2404 #-------------------------------------------------------------------------
2398 # Things related to the running of code
2405 # Things related to the running of code
2399 #-------------------------------------------------------------------------
2406 #-------------------------------------------------------------------------
2400
2407
2401 def ex(self, cmd):
2408 def ex(self, cmd):
2402 """Execute a normal python statement in user namespace."""
2409 """Execute a normal python statement in user namespace."""
2403 with self.builtin_trap:
2410 with self.builtin_trap:
2404 exec cmd in self.user_global_ns, self.user_ns
2411 exec cmd in self.user_global_ns, self.user_ns
2405
2412
2406 def ev(self, expr):
2413 def ev(self, expr):
2407 """Evaluate python expression expr in user namespace.
2414 """Evaluate python expression expr in user namespace.
2408
2415
2409 Returns the result of evaluation
2416 Returns the result of evaluation
2410 """
2417 """
2411 with self.builtin_trap:
2418 with self.builtin_trap:
2412 return eval(expr, self.user_global_ns, self.user_ns)
2419 return eval(expr, self.user_global_ns, self.user_ns)
2413
2420
2414 def safe_execfile(self, fname, *where, **kw):
2421 def safe_execfile(self, fname, *where, **kw):
2415 """A safe version of the builtin execfile().
2422 """A safe version of the builtin execfile().
2416
2423
2417 This version will never throw an exception, but instead print
2424 This version will never throw an exception, but instead print
2418 helpful error messages to the screen. This only works on pure
2425 helpful error messages to the screen. This only works on pure
2419 Python files with the .py extension.
2426 Python files with the .py extension.
2420
2427
2421 Parameters
2428 Parameters
2422 ----------
2429 ----------
2423 fname : string
2430 fname : string
2424 The name of the file to be executed.
2431 The name of the file to be executed.
2425 where : tuple
2432 where : tuple
2426 One or two namespaces, passed to execfile() as (globals,locals).
2433 One or two namespaces, passed to execfile() as (globals,locals).
2427 If only one is given, it is passed as both.
2434 If only one is given, it is passed as both.
2428 exit_ignore : bool (False)
2435 exit_ignore : bool (False)
2429 If True, then silence SystemExit for non-zero status (it is always
2436 If True, then silence SystemExit for non-zero status (it is always
2430 silenced for zero status, as it is so common).
2437 silenced for zero status, as it is so common).
2431 raise_exceptions : bool (False)
2438 raise_exceptions : bool (False)
2432 If True raise exceptions everywhere. Meant for testing.
2439 If True raise exceptions everywhere. Meant for testing.
2433
2440
2434 """
2441 """
2435 kw.setdefault('exit_ignore', False)
2442 kw.setdefault('exit_ignore', False)
2436 kw.setdefault('raise_exceptions', False)
2443 kw.setdefault('raise_exceptions', False)
2437
2444
2438 fname = os.path.abspath(os.path.expanduser(fname))
2445 fname = os.path.abspath(os.path.expanduser(fname))
2439
2446
2440 # Make sure we can open the file
2447 # Make sure we can open the file
2441 try:
2448 try:
2442 with open(fname) as thefile:
2449 with open(fname) as thefile:
2443 pass
2450 pass
2444 except:
2451 except:
2445 warn('Could not open file <%s> for safe execution.' % fname)
2452 warn('Could not open file <%s> for safe execution.' % fname)
2446 return
2453 return
2447
2454
2448 # Find things also in current directory. This is needed to mimic the
2455 # Find things also in current directory. This is needed to mimic the
2449 # behavior of running a script from the system command line, where
2456 # behavior of running a script from the system command line, where
2450 # Python inserts the script's directory into sys.path
2457 # Python inserts the script's directory into sys.path
2451 dname = os.path.dirname(fname)
2458 dname = os.path.dirname(fname)
2452
2459
2453 with prepended_to_syspath(dname):
2460 with prepended_to_syspath(dname):
2454 try:
2461 try:
2455 py3compat.execfile(fname,*where)
2462 py3compat.execfile(fname,*where)
2456 except SystemExit as status:
2463 except SystemExit as status:
2457 # If the call was made with 0 or None exit status (sys.exit(0)
2464 # If the call was made with 0 or None exit status (sys.exit(0)
2458 # or sys.exit() ), don't bother showing a traceback, as both of
2465 # or sys.exit() ), don't bother showing a traceback, as both of
2459 # these are considered normal by the OS:
2466 # these are considered normal by the OS:
2460 # > python -c'import sys;sys.exit(0)'; echo $?
2467 # > python -c'import sys;sys.exit(0)'; echo $?
2461 # 0
2468 # 0
2462 # > python -c'import sys;sys.exit()'; echo $?
2469 # > python -c'import sys;sys.exit()'; echo $?
2463 # 0
2470 # 0
2464 # For other exit status, we show the exception unless
2471 # For other exit status, we show the exception unless
2465 # explicitly silenced, but only in short form.
2472 # explicitly silenced, but only in short form.
2466 if kw['raise_exceptions']:
2473 if kw['raise_exceptions']:
2467 raise
2474 raise
2468 if status.code not in (0, None) and not kw['exit_ignore']:
2475 if status.code not in (0, None) and not kw['exit_ignore']:
2469 self.showtraceback(exception_only=True)
2476 self.showtraceback(exception_only=True)
2470 except:
2477 except:
2471 if kw['raise_exceptions']:
2478 if kw['raise_exceptions']:
2472 raise
2479 raise
2473 self.showtraceback()
2480 self.showtraceback()
2474
2481
2475 def safe_execfile_ipy(self, fname):
2482 def safe_execfile_ipy(self, fname):
2476 """Like safe_execfile, but for .ipy files with IPython syntax.
2483 """Like safe_execfile, but for .ipy files with IPython syntax.
2477
2484
2478 Parameters
2485 Parameters
2479 ----------
2486 ----------
2480 fname : str
2487 fname : str
2481 The name of the file to execute. The filename must have a
2488 The name of the file to execute. The filename must have a
2482 .ipy extension.
2489 .ipy extension.
2483 """
2490 """
2484 fname = os.path.abspath(os.path.expanduser(fname))
2491 fname = os.path.abspath(os.path.expanduser(fname))
2485
2492
2486 # Make sure we can open the file
2493 # Make sure we can open the file
2487 try:
2494 try:
2488 with open(fname) as thefile:
2495 with open(fname) as thefile:
2489 pass
2496 pass
2490 except:
2497 except:
2491 warn('Could not open file <%s> for safe execution.' % fname)
2498 warn('Could not open file <%s> for safe execution.' % fname)
2492 return
2499 return
2493
2500
2494 # Find things also in current directory. This is needed to mimic the
2501 # Find things also in current directory. This is needed to mimic the
2495 # behavior of running a script from the system command line, where
2502 # behavior of running a script from the system command line, where
2496 # Python inserts the script's directory into sys.path
2503 # Python inserts the script's directory into sys.path
2497 dname = os.path.dirname(fname)
2504 dname = os.path.dirname(fname)
2498
2505
2499 with prepended_to_syspath(dname):
2506 with prepended_to_syspath(dname):
2500 try:
2507 try:
2501 with open(fname) as thefile:
2508 with open(fname) as thefile:
2502 # self.run_cell currently captures all exceptions
2509 # self.run_cell currently captures all exceptions
2503 # raised in user code. It would be nice if there were
2510 # raised in user code. It would be nice if there were
2504 # versions of runlines, execfile that did raise, so
2511 # versions of runlines, execfile that did raise, so
2505 # we could catch the errors.
2512 # we could catch the errors.
2506 self.run_cell(thefile.read(), store_history=False)
2513 self.run_cell(thefile.read(), store_history=False)
2507 except:
2514 except:
2508 self.showtraceback()
2515 self.showtraceback()
2509 warn('Unknown failure executing file: <%s>' % fname)
2516 warn('Unknown failure executing file: <%s>' % fname)
2510
2517
2511 def safe_run_module(self, mod_name, where):
2518 def safe_run_module(self, mod_name, where):
2512 """A safe version of runpy.run_module().
2519 """A safe version of runpy.run_module().
2513
2520
2514 This version will never throw an exception, but instead print
2521 This version will never throw an exception, but instead print
2515 helpful error messages to the screen.
2522 helpful error messages to the screen.
2516
2523
2517 Parameters
2524 Parameters
2518 ----------
2525 ----------
2519 mod_name : string
2526 mod_name : string
2520 The name of the module to be executed.
2527 The name of the module to be executed.
2521 where : dict
2528 where : dict
2522 The globals namespace.
2529 The globals namespace.
2523 """
2530 """
2524 try:
2531 try:
2525 where.update(
2532 where.update(
2526 runpy.run_module(str(mod_name), run_name="__main__",
2533 runpy.run_module(str(mod_name), run_name="__main__",
2527 alter_sys=True)
2534 alter_sys=True)
2528 )
2535 )
2529 except:
2536 except:
2530 self.showtraceback()
2537 self.showtraceback()
2531 warn('Unknown failure executing module: <%s>' % mod_name)
2538 warn('Unknown failure executing module: <%s>' % mod_name)
2532
2539
2533 def _run_cached_cell_magic(self, magic_name, line):
2540 def _run_cached_cell_magic(self, magic_name, line):
2534 """Special method to call a cell magic with the data stored in self.
2541 """Special method to call a cell magic with the data stored in self.
2535 """
2542 """
2536 cell = self._current_cell_magic_body
2543 cell = self._current_cell_magic_body
2537 self._current_cell_magic_body = None
2544 self._current_cell_magic_body = None
2538 return self.run_cell_magic(magic_name, line, cell)
2545 return self.run_cell_magic(magic_name, line, cell)
2539
2546
2540 def run_cell(self, raw_cell, store_history=False, silent=False):
2547 def run_cell(self, raw_cell, store_history=False, silent=False):
2541 """Run a complete IPython cell.
2548 """Run a complete IPython cell.
2542
2549
2543 Parameters
2550 Parameters
2544 ----------
2551 ----------
2545 raw_cell : str
2552 raw_cell : str
2546 The code (including IPython code such as %magic functions) to run.
2553 The code (including IPython code such as %magic functions) to run.
2547 store_history : bool
2554 store_history : bool
2548 If True, the raw and translated cell will be stored in IPython's
2555 If True, the raw and translated cell will be stored in IPython's
2549 history. For user code calling back into IPython's machinery, this
2556 history. For user code calling back into IPython's machinery, this
2550 should be set to False.
2557 should be set to False.
2551 silent : bool
2558 silent : bool
2552 If True, avoid side-effects, such as implicit displayhooks and
2559 If True, avoid side-effects, such as implicit displayhooks and
2553 and logging. silent=True forces store_history=False.
2560 and logging. silent=True forces store_history=False.
2554 """
2561 """
2555 if (not raw_cell) or raw_cell.isspace():
2562 if (not raw_cell) or raw_cell.isspace():
2556 return
2563 return
2557
2564
2558 if silent:
2565 if silent:
2559 store_history = False
2566 store_history = False
2560
2567
2561 self.input_splitter.push(raw_cell)
2568 self.input_splitter.push(raw_cell)
2562
2569
2563 # Check for cell magics, which leave state behind. This interface is
2570 # Check for cell magics, which leave state behind. This interface is
2564 # ugly, we need to do something cleaner later... Now the logic is
2571 # ugly, we need to do something cleaner later... Now the logic is
2565 # simply that the input_splitter remembers if there was a cell magic,
2572 # simply that the input_splitter remembers if there was a cell magic,
2566 # and in that case we grab the cell body.
2573 # and in that case we grab the cell body.
2567 if self.input_splitter.cell_magic_parts:
2574 if self.input_splitter.cell_magic_parts:
2568 self._current_cell_magic_body = \
2575 self._current_cell_magic_body = \
2569 ''.join(self.input_splitter.cell_magic_parts)
2576 ''.join(self.input_splitter.cell_magic_parts)
2570 cell = self.input_splitter.source_reset()
2577 cell = self.input_splitter.source_reset()
2571
2578
2572 with self.builtin_trap:
2579 with self.builtin_trap:
2573 prefilter_failed = False
2580 prefilter_failed = False
2574 if len(cell.splitlines()) == 1:
2581 if len(cell.splitlines()) == 1:
2575 try:
2582 try:
2576 # use prefilter_lines to handle trailing newlines
2583 # use prefilter_lines to handle trailing newlines
2577 # restore trailing newline for ast.parse
2584 # restore trailing newline for ast.parse
2578 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2585 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2579 except AliasError as e:
2586 except AliasError as e:
2580 error(e)
2587 error(e)
2581 prefilter_failed = True
2588 prefilter_failed = True
2582 except Exception:
2589 except Exception:
2583 # don't allow prefilter errors to crash IPython
2590 # don't allow prefilter errors to crash IPython
2584 self.showtraceback()
2591 self.showtraceback()
2585 prefilter_failed = True
2592 prefilter_failed = True
2586
2593
2587 # Store raw and processed history
2594 # Store raw and processed history
2588 if store_history:
2595 if store_history:
2589 self.history_manager.store_inputs(self.execution_count,
2596 self.history_manager.store_inputs(self.execution_count,
2590 cell, raw_cell)
2597 cell, raw_cell)
2591 if not silent:
2598 if not silent:
2592 self.logger.log(cell, raw_cell)
2599 self.logger.log(cell, raw_cell)
2593
2600
2594 if not prefilter_failed:
2601 if not prefilter_failed:
2595 # don't run if prefilter failed
2602 # don't run if prefilter failed
2596 cell_name = self.compile.cache(cell, self.execution_count)
2603 cell_name = self.compile.cache(cell, self.execution_count)
2597
2604
2598 with self.display_trap:
2605 with self.display_trap:
2599 try:
2606 try:
2600 code_ast = self.compile.ast_parse(cell,
2607 code_ast = self.compile.ast_parse(cell,
2601 filename=cell_name)
2608 filename=cell_name)
2602 except IndentationError:
2609 except IndentationError:
2603 self.showindentationerror()
2610 self.showindentationerror()
2604 if store_history:
2611 if store_history:
2605 self.execution_count += 1
2612 self.execution_count += 1
2606 return None
2613 return None
2607 except (OverflowError, SyntaxError, ValueError, TypeError,
2614 except (OverflowError, SyntaxError, ValueError, TypeError,
2608 MemoryError):
2615 MemoryError):
2609 self.showsyntaxerror()
2616 self.showsyntaxerror()
2610 if store_history:
2617 if store_history:
2611 self.execution_count += 1
2618 self.execution_count += 1
2612 return None
2619 return None
2613
2620
2621 code_ast = self.transform_ast(code_ast)
2622
2614 interactivity = "none" if silent else self.ast_node_interactivity
2623 interactivity = "none" if silent else self.ast_node_interactivity
2615 self.run_ast_nodes(code_ast.body, cell_name,
2624 self.run_ast_nodes(code_ast.body, cell_name,
2616 interactivity=interactivity)
2625 interactivity=interactivity)
2617
2626
2618 # Execute any registered post-execution functions.
2627 # Execute any registered post-execution functions.
2619 # unless we are silent
2628 # unless we are silent
2620 post_exec = [] if silent else self._post_execute.iteritems()
2629 post_exec = [] if silent else self._post_execute.iteritems()
2621
2630
2622 for func, status in post_exec:
2631 for func, status in post_exec:
2623 if self.disable_failing_post_execute and not status:
2632 if self.disable_failing_post_execute and not status:
2624 continue
2633 continue
2625 try:
2634 try:
2626 func()
2635 func()
2627 except KeyboardInterrupt:
2636 except KeyboardInterrupt:
2628 print("\nKeyboardInterrupt", file=io.stderr)
2637 print("\nKeyboardInterrupt", file=io.stderr)
2629 except Exception:
2638 except Exception:
2630 # register as failing:
2639 # register as failing:
2631 self._post_execute[func] = False
2640 self._post_execute[func] = False
2632 self.showtraceback()
2641 self.showtraceback()
2633 print('\n'.join([
2642 print('\n'.join([
2634 "post-execution function %r produced an error." % func,
2643 "post-execution function %r produced an error." % func,
2635 "If this problem persists, you can disable failing post-exec functions with:",
2644 "If this problem persists, you can disable failing post-exec functions with:",
2636 "",
2645 "",
2637 " get_ipython().disable_failing_post_execute = True"
2646 " get_ipython().disable_failing_post_execute = True"
2638 ]), file=io.stderr)
2647 ]), file=io.stderr)
2639
2648
2640 if store_history:
2649 if store_history:
2641 # Write output to the database. Does nothing unless
2650 # Write output to the database. Does nothing unless
2642 # history output logging is enabled.
2651 # history output logging is enabled.
2643 self.history_manager.store_output(self.execution_count)
2652 self.history_manager.store_output(self.execution_count)
2644 # Each cell is a *single* input, regardless of how many lines it has
2653 # Each cell is a *single* input, regardless of how many lines it has
2645 self.execution_count += 1
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 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'):
2681 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'):
2648 """Run a sequence of AST nodes. The execution mode depends on the
2682 """Run a sequence of AST nodes. The execution mode depends on the
2649 interactivity parameter.
2683 interactivity parameter.
2650
2684
2651 Parameters
2685 Parameters
2652 ----------
2686 ----------
2653 nodelist : list
2687 nodelist : list
2654 A sequence of AST nodes to run.
2688 A sequence of AST nodes to run.
2655 cell_name : str
2689 cell_name : str
2656 Will be passed to the compiler as the filename of the cell. Typically
2690 Will be passed to the compiler as the filename of the cell. Typically
2657 the value returned by ip.compile.cache(cell).
2691 the value returned by ip.compile.cache(cell).
2658 interactivity : str
2692 interactivity : str
2659 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2693 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2660 run interactively (displaying output from expressions). 'last_expr'
2694 run interactively (displaying output from expressions). 'last_expr'
2661 will run the last node interactively only if it is an expression (i.e.
2695 will run the last node interactively only if it is an expression (i.e.
2662 expressions in loops or other blocks are not displayed. Other values
2696 expressions in loops or other blocks are not displayed. Other values
2663 for this parameter will raise a ValueError.
2697 for this parameter will raise a ValueError.
2664 """
2698 """
2665 if not nodelist:
2699 if not nodelist:
2666 return
2700 return
2667
2701
2668 if interactivity == 'last_expr':
2702 if interactivity == 'last_expr':
2669 if isinstance(nodelist[-1], ast.Expr):
2703 if isinstance(nodelist[-1], ast.Expr):
2670 interactivity = "last"
2704 interactivity = "last"
2671 else:
2705 else:
2672 interactivity = "none"
2706 interactivity = "none"
2673
2707
2674 if interactivity == 'none':
2708 if interactivity == 'none':
2675 to_run_exec, to_run_interactive = nodelist, []
2709 to_run_exec, to_run_interactive = nodelist, []
2676 elif interactivity == 'last':
2710 elif interactivity == 'last':
2677 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2711 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2678 elif interactivity == 'all':
2712 elif interactivity == 'all':
2679 to_run_exec, to_run_interactive = [], nodelist
2713 to_run_exec, to_run_interactive = [], nodelist
2680 else:
2714 else:
2681 raise ValueError("Interactivity was %r" % interactivity)
2715 raise ValueError("Interactivity was %r" % interactivity)
2682
2716
2683 exec_count = self.execution_count
2717 exec_count = self.execution_count
2684
2718
2685 try:
2719 try:
2686 for i, node in enumerate(to_run_exec):
2720 for i, node in enumerate(to_run_exec):
2687 mod = ast.Module([node])
2721 mod = ast.Module([node])
2688 code = self.compile(mod, cell_name, "exec")
2722 code = self.compile(mod, cell_name, "exec")
2689 if self.run_code(code):
2723 if self.run_code(code):
2690 return True
2724 return True
2691
2725
2692 for i, node in enumerate(to_run_interactive):
2726 for i, node in enumerate(to_run_interactive):
2693 mod = ast.Interactive([node])
2727 mod = ast.Interactive([node])
2694 code = self.compile(mod, cell_name, "single")
2728 code = self.compile(mod, cell_name, "single")
2695 if self.run_code(code):
2729 if self.run_code(code):
2696 return True
2730 return True
2697
2731
2698 # Flush softspace
2732 # Flush softspace
2699 if softspace(sys.stdout, 0):
2733 if softspace(sys.stdout, 0):
2700 print()
2734 print()
2701
2735
2702 except:
2736 except:
2703 # It's possible to have exceptions raised here, typically by
2737 # It's possible to have exceptions raised here, typically by
2704 # compilation of odd code (such as a naked 'return' outside a
2738 # compilation of odd code (such as a naked 'return' outside a
2705 # function) that did parse but isn't valid. Typically the exception
2739 # function) that did parse but isn't valid. Typically the exception
2706 # is a SyntaxError, but it's safest just to catch anything and show
2740 # is a SyntaxError, but it's safest just to catch anything and show
2707 # the user a traceback.
2741 # the user a traceback.
2708
2742
2709 # We do only one try/except outside the loop to minimize the impact
2743 # We do only one try/except outside the loop to minimize the impact
2710 # on runtime, and also because if any node in the node list is
2744 # on runtime, and also because if any node in the node list is
2711 # broken, we should stop execution completely.
2745 # broken, we should stop execution completely.
2712 self.showtraceback()
2746 self.showtraceback()
2713
2747
2714 return False
2748 return False
2715
2749
2716 def run_code(self, code_obj):
2750 def run_code(self, code_obj):
2717 """Execute a code object.
2751 """Execute a code object.
2718
2752
2719 When an exception occurs, self.showtraceback() is called to display a
2753 When an exception occurs, self.showtraceback() is called to display a
2720 traceback.
2754 traceback.
2721
2755
2722 Parameters
2756 Parameters
2723 ----------
2757 ----------
2724 code_obj : code object
2758 code_obj : code object
2725 A compiled code object, to be executed
2759 A compiled code object, to be executed
2726
2760
2727 Returns
2761 Returns
2728 -------
2762 -------
2729 False : successful execution.
2763 False : successful execution.
2730 True : an error occurred.
2764 True : an error occurred.
2731 """
2765 """
2732
2766
2733 # Set our own excepthook in case the user code tries to call it
2767 # Set our own excepthook in case the user code tries to call it
2734 # directly, so that the IPython crash handler doesn't get triggered
2768 # directly, so that the IPython crash handler doesn't get triggered
2735 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2769 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2736
2770
2737 # we save the original sys.excepthook in the instance, in case config
2771 # we save the original sys.excepthook in the instance, in case config
2738 # code (such as magics) needs access to it.
2772 # code (such as magics) needs access to it.
2739 self.sys_excepthook = old_excepthook
2773 self.sys_excepthook = old_excepthook
2740 outflag = 1 # happens in more places, so it's easier as default
2774 outflag = 1 # happens in more places, so it's easier as default
2741 try:
2775 try:
2742 try:
2776 try:
2743 self.hooks.pre_run_code_hook()
2777 self.hooks.pre_run_code_hook()
2744 #rprint('Running code', repr(code_obj)) # dbg
2778 #rprint('Running code', repr(code_obj)) # dbg
2745 exec code_obj in self.user_global_ns, self.user_ns
2779 exec code_obj in self.user_global_ns, self.user_ns
2746 finally:
2780 finally:
2747 # Reset our crash handler in place
2781 # Reset our crash handler in place
2748 sys.excepthook = old_excepthook
2782 sys.excepthook = old_excepthook
2749 except SystemExit:
2783 except SystemExit:
2750 self.showtraceback(exception_only=True)
2784 self.showtraceback(exception_only=True)
2751 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2785 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2752 except self.custom_exceptions:
2786 except self.custom_exceptions:
2753 etype,value,tb = sys.exc_info()
2787 etype,value,tb = sys.exc_info()
2754 self.CustomTB(etype,value,tb)
2788 self.CustomTB(etype,value,tb)
2755 except:
2789 except:
2756 self.showtraceback()
2790 self.showtraceback()
2757 else:
2791 else:
2758 outflag = 0
2792 outflag = 0
2759 return outflag
2793 return outflag
2760
2794
2761 # For backwards compatibility
2795 # For backwards compatibility
2762 runcode = run_code
2796 runcode = run_code
2763
2797
2764 #-------------------------------------------------------------------------
2798 #-------------------------------------------------------------------------
2765 # Things related to GUI support and pylab
2799 # Things related to GUI support and pylab
2766 #-------------------------------------------------------------------------
2800 #-------------------------------------------------------------------------
2767
2801
2768 def enable_gui(self, gui=None):
2802 def enable_gui(self, gui=None):
2769 raise NotImplementedError('Implement enable_gui in a subclass')
2803 raise NotImplementedError('Implement enable_gui in a subclass')
2770
2804
2771 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
2805 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
2772 """Activate pylab support at runtime.
2806 """Activate pylab support at runtime.
2773
2807
2774 This turns on support for matplotlib, preloads into the interactive
2808 This turns on support for matplotlib, preloads into the interactive
2775 namespace all of numpy and pylab, and configures IPython to correctly
2809 namespace all of numpy and pylab, and configures IPython to correctly
2776 interact with the GUI event loop. The GUI backend to be used can be
2810 interact with the GUI event loop. The GUI backend to be used can be
2777 optionally selected with the optional :param:`gui` argument.
2811 optionally selected with the optional :param:`gui` argument.
2778
2812
2779 Parameters
2813 Parameters
2780 ----------
2814 ----------
2781 gui : optional, string
2815 gui : optional, string
2782
2816
2783 If given, dictates the choice of matplotlib GUI backend to use
2817 If given, dictates the choice of matplotlib GUI backend to use
2784 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2818 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2785 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2819 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2786 matplotlib (as dictated by the matplotlib build-time options plus the
2820 matplotlib (as dictated by the matplotlib build-time options plus the
2787 user's matplotlibrc configuration file). Note that not all backends
2821 user's matplotlibrc configuration file). Note that not all backends
2788 make sense in all contexts, for example a terminal ipython can't
2822 make sense in all contexts, for example a terminal ipython can't
2789 display figures inline.
2823 display figures inline.
2790 """
2824 """
2791 from IPython.core.pylabtools import mpl_runner
2825 from IPython.core.pylabtools import mpl_runner
2792 # We want to prevent the loading of pylab to pollute the user's
2826 # We want to prevent the loading of pylab to pollute the user's
2793 # namespace as shown by the %who* magics, so we execute the activation
2827 # namespace as shown by the %who* magics, so we execute the activation
2794 # code in an empty namespace, and we update *both* user_ns and
2828 # code in an empty namespace, and we update *both* user_ns and
2795 # user_ns_hidden with this information.
2829 # user_ns_hidden with this information.
2796 ns = {}
2830 ns = {}
2797 try:
2831 try:
2798 gui = pylab_activate(ns, gui, import_all, self, welcome_message=welcome_message)
2832 gui = pylab_activate(ns, gui, import_all, self, welcome_message=welcome_message)
2799 except KeyError:
2833 except KeyError:
2800 error("Backend %r not supported" % gui)
2834 error("Backend %r not supported" % gui)
2801 return
2835 return
2802 self.user_ns.update(ns)
2836 self.user_ns.update(ns)
2803 self.user_ns_hidden.update(ns)
2837 self.user_ns_hidden.update(ns)
2804 # Now we must activate the gui pylab wants to use, and fix %run to take
2838 # Now we must activate the gui pylab wants to use, and fix %run to take
2805 # plot updates into account
2839 # plot updates into account
2806 self.enable_gui(gui)
2840 self.enable_gui(gui)
2807 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2841 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2808 mpl_runner(self.safe_execfile)
2842 mpl_runner(self.safe_execfile)
2809
2843
2810 #-------------------------------------------------------------------------
2844 #-------------------------------------------------------------------------
2811 # Utilities
2845 # Utilities
2812 #-------------------------------------------------------------------------
2846 #-------------------------------------------------------------------------
2813
2847
2814 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
2848 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
2815 """Expand python variables in a string.
2849 """Expand python variables in a string.
2816
2850
2817 The depth argument indicates how many frames above the caller should
2851 The depth argument indicates how many frames above the caller should
2818 be walked to look for the local namespace where to expand variables.
2852 be walked to look for the local namespace where to expand variables.
2819
2853
2820 The global namespace for expansion is always the user's interactive
2854 The global namespace for expansion is always the user's interactive
2821 namespace.
2855 namespace.
2822 """
2856 """
2823 ns = self.user_ns.copy()
2857 ns = self.user_ns.copy()
2824 ns.update(sys._getframe(depth+1).f_locals)
2858 ns.update(sys._getframe(depth+1).f_locals)
2825 try:
2859 try:
2826 # We have to use .vformat() here, because 'self' is a valid and common
2860 # We have to use .vformat() here, because 'self' is a valid and common
2827 # name, and expanding **ns for .format() would make it collide with
2861 # name, and expanding **ns for .format() would make it collide with
2828 # the 'self' argument of the method.
2862 # the 'self' argument of the method.
2829 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
2863 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
2830 except Exception:
2864 except Exception:
2831 # if formatter couldn't format, just let it go untransformed
2865 # if formatter couldn't format, just let it go untransformed
2832 pass
2866 pass
2833 return cmd
2867 return cmd
2834
2868
2835 def mktempfile(self, data=None, prefix='ipython_edit_'):
2869 def mktempfile(self, data=None, prefix='ipython_edit_'):
2836 """Make a new tempfile and return its filename.
2870 """Make a new tempfile and return its filename.
2837
2871
2838 This makes a call to tempfile.mktemp, but it registers the created
2872 This makes a call to tempfile.mktemp, but it registers the created
2839 filename internally so ipython cleans it up at exit time.
2873 filename internally so ipython cleans it up at exit time.
2840
2874
2841 Optional inputs:
2875 Optional inputs:
2842
2876
2843 - data(None): if data is given, it gets written out to the temp file
2877 - data(None): if data is given, it gets written out to the temp file
2844 immediately, and the file is closed again."""
2878 immediately, and the file is closed again."""
2845
2879
2846 filename = tempfile.mktemp('.py', prefix)
2880 filename = tempfile.mktemp('.py', prefix)
2847 self.tempfiles.append(filename)
2881 self.tempfiles.append(filename)
2848
2882
2849 if data:
2883 if data:
2850 tmp_file = open(filename,'w')
2884 tmp_file = open(filename,'w')
2851 tmp_file.write(data)
2885 tmp_file.write(data)
2852 tmp_file.close()
2886 tmp_file.close()
2853 return filename
2887 return filename
2854
2888
2855 # TODO: This should be removed when Term is refactored.
2889 # TODO: This should be removed when Term is refactored.
2856 def write(self,data):
2890 def write(self,data):
2857 """Write a string to the default output"""
2891 """Write a string to the default output"""
2858 io.stdout.write(data)
2892 io.stdout.write(data)
2859
2893
2860 # TODO: This should be removed when Term is refactored.
2894 # TODO: This should be removed when Term is refactored.
2861 def write_err(self,data):
2895 def write_err(self,data):
2862 """Write a string to the default error output"""
2896 """Write a string to the default error output"""
2863 io.stderr.write(data)
2897 io.stderr.write(data)
2864
2898
2865 def ask_yes_no(self, prompt, default=None):
2899 def ask_yes_no(self, prompt, default=None):
2866 if self.quiet:
2900 if self.quiet:
2867 return True
2901 return True
2868 return ask_yes_no(prompt,default)
2902 return ask_yes_no(prompt,default)
2869
2903
2870 def show_usage(self):
2904 def show_usage(self):
2871 """Show a usage message"""
2905 """Show a usage message"""
2872 page.page(IPython.core.usage.interactive_usage)
2906 page.page(IPython.core.usage.interactive_usage)
2873
2907
2874 def extract_input_lines(self, range_str, raw=False):
2908 def extract_input_lines(self, range_str, raw=False):
2875 """Return as a string a set of input history slices.
2909 """Return as a string a set of input history slices.
2876
2910
2877 Parameters
2911 Parameters
2878 ----------
2912 ----------
2879 range_str : string
2913 range_str : string
2880 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
2914 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
2881 since this function is for use by magic functions which get their
2915 since this function is for use by magic functions which get their
2882 arguments as strings. The number before the / is the session
2916 arguments as strings. The number before the / is the session
2883 number: ~n goes n back from the current session.
2917 number: ~n goes n back from the current session.
2884
2918
2885 Optional Parameters:
2919 Optional Parameters:
2886 - raw(False): by default, the processed input is used. If this is
2920 - raw(False): by default, the processed input is used. If this is
2887 true, the raw input history is used instead.
2921 true, the raw input history is used instead.
2888
2922
2889 Note that slices can be called with two notations:
2923 Note that slices can be called with two notations:
2890
2924
2891 N:M -> standard python form, means including items N...(M-1).
2925 N:M -> standard python form, means including items N...(M-1).
2892
2926
2893 N-M -> include items N..M (closed endpoint)."""
2927 N-M -> include items N..M (closed endpoint)."""
2894 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
2928 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
2895 return "\n".join(x for _, _, x in lines)
2929 return "\n".join(x for _, _, x in lines)
2896
2930
2897 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True):
2931 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True):
2898 """Get a code string from history, file, url, or a string or macro.
2932 """Get a code string from history, file, url, or a string or macro.
2899
2933
2900 This is mainly used by magic functions.
2934 This is mainly used by magic functions.
2901
2935
2902 Parameters
2936 Parameters
2903 ----------
2937 ----------
2904
2938
2905 target : str
2939 target : str
2906
2940
2907 A string specifying code to retrieve. This will be tried respectively
2941 A string specifying code to retrieve. This will be tried respectively
2908 as: ranges of input history (see %history for syntax), url,
2942 as: ranges of input history (see %history for syntax), url,
2909 correspnding .py file, filename, or an expression evaluating to a
2943 correspnding .py file, filename, or an expression evaluating to a
2910 string or Macro in the user namespace.
2944 string or Macro in the user namespace.
2911
2945
2912 raw : bool
2946 raw : bool
2913 If true (default), retrieve raw history. Has no effect on the other
2947 If true (default), retrieve raw history. Has no effect on the other
2914 retrieval mechanisms.
2948 retrieval mechanisms.
2915
2949
2916 py_only : bool (default False)
2950 py_only : bool (default False)
2917 Only try to fetch python code, do not try alternative methods to decode file
2951 Only try to fetch python code, do not try alternative methods to decode file
2918 if unicode fails.
2952 if unicode fails.
2919
2953
2920 Returns
2954 Returns
2921 -------
2955 -------
2922 A string of code.
2956 A string of code.
2923
2957
2924 ValueError is raised if nothing is found, and TypeError if it evaluates
2958 ValueError is raised if nothing is found, and TypeError if it evaluates
2925 to an object of another type. In each case, .args[0] is a printable
2959 to an object of another type. In each case, .args[0] is a printable
2926 message.
2960 message.
2927 """
2961 """
2928 code = self.extract_input_lines(target, raw=raw) # Grab history
2962 code = self.extract_input_lines(target, raw=raw) # Grab history
2929 if code:
2963 if code:
2930 return code
2964 return code
2931 utarget = unquote_filename(target)
2965 utarget = unquote_filename(target)
2932 try:
2966 try:
2933 if utarget.startswith(('http://', 'https://')):
2967 if utarget.startswith(('http://', 'https://')):
2934 return openpy.read_py_url(utarget, skip_encoding_cookie=skip_encoding_cookie)
2968 return openpy.read_py_url(utarget, skip_encoding_cookie=skip_encoding_cookie)
2935 except UnicodeDecodeError:
2969 except UnicodeDecodeError:
2936 if not py_only :
2970 if not py_only :
2937 response = urllib.urlopen(target)
2971 response = urllib.urlopen(target)
2938 return response.read().decode('latin1')
2972 return response.read().decode('latin1')
2939 raise ValueError(("'%s' seem to be unreadable.") % utarget)
2973 raise ValueError(("'%s' seem to be unreadable.") % utarget)
2940
2974
2941 potential_target = [target]
2975 potential_target = [target]
2942 try :
2976 try :
2943 potential_target.insert(0,get_py_filename(target))
2977 potential_target.insert(0,get_py_filename(target))
2944 except IOError:
2978 except IOError:
2945 pass
2979 pass
2946
2980
2947 for tgt in potential_target :
2981 for tgt in potential_target :
2948 if os.path.isfile(tgt): # Read file
2982 if os.path.isfile(tgt): # Read file
2949 try :
2983 try :
2950 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
2984 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
2951 except UnicodeDecodeError :
2985 except UnicodeDecodeError :
2952 if not py_only :
2986 if not py_only :
2953 with io_open(tgt,'r', encoding='latin1') as f :
2987 with io_open(tgt,'r', encoding='latin1') as f :
2954 return f.read()
2988 return f.read()
2955 raise ValueError(("'%s' seem to be unreadable.") % target)
2989 raise ValueError(("'%s' seem to be unreadable.") % target)
2956
2990
2957 try: # User namespace
2991 try: # User namespace
2958 codeobj = eval(target, self.user_ns)
2992 codeobj = eval(target, self.user_ns)
2959 except Exception:
2993 except Exception:
2960 raise ValueError(("'%s' was not found in history, as a file, url, "
2994 raise ValueError(("'%s' was not found in history, as a file, url, "
2961 "nor in the user namespace.") % target)
2995 "nor in the user namespace.") % target)
2962 if isinstance(codeobj, basestring):
2996 if isinstance(codeobj, basestring):
2963 return codeobj
2997 return codeobj
2964 elif isinstance(codeobj, Macro):
2998 elif isinstance(codeobj, Macro):
2965 return codeobj.value
2999 return codeobj.value
2966
3000
2967 raise TypeError("%s is neither a string nor a macro." % target,
3001 raise TypeError("%s is neither a string nor a macro." % target,
2968 codeobj)
3002 codeobj)
2969
3003
2970 #-------------------------------------------------------------------------
3004 #-------------------------------------------------------------------------
2971 # Things related to IPython exiting
3005 # Things related to IPython exiting
2972 #-------------------------------------------------------------------------
3006 #-------------------------------------------------------------------------
2973 def atexit_operations(self):
3007 def atexit_operations(self):
2974 """This will be executed at the time of exit.
3008 """This will be executed at the time of exit.
2975
3009
2976 Cleanup operations and saving of persistent data that is done
3010 Cleanup operations and saving of persistent data that is done
2977 unconditionally by IPython should be performed here.
3011 unconditionally by IPython should be performed here.
2978
3012
2979 For things that may depend on startup flags or platform specifics (such
3013 For things that may depend on startup flags or platform specifics (such
2980 as having readline or not), register a separate atexit function in the
3014 as having readline or not), register a separate atexit function in the
2981 code that has the appropriate information, rather than trying to
3015 code that has the appropriate information, rather than trying to
2982 clutter
3016 clutter
2983 """
3017 """
2984 # Close the history session (this stores the end time and line count)
3018 # Close the history session (this stores the end time and line count)
2985 # this must be *before* the tempfile cleanup, in case of temporary
3019 # this must be *before* the tempfile cleanup, in case of temporary
2986 # history db
3020 # history db
2987 self.history_manager.end_session()
3021 self.history_manager.end_session()
2988
3022
2989 # Cleanup all tempfiles left around
3023 # Cleanup all tempfiles left around
2990 for tfile in self.tempfiles:
3024 for tfile in self.tempfiles:
2991 try:
3025 try:
2992 os.unlink(tfile)
3026 os.unlink(tfile)
2993 except OSError:
3027 except OSError:
2994 pass
3028 pass
2995
3029
2996 # Clear all user namespaces to release all references cleanly.
3030 # Clear all user namespaces to release all references cleanly.
2997 self.reset(new_session=False)
3031 self.reset(new_session=False)
2998
3032
2999 # Run user hooks
3033 # Run user hooks
3000 self.hooks.shutdown_hook()
3034 self.hooks.shutdown_hook()
3001
3035
3002 def cleanup(self):
3036 def cleanup(self):
3003 self.restore_sys_module_state()
3037 self.restore_sys_module_state()
3004
3038
3005
3039
3006 class InteractiveShellABC(object):
3040 class InteractiveShellABC(object):
3007 """An abstract base class for InteractiveShell."""
3041 """An abstract base class for InteractiveShell."""
3008 __metaclass__ = abc.ABCMeta
3042 __metaclass__ = abc.ABCMeta
3009
3043
3010 InteractiveShellABC.register(InteractiveShell)
3044 InteractiveShellABC.register(InteractiveShell)
@@ -1,1035 +1,1077 b''
1 """Implementation of execution-related magic functions.
1 """Implementation of execution-related magic functions.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Copyright (c) 2012 The IPython Development Team.
4 # Copyright (c) 2012 The IPython Development Team.
5 #
5 #
6 # Distributed under the terms of the Modified BSD License.
6 # Distributed under the terms of the Modified BSD License.
7 #
7 #
8 # The full license is in the file COPYING.txt, distributed with this software.
8 # The full license is in the file COPYING.txt, distributed with this software.
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Imports
12 # Imports
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 # Stdlib
15 # Stdlib
16 import __builtin__ as builtin_mod
16 import __builtin__ as builtin_mod
17 import ast
17 import bdb
18 import bdb
18 import os
19 import os
19 import sys
20 import sys
20 import time
21 import time
21 from StringIO import StringIO
22 from StringIO import StringIO
22
23
23 # cProfile was added in Python2.5
24 # cProfile was added in Python2.5
24 try:
25 try:
25 import cProfile as profile
26 import cProfile as profile
26 import pstats
27 import pstats
27 except ImportError:
28 except ImportError:
28 # profile isn't bundled by default in Debian for license reasons
29 # profile isn't bundled by default in Debian for license reasons
29 try:
30 try:
30 import profile, pstats
31 import profile, pstats
31 except ImportError:
32 except ImportError:
32 profile = pstats = None
33 profile = pstats = None
33
34
34 # Our own packages
35 # Our own packages
35 from IPython.core import debugger, oinspect
36 from IPython.core import debugger, oinspect
36 from IPython.core import magic_arguments
37 from IPython.core import magic_arguments
37 from IPython.core import page
38 from IPython.core import page
38 from IPython.core.error import UsageError
39 from IPython.core.error import UsageError
39 from IPython.core.macro import Macro
40 from IPython.core.macro import Macro
40 from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,
41 from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,
41 line_cell_magic, on_off, needs_local_scope)
42 line_cell_magic, on_off, needs_local_scope)
42 from IPython.testing.skipdoctest import skip_doctest
43 from IPython.testing.skipdoctest import skip_doctest
43 from IPython.utils import py3compat
44 from IPython.utils import py3compat
44 from IPython.utils.io import capture_output
45 from IPython.utils.io import capture_output
45 from IPython.utils.ipstruct import Struct
46 from IPython.utils.ipstruct import Struct
46 from IPython.utils.module_paths import find_mod
47 from IPython.utils.module_paths import find_mod
47 from IPython.utils.path import get_py_filename, unquote_filename, shellglob
48 from IPython.utils.path import get_py_filename, unquote_filename, shellglob
48 from IPython.utils.timing import clock, clock2
49 from IPython.utils.timing import clock, clock2
49 from IPython.utils.warn import warn, error
50 from IPython.utils.warn import warn, error
50
51
51
52
52 #-----------------------------------------------------------------------------
53 #-----------------------------------------------------------------------------
53 # Magic implementation classes
54 # Magic implementation classes
54 #-----------------------------------------------------------------------------
55 #-----------------------------------------------------------------------------
55
56
56 @magics_class
57 @magics_class
57 class ExecutionMagics(Magics):
58 class ExecutionMagics(Magics):
58 """Magics related to code execution, debugging, profiling, etc.
59 """Magics related to code execution, debugging, profiling, etc.
59
60
60 """
61 """
61
62
62 def __init__(self, shell):
63 def __init__(self, shell):
63 super(ExecutionMagics, self).__init__(shell)
64 super(ExecutionMagics, self).__init__(shell)
64 if profile is None:
65 if profile is None:
65 self.prun = self.profile_missing_notice
66 self.prun = self.profile_missing_notice
66 # Default execution function used to actually run user code.
67 # Default execution function used to actually run user code.
67 self.default_runner = None
68 self.default_runner = None
68
69
69 def profile_missing_notice(self, *args, **kwargs):
70 def profile_missing_notice(self, *args, **kwargs):
70 error("""\
71 error("""\
71 The profile module could not be found. It has been removed from the standard
72 The profile module could not be found. It has been removed from the standard
72 python packages because of its non-free license. To use profiling, install the
73 python packages because of its non-free license. To use profiling, install the
73 python-profiler package from non-free.""")
74 python-profiler package from non-free.""")
74
75
75 @skip_doctest
76 @skip_doctest
76 @line_cell_magic
77 @line_cell_magic
77 def prun(self, parameter_s='', cell=None, user_mode=True,
78 def prun(self, parameter_s='', cell=None, user_mode=True,
78 opts=None,arg_lst=None,prog_ns=None):
79 opts=None,arg_lst=None,prog_ns=None):
79
80
80 """Run a statement through the python code profiler.
81 """Run a statement through the python code profiler.
81
82
82 Usage, in line mode:
83 Usage, in line mode:
83 %prun [options] statement
84 %prun [options] statement
84
85
85 Usage, in cell mode:
86 Usage, in cell mode:
86 %%prun [options] [statement]
87 %%prun [options] [statement]
87 code...
88 code...
88 code...
89 code...
89
90
90 In cell mode, the additional code lines are appended to the (possibly
91 In cell mode, the additional code lines are appended to the (possibly
91 empty) statement in the first line. Cell mode allows you to easily
92 empty) statement in the first line. Cell mode allows you to easily
92 profile multiline blocks without having to put them in a separate
93 profile multiline blocks without having to put them in a separate
93 function.
94 function.
94
95
95 The given statement (which doesn't require quote marks) is run via the
96 The given statement (which doesn't require quote marks) is run via the
96 python profiler in a manner similar to the profile.run() function.
97 python profiler in a manner similar to the profile.run() function.
97 Namespaces are internally managed to work correctly; profile.run
98 Namespaces are internally managed to work correctly; profile.run
98 cannot be used in IPython because it makes certain assumptions about
99 cannot be used in IPython because it makes certain assumptions about
99 namespaces which do not hold under IPython.
100 namespaces which do not hold under IPython.
100
101
101 Options:
102 Options:
102
103
103 -l <limit>: you can place restrictions on what or how much of the
104 -l <limit>: you can place restrictions on what or how much of the
104 profile gets printed. The limit value can be:
105 profile gets printed. The limit value can be:
105
106
106 * A string: only information for function names containing this string
107 * A string: only information for function names containing this string
107 is printed.
108 is printed.
108
109
109 * An integer: only these many lines are printed.
110 * An integer: only these many lines are printed.
110
111
111 * A float (between 0 and 1): this fraction of the report is printed
112 * A float (between 0 and 1): this fraction of the report is printed
112 (for example, use a limit of 0.4 to see the topmost 40% only).
113 (for example, use a limit of 0.4 to see the topmost 40% only).
113
114
114 You can combine several limits with repeated use of the option. For
115 You can combine several limits with repeated use of the option. For
115 example, '-l __init__ -l 5' will print only the topmost 5 lines of
116 example, '-l __init__ -l 5' will print only the topmost 5 lines of
116 information about class constructors.
117 information about class constructors.
117
118
118 -r: return the pstats.Stats object generated by the profiling. This
119 -r: return the pstats.Stats object generated by the profiling. This
119 object has all the information about the profile in it, and you can
120 object has all the information about the profile in it, and you can
120 later use it for further analysis or in other functions.
121 later use it for further analysis or in other functions.
121
122
122 -s <key>: sort profile by given key. You can provide more than one key
123 -s <key>: sort profile by given key. You can provide more than one key
123 by using the option several times: '-s key1 -s key2 -s key3...'. The
124 by using the option several times: '-s key1 -s key2 -s key3...'. The
124 default sorting key is 'time'.
125 default sorting key is 'time'.
125
126
126 The following is copied verbatim from the profile documentation
127 The following is copied verbatim from the profile documentation
127 referenced below:
128 referenced below:
128
129
129 When more than one key is provided, additional keys are used as
130 When more than one key is provided, additional keys are used as
130 secondary criteria when the there is equality in all keys selected
131 secondary criteria when the there is equality in all keys selected
131 before them.
132 before them.
132
133
133 Abbreviations can be used for any key names, as long as the
134 Abbreviations can be used for any key names, as long as the
134 abbreviation is unambiguous. The following are the keys currently
135 abbreviation is unambiguous. The following are the keys currently
135 defined:
136 defined:
136
137
137 Valid Arg Meaning
138 Valid Arg Meaning
138 "calls" call count
139 "calls" call count
139 "cumulative" cumulative time
140 "cumulative" cumulative time
140 "file" file name
141 "file" file name
141 "module" file name
142 "module" file name
142 "pcalls" primitive call count
143 "pcalls" primitive call count
143 "line" line number
144 "line" line number
144 "name" function name
145 "name" function name
145 "nfl" name/file/line
146 "nfl" name/file/line
146 "stdname" standard name
147 "stdname" standard name
147 "time" internal time
148 "time" internal time
148
149
149 Note that all sorts on statistics are in descending order (placing
150 Note that all sorts on statistics are in descending order (placing
150 most time consuming items first), where as name, file, and line number
151 most time consuming items first), where as name, file, and line number
151 searches are in ascending order (i.e., alphabetical). The subtle
152 searches are in ascending order (i.e., alphabetical). The subtle
152 distinction between "nfl" and "stdname" is that the standard name is a
153 distinction between "nfl" and "stdname" is that the standard name is a
153 sort of the name as printed, which means that the embedded line
154 sort of the name as printed, which means that the embedded line
154 numbers get compared in an odd way. For example, lines 3, 20, and 40
155 numbers get compared in an odd way. For example, lines 3, 20, and 40
155 would (if the file names were the same) appear in the string order
156 would (if the file names were the same) appear in the string order
156 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
157 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
157 line numbers. In fact, sort_stats("nfl") is the same as
158 line numbers. In fact, sort_stats("nfl") is the same as
158 sort_stats("name", "file", "line").
159 sort_stats("name", "file", "line").
159
160
160 -T <filename>: save profile results as shown on screen to a text
161 -T <filename>: save profile results as shown on screen to a text
161 file. The profile is still shown on screen.
162 file. The profile is still shown on screen.
162
163
163 -D <filename>: save (via dump_stats) profile statistics to given
164 -D <filename>: save (via dump_stats) profile statistics to given
164 filename. This data is in a format understood by the pstats module, and
165 filename. This data is in a format understood by the pstats module, and
165 is generated by a call to the dump_stats() method of profile
166 is generated by a call to the dump_stats() method of profile
166 objects. The profile is still shown on screen.
167 objects. The profile is still shown on screen.
167
168
168 -q: suppress output to the pager. Best used with -T and/or -D above.
169 -q: suppress output to the pager. Best used with -T and/or -D above.
169
170
170 If you want to run complete programs under the profiler's control, use
171 If you want to run complete programs under the profiler's control, use
171 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
172 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
172 contains profiler specific options as described here.
173 contains profiler specific options as described here.
173
174
174 You can read the complete documentation for the profile module with::
175 You can read the complete documentation for the profile module with::
175
176
176 In [1]: import profile; profile.help()
177 In [1]: import profile; profile.help()
177 """
178 """
178
179
179 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
180 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
180
181
181 if user_mode: # regular user call
182 if user_mode: # regular user call
182 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:q',
183 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:q',
183 list_all=True, posix=False)
184 list_all=True, posix=False)
184 namespace = self.shell.user_ns
185 namespace = self.shell.user_ns
185 if cell is not None:
186 if cell is not None:
186 arg_str += '\n' + cell
187 arg_str += '\n' + cell
187 else: # called to run a program by %run -p
188 else: # called to run a program by %run -p
188 try:
189 try:
189 filename = get_py_filename(arg_lst[0])
190 filename = get_py_filename(arg_lst[0])
190 except IOError as e:
191 except IOError as e:
191 try:
192 try:
192 msg = str(e)
193 msg = str(e)
193 except UnicodeError:
194 except UnicodeError:
194 msg = e.message
195 msg = e.message
195 error(msg)
196 error(msg)
196 return
197 return
197
198
198 arg_str = 'execfile(filename,prog_ns)'
199 arg_str = 'execfile(filename,prog_ns)'
199 namespace = {
200 namespace = {
200 'execfile': self.shell.safe_execfile,
201 'execfile': self.shell.safe_execfile,
201 'prog_ns': prog_ns,
202 'prog_ns': prog_ns,
202 'filename': filename
203 'filename': filename
203 }
204 }
204
205
205 opts.merge(opts_def)
206 opts.merge(opts_def)
206
207
207 prof = profile.Profile()
208 prof = profile.Profile()
208 try:
209 try:
209 prof = prof.runctx(arg_str,namespace,namespace)
210 prof = prof.runctx(arg_str,namespace,namespace)
210 sys_exit = ''
211 sys_exit = ''
211 except SystemExit:
212 except SystemExit:
212 sys_exit = """*** SystemExit exception caught in code being profiled."""
213 sys_exit = """*** SystemExit exception caught in code being profiled."""
213
214
214 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
215 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
215
216
216 lims = opts.l
217 lims = opts.l
217 if lims:
218 if lims:
218 lims = [] # rebuild lims with ints/floats/strings
219 lims = [] # rebuild lims with ints/floats/strings
219 for lim in opts.l:
220 for lim in opts.l:
220 try:
221 try:
221 lims.append(int(lim))
222 lims.append(int(lim))
222 except ValueError:
223 except ValueError:
223 try:
224 try:
224 lims.append(float(lim))
225 lims.append(float(lim))
225 except ValueError:
226 except ValueError:
226 lims.append(lim)
227 lims.append(lim)
227
228
228 # Trap output.
229 # Trap output.
229 stdout_trap = StringIO()
230 stdout_trap = StringIO()
230 stats_stream = stats.stream
231 stats_stream = stats.stream
231 try:
232 try:
232 stats.stream = stdout_trap
233 stats.stream = stdout_trap
233 stats.print_stats(*lims)
234 stats.print_stats(*lims)
234 finally:
235 finally:
235 stats.stream = stats_stream
236 stats.stream = stats_stream
236
237
237 output = stdout_trap.getvalue()
238 output = stdout_trap.getvalue()
238 output = output.rstrip()
239 output = output.rstrip()
239
240
240 if 'q' not in opts:
241 if 'q' not in opts:
241 page.page(output)
242 page.page(output)
242 print sys_exit,
243 print sys_exit,
243
244
244 dump_file = opts.D[0]
245 dump_file = opts.D[0]
245 text_file = opts.T[0]
246 text_file = opts.T[0]
246 if dump_file:
247 if dump_file:
247 dump_file = unquote_filename(dump_file)
248 dump_file = unquote_filename(dump_file)
248 prof.dump_stats(dump_file)
249 prof.dump_stats(dump_file)
249 print '\n*** Profile stats marshalled to file',\
250 print '\n*** Profile stats marshalled to file',\
250 repr(dump_file)+'.',sys_exit
251 repr(dump_file)+'.',sys_exit
251 if text_file:
252 if text_file:
252 text_file = unquote_filename(text_file)
253 text_file = unquote_filename(text_file)
253 pfile = open(text_file,'w')
254 pfile = open(text_file,'w')
254 pfile.write(output)
255 pfile.write(output)
255 pfile.close()
256 pfile.close()
256 print '\n*** Profile printout saved to text file',\
257 print '\n*** Profile printout saved to text file',\
257 repr(text_file)+'.',sys_exit
258 repr(text_file)+'.',sys_exit
258
259
259 if 'r' in opts:
260 if 'r' in opts:
260 return stats
261 return stats
261 else:
262 else:
262 return None
263 return None
263
264
264 @line_magic
265 @line_magic
265 def pdb(self, parameter_s=''):
266 def pdb(self, parameter_s=''):
266 """Control the automatic calling of the pdb interactive debugger.
267 """Control the automatic calling of the pdb interactive debugger.
267
268
268 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
269 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
269 argument it works as a toggle.
270 argument it works as a toggle.
270
271
271 When an exception is triggered, IPython can optionally call the
272 When an exception is triggered, IPython can optionally call the
272 interactive pdb debugger after the traceback printout. %pdb toggles
273 interactive pdb debugger after the traceback printout. %pdb toggles
273 this feature on and off.
274 this feature on and off.
274
275
275 The initial state of this feature is set in your configuration
276 The initial state of this feature is set in your configuration
276 file (the option is ``InteractiveShell.pdb``).
277 file (the option is ``InteractiveShell.pdb``).
277
278
278 If you want to just activate the debugger AFTER an exception has fired,
279 If you want to just activate the debugger AFTER an exception has fired,
279 without having to type '%pdb on' and rerunning your code, you can use
280 without having to type '%pdb on' and rerunning your code, you can use
280 the %debug magic."""
281 the %debug magic."""
281
282
282 par = parameter_s.strip().lower()
283 par = parameter_s.strip().lower()
283
284
284 if par:
285 if par:
285 try:
286 try:
286 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
287 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
287 except KeyError:
288 except KeyError:
288 print ('Incorrect argument. Use on/1, off/0, '
289 print ('Incorrect argument. Use on/1, off/0, '
289 'or nothing for a toggle.')
290 'or nothing for a toggle.')
290 return
291 return
291 else:
292 else:
292 # toggle
293 # toggle
293 new_pdb = not self.shell.call_pdb
294 new_pdb = not self.shell.call_pdb
294
295
295 # set on the shell
296 # set on the shell
296 self.shell.call_pdb = new_pdb
297 self.shell.call_pdb = new_pdb
297 print 'Automatic pdb calling has been turned',on_off(new_pdb)
298 print 'Automatic pdb calling has been turned',on_off(new_pdb)
298
299
299 @line_magic
300 @line_magic
300 def debug(self, parameter_s=''):
301 def debug(self, parameter_s=''):
301 """Activate the interactive debugger in post-mortem mode.
302 """Activate the interactive debugger in post-mortem mode.
302
303
303 If an exception has just occurred, this lets you inspect its stack
304 If an exception has just occurred, this lets you inspect its stack
304 frames interactively. Note that this will always work only on the last
305 frames interactively. Note that this will always work only on the last
305 traceback that occurred, so you must call this quickly after an
306 traceback that occurred, so you must call this quickly after an
306 exception that you wish to inspect has fired, because if another one
307 exception that you wish to inspect has fired, because if another one
307 occurs, it clobbers the previous one.
308 occurs, it clobbers the previous one.
308
309
309 If you want IPython to automatically do this on every exception, see
310 If you want IPython to automatically do this on every exception, see
310 the %pdb magic for more details.
311 the %pdb magic for more details.
311 """
312 """
312 self.shell.debugger(force=True)
313 self.shell.debugger(force=True)
313
314
314 @line_magic
315 @line_magic
315 def tb(self, s):
316 def tb(self, s):
316 """Print the last traceback with the currently active exception mode.
317 """Print the last traceback with the currently active exception mode.
317
318
318 See %xmode for changing exception reporting modes."""
319 See %xmode for changing exception reporting modes."""
319 self.shell.showtraceback()
320 self.shell.showtraceback()
320
321
321 @skip_doctest
322 @skip_doctest
322 @line_magic
323 @line_magic
323 def run(self, parameter_s='', runner=None,
324 def run(self, parameter_s='', runner=None,
324 file_finder=get_py_filename):
325 file_finder=get_py_filename):
325 """Run the named file inside IPython as a program.
326 """Run the named file inside IPython as a program.
326
327
327 Usage:\\
328 Usage:\\
328 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options] -G] file [args]
329 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options] -G] file [args]
329
330
330 Parameters after the filename are passed as command-line arguments to
331 Parameters after the filename are passed as command-line arguments to
331 the program (put in sys.argv). Then, control returns to IPython's
332 the program (put in sys.argv). Then, control returns to IPython's
332 prompt.
333 prompt.
333
334
334 This is similar to running at a system prompt:\\
335 This is similar to running at a system prompt:\\
335 $ python file args\\
336 $ python file args\\
336 but with the advantage of giving you IPython's tracebacks, and of
337 but with the advantage of giving you IPython's tracebacks, and of
337 loading all variables into your interactive namespace for further use
338 loading all variables into your interactive namespace for further use
338 (unless -p is used, see below).
339 (unless -p is used, see below).
339
340
340 The file is executed in a namespace initially consisting only of
341 The file is executed in a namespace initially consisting only of
341 __name__=='__main__' and sys.argv constructed as indicated. It thus
342 __name__=='__main__' and sys.argv constructed as indicated. It thus
342 sees its environment as if it were being run as a stand-alone program
343 sees its environment as if it were being run as a stand-alone program
343 (except for sharing global objects such as previously imported
344 (except for sharing global objects such as previously imported
344 modules). But after execution, the IPython interactive namespace gets
345 modules). But after execution, the IPython interactive namespace gets
345 updated with all variables defined in the program (except for __name__
346 updated with all variables defined in the program (except for __name__
346 and sys.argv). This allows for very convenient loading of code for
347 and sys.argv). This allows for very convenient loading of code for
347 interactive work, while giving each program a 'clean sheet' to run in.
348 interactive work, while giving each program a 'clean sheet' to run in.
348
349
349 Arguments are expanded using shell-like glob match. Patterns
350 Arguments are expanded using shell-like glob match. Patterns
350 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
351 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
351 tilde '~' will be expanded into user's home directory. Unlike
352 tilde '~' will be expanded into user's home directory. Unlike
352 real shells, quotation does not suppress expansions. Use
353 real shells, quotation does not suppress expansions. Use
353 *two* back slashes (e.g., '\\\\*') to suppress expansions.
354 *two* back slashes (e.g., '\\\\*') to suppress expansions.
354 To completely disable these expansions, you can use -G flag.
355 To completely disable these expansions, you can use -G flag.
355
356
356 Options:
357 Options:
357
358
358 -n: __name__ is NOT set to '__main__', but to the running file's name
359 -n: __name__ is NOT set to '__main__', but to the running file's name
359 without extension (as python does under import). This allows running
360 without extension (as python does under import). This allows running
360 scripts and reloading the definitions in them without calling code
361 scripts and reloading the definitions in them without calling code
361 protected by an ' if __name__ == "__main__" ' clause.
362 protected by an ' if __name__ == "__main__" ' clause.
362
363
363 -i: run the file in IPython's namespace instead of an empty one. This
364 -i: run the file in IPython's namespace instead of an empty one. This
364 is useful if you are experimenting with code written in a text editor
365 is useful if you are experimenting with code written in a text editor
365 which depends on variables defined interactively.
366 which depends on variables defined interactively.
366
367
367 -e: ignore sys.exit() calls or SystemExit exceptions in the script
368 -e: ignore sys.exit() calls or SystemExit exceptions in the script
368 being run. This is particularly useful if IPython is being used to
369 being run. This is particularly useful if IPython is being used to
369 run unittests, which always exit with a sys.exit() call. In such
370 run unittests, which always exit with a sys.exit() call. In such
370 cases you are interested in the output of the test results, not in
371 cases you are interested in the output of the test results, not in
371 seeing a traceback of the unittest module.
372 seeing a traceback of the unittest module.
372
373
373 -t: print timing information at the end of the run. IPython will give
374 -t: print timing information at the end of the run. IPython will give
374 you an estimated CPU time consumption for your script, which under
375 you an estimated CPU time consumption for your script, which under
375 Unix uses the resource module to avoid the wraparound problems of
376 Unix uses the resource module to avoid the wraparound problems of
376 time.clock(). Under Unix, an estimate of time spent on system tasks
377 time.clock(). Under Unix, an estimate of time spent on system tasks
377 is also given (for Windows platforms this is reported as 0.0).
378 is also given (for Windows platforms this is reported as 0.0).
378
379
379 If -t is given, an additional -N<N> option can be given, where <N>
380 If -t is given, an additional -N<N> option can be given, where <N>
380 must be an integer indicating how many times you want the script to
381 must be an integer indicating how many times you want the script to
381 run. The final timing report will include total and per run results.
382 run. The final timing report will include total and per run results.
382
383
383 For example (testing the script uniq_stable.py)::
384 For example (testing the script uniq_stable.py)::
384
385
385 In [1]: run -t uniq_stable
386 In [1]: run -t uniq_stable
386
387
387 IPython CPU timings (estimated):\\
388 IPython CPU timings (estimated):\\
388 User : 0.19597 s.\\
389 User : 0.19597 s.\\
389 System: 0.0 s.\\
390 System: 0.0 s.\\
390
391
391 In [2]: run -t -N5 uniq_stable
392 In [2]: run -t -N5 uniq_stable
392
393
393 IPython CPU timings (estimated):\\
394 IPython CPU timings (estimated):\\
394 Total runs performed: 5\\
395 Total runs performed: 5\\
395 Times : Total Per run\\
396 Times : Total Per run\\
396 User : 0.910862 s, 0.1821724 s.\\
397 User : 0.910862 s, 0.1821724 s.\\
397 System: 0.0 s, 0.0 s.
398 System: 0.0 s, 0.0 s.
398
399
399 -d: run your program under the control of pdb, the Python debugger.
400 -d: run your program under the control of pdb, the Python debugger.
400 This allows you to execute your program step by step, watch variables,
401 This allows you to execute your program step by step, watch variables,
401 etc. Internally, what IPython does is similar to calling:
402 etc. Internally, what IPython does is similar to calling:
402
403
403 pdb.run('execfile("YOURFILENAME")')
404 pdb.run('execfile("YOURFILENAME")')
404
405
405 with a breakpoint set on line 1 of your file. You can change the line
406 with a breakpoint set on line 1 of your file. You can change the line
406 number for this automatic breakpoint to be <N> by using the -bN option
407 number for this automatic breakpoint to be <N> by using the -bN option
407 (where N must be an integer). For example::
408 (where N must be an integer). For example::
408
409
409 %run -d -b40 myscript
410 %run -d -b40 myscript
410
411
411 will set the first breakpoint at line 40 in myscript.py. Note that
412 will set the first breakpoint at line 40 in myscript.py. Note that
412 the first breakpoint must be set on a line which actually does
413 the first breakpoint must be set on a line which actually does
413 something (not a comment or docstring) for it to stop execution.
414 something (not a comment or docstring) for it to stop execution.
414
415
415 When the pdb debugger starts, you will see a (Pdb) prompt. You must
416 When the pdb debugger starts, you will see a (Pdb) prompt. You must
416 first enter 'c' (without quotes) to start execution up to the first
417 first enter 'c' (without quotes) to start execution up to the first
417 breakpoint.
418 breakpoint.
418
419
419 Entering 'help' gives information about the use of the debugger. You
420 Entering 'help' gives information about the use of the debugger. You
420 can easily see pdb's full documentation with "import pdb;pdb.help()"
421 can easily see pdb's full documentation with "import pdb;pdb.help()"
421 at a prompt.
422 at a prompt.
422
423
423 -p: run program under the control of the Python profiler module (which
424 -p: run program under the control of the Python profiler module (which
424 prints a detailed report of execution times, function calls, etc).
425 prints a detailed report of execution times, function calls, etc).
425
426
426 You can pass other options after -p which affect the behavior of the
427 You can pass other options after -p which affect the behavior of the
427 profiler itself. See the docs for %prun for details.
428 profiler itself. See the docs for %prun for details.
428
429
429 In this mode, the program's variables do NOT propagate back to the
430 In this mode, the program's variables do NOT propagate back to the
430 IPython interactive namespace (because they remain in the namespace
431 IPython interactive namespace (because they remain in the namespace
431 where the profiler executes them).
432 where the profiler executes them).
432
433
433 Internally this triggers a call to %prun, see its documentation for
434 Internally this triggers a call to %prun, see its documentation for
434 details on the options available specifically for profiling.
435 details on the options available specifically for profiling.
435
436
436 There is one special usage for which the text above doesn't apply:
437 There is one special usage for which the text above doesn't apply:
437 if the filename ends with .ipy, the file is run as ipython script,
438 if the filename ends with .ipy, the file is run as ipython script,
438 just as if the commands were written on IPython prompt.
439 just as if the commands were written on IPython prompt.
439
440
440 -m: specify module name to load instead of script path. Similar to
441 -m: specify module name to load instead of script path. Similar to
441 the -m option for the python interpreter. Use this option last if you
442 the -m option for the python interpreter. Use this option last if you
442 want to combine with other %run options. Unlike the python interpreter
443 want to combine with other %run options. Unlike the python interpreter
443 only source modules are allowed no .pyc or .pyo files.
444 only source modules are allowed no .pyc or .pyo files.
444 For example::
445 For example::
445
446
446 %run -m example
447 %run -m example
447
448
448 will run the example module.
449 will run the example module.
449
450
450 -G: disable shell-like glob expansion of arguments.
451 -G: disable shell-like glob expansion of arguments.
451
452
452 """
453 """
453
454
454 # get arguments and set sys.argv for program to be run.
455 # get arguments and set sys.argv for program to be run.
455 opts, arg_lst = self.parse_options(parameter_s,
456 opts, arg_lst = self.parse_options(parameter_s,
456 'nidtN:b:pD:l:rs:T:em:G',
457 'nidtN:b:pD:l:rs:T:em:G',
457 mode='list', list_all=1)
458 mode='list', list_all=1)
458 if "m" in opts:
459 if "m" in opts:
459 modulename = opts["m"][0]
460 modulename = opts["m"][0]
460 modpath = find_mod(modulename)
461 modpath = find_mod(modulename)
461 if modpath is None:
462 if modpath is None:
462 warn('%r is not a valid modulename on sys.path'%modulename)
463 warn('%r is not a valid modulename on sys.path'%modulename)
463 return
464 return
464 arg_lst = [modpath] + arg_lst
465 arg_lst = [modpath] + arg_lst
465 try:
466 try:
466 filename = file_finder(arg_lst[0])
467 filename = file_finder(arg_lst[0])
467 except IndexError:
468 except IndexError:
468 warn('you must provide at least a filename.')
469 warn('you must provide at least a filename.')
469 print '\n%run:\n', oinspect.getdoc(self.run)
470 print '\n%run:\n', oinspect.getdoc(self.run)
470 return
471 return
471 except IOError as e:
472 except IOError as e:
472 try:
473 try:
473 msg = str(e)
474 msg = str(e)
474 except UnicodeError:
475 except UnicodeError:
475 msg = e.message
476 msg = e.message
476 error(msg)
477 error(msg)
477 return
478 return
478
479
479 if filename.lower().endswith('.ipy'):
480 if filename.lower().endswith('.ipy'):
480 self.shell.safe_execfile_ipy(filename)
481 self.shell.safe_execfile_ipy(filename)
481 return
482 return
482
483
483 # Control the response to exit() calls made by the script being run
484 # Control the response to exit() calls made by the script being run
484 exit_ignore = 'e' in opts
485 exit_ignore = 'e' in opts
485
486
486 # Make sure that the running script gets a proper sys.argv as if it
487 # Make sure that the running script gets a proper sys.argv as if it
487 # were run from a system shell.
488 # were run from a system shell.
488 save_argv = sys.argv # save it for later restoring
489 save_argv = sys.argv # save it for later restoring
489
490
490 if 'G' in opts:
491 if 'G' in opts:
491 args = arg_lst[1:]
492 args = arg_lst[1:]
492 else:
493 else:
493 # tilde and glob expansion
494 # tilde and glob expansion
494 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
495 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
495
496
496 sys.argv = [filename] + args # put in the proper filename
497 sys.argv = [filename] + args # put in the proper filename
497 # protect sys.argv from potential unicode strings on Python 2:
498 # protect sys.argv from potential unicode strings on Python 2:
498 if not py3compat.PY3:
499 if not py3compat.PY3:
499 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
500 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
500
501
501 if 'i' in opts:
502 if 'i' in opts:
502 # Run in user's interactive namespace
503 # Run in user's interactive namespace
503 prog_ns = self.shell.user_ns
504 prog_ns = self.shell.user_ns
504 __name__save = self.shell.user_ns['__name__']
505 __name__save = self.shell.user_ns['__name__']
505 prog_ns['__name__'] = '__main__'
506 prog_ns['__name__'] = '__main__'
506 main_mod = self.shell.new_main_mod(prog_ns)
507 main_mod = self.shell.new_main_mod(prog_ns)
507 else:
508 else:
508 # Run in a fresh, empty namespace
509 # Run in a fresh, empty namespace
509 if 'n' in opts:
510 if 'n' in opts:
510 name = os.path.splitext(os.path.basename(filename))[0]
511 name = os.path.splitext(os.path.basename(filename))[0]
511 else:
512 else:
512 name = '__main__'
513 name = '__main__'
513
514
514 main_mod = self.shell.new_main_mod()
515 main_mod = self.shell.new_main_mod()
515 prog_ns = main_mod.__dict__
516 prog_ns = main_mod.__dict__
516 prog_ns['__name__'] = name
517 prog_ns['__name__'] = name
517
518
518 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
519 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
519 # set the __file__ global in the script's namespace
520 # set the __file__ global in the script's namespace
520 prog_ns['__file__'] = filename
521 prog_ns['__file__'] = filename
521
522
522 # pickle fix. See interactiveshell for an explanation. But we need to
523 # pickle fix. See interactiveshell for an explanation. But we need to
523 # make sure that, if we overwrite __main__, we replace it at the end
524 # make sure that, if we overwrite __main__, we replace it at the end
524 main_mod_name = prog_ns['__name__']
525 main_mod_name = prog_ns['__name__']
525
526
526 if main_mod_name == '__main__':
527 if main_mod_name == '__main__':
527 restore_main = sys.modules['__main__']
528 restore_main = sys.modules['__main__']
528 else:
529 else:
529 restore_main = False
530 restore_main = False
530
531
531 # This needs to be undone at the end to prevent holding references to
532 # This needs to be undone at the end to prevent holding references to
532 # every single object ever created.
533 # every single object ever created.
533 sys.modules[main_mod_name] = main_mod
534 sys.modules[main_mod_name] = main_mod
534
535
535 try:
536 try:
536 stats = None
537 stats = None
537 with self.shell.readline_no_record:
538 with self.shell.readline_no_record:
538 if 'p' in opts:
539 if 'p' in opts:
539 stats = self.prun('', None, False, opts, arg_lst, prog_ns)
540 stats = self.prun('', None, False, opts, arg_lst, prog_ns)
540 else:
541 else:
541 if 'd' in opts:
542 if 'd' in opts:
542 deb = debugger.Pdb(self.shell.colors)
543 deb = debugger.Pdb(self.shell.colors)
543 # reset Breakpoint state, which is moronically kept
544 # reset Breakpoint state, which is moronically kept
544 # in a class
545 # in a class
545 bdb.Breakpoint.next = 1
546 bdb.Breakpoint.next = 1
546 bdb.Breakpoint.bplist = {}
547 bdb.Breakpoint.bplist = {}
547 bdb.Breakpoint.bpbynumber = [None]
548 bdb.Breakpoint.bpbynumber = [None]
548 # Set an initial breakpoint to stop execution
549 # Set an initial breakpoint to stop execution
549 maxtries = 10
550 maxtries = 10
550 bp = int(opts.get('b', [1])[0])
551 bp = int(opts.get('b', [1])[0])
551 checkline = deb.checkline(filename, bp)
552 checkline = deb.checkline(filename, bp)
552 if not checkline:
553 if not checkline:
553 for bp in range(bp + 1, bp + maxtries + 1):
554 for bp in range(bp + 1, bp + maxtries + 1):
554 if deb.checkline(filename, bp):
555 if deb.checkline(filename, bp):
555 break
556 break
556 else:
557 else:
557 msg = ("\nI failed to find a valid line to set "
558 msg = ("\nI failed to find a valid line to set "
558 "a breakpoint\n"
559 "a breakpoint\n"
559 "after trying up to line: %s.\n"
560 "after trying up to line: %s.\n"
560 "Please set a valid breakpoint manually "
561 "Please set a valid breakpoint manually "
561 "with the -b option." % bp)
562 "with the -b option." % bp)
562 error(msg)
563 error(msg)
563 return
564 return
564 # if we find a good linenumber, set the breakpoint
565 # if we find a good linenumber, set the breakpoint
565 deb.do_break('%s:%s' % (filename, bp))
566 deb.do_break('%s:%s' % (filename, bp))
566
567
567 # Mimic Pdb._runscript(...)
568 # Mimic Pdb._runscript(...)
568 deb._wait_for_mainpyfile = True
569 deb._wait_for_mainpyfile = True
569 deb.mainpyfile = deb.canonic(filename)
570 deb.mainpyfile = deb.canonic(filename)
570
571
571 # Start file run
572 # Start file run
572 print "NOTE: Enter 'c' at the",
573 print "NOTE: Enter 'c' at the",
573 print "%s prompt to start your script." % deb.prompt
574 print "%s prompt to start your script." % deb.prompt
574 ns = {'execfile': py3compat.execfile, 'prog_ns': prog_ns}
575 ns = {'execfile': py3compat.execfile, 'prog_ns': prog_ns}
575 try:
576 try:
576 #save filename so it can be used by methods on the deb object
577 #save filename so it can be used by methods on the deb object
577 deb._exec_filename = filename
578 deb._exec_filename = filename
578 deb.run('execfile("%s", prog_ns)' % filename, ns)
579 deb.run('execfile("%s", prog_ns)' % filename, ns)
579
580
580 except:
581 except:
581 etype, value, tb = sys.exc_info()
582 etype, value, tb = sys.exc_info()
582 # Skip three frames in the traceback: the %run one,
583 # Skip three frames in the traceback: the %run one,
583 # one inside bdb.py, and the command-line typed by the
584 # one inside bdb.py, and the command-line typed by the
584 # user (run by exec in pdb itself).
585 # user (run by exec in pdb itself).
585 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
586 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
586 else:
587 else:
587 if runner is None:
588 if runner is None:
588 runner = self.default_runner
589 runner = self.default_runner
589 if runner is None:
590 if runner is None:
590 runner = self.shell.safe_execfile
591 runner = self.shell.safe_execfile
591 if 't' in opts:
592 if 't' in opts:
592 # timed execution
593 # timed execution
593 try:
594 try:
594 nruns = int(opts['N'][0])
595 nruns = int(opts['N'][0])
595 if nruns < 1:
596 if nruns < 1:
596 error('Number of runs must be >=1')
597 error('Number of runs must be >=1')
597 return
598 return
598 except (KeyError):
599 except (KeyError):
599 nruns = 1
600 nruns = 1
600 twall0 = time.time()
601 twall0 = time.time()
601 if nruns == 1:
602 if nruns == 1:
602 t0 = clock2()
603 t0 = clock2()
603 runner(filename, prog_ns, prog_ns,
604 runner(filename, prog_ns, prog_ns,
604 exit_ignore=exit_ignore)
605 exit_ignore=exit_ignore)
605 t1 = clock2()
606 t1 = clock2()
606 t_usr = t1[0] - t0[0]
607 t_usr = t1[0] - t0[0]
607 t_sys = t1[1] - t0[1]
608 t_sys = t1[1] - t0[1]
608 print "\nIPython CPU timings (estimated):"
609 print "\nIPython CPU timings (estimated):"
609 print " User : %10.2f s." % t_usr
610 print " User : %10.2f s." % t_usr
610 print " System : %10.2f s." % t_sys
611 print " System : %10.2f s." % t_sys
611 else:
612 else:
612 runs = range(nruns)
613 runs = range(nruns)
613 t0 = clock2()
614 t0 = clock2()
614 for nr in runs:
615 for nr in runs:
615 runner(filename, prog_ns, prog_ns,
616 runner(filename, prog_ns, prog_ns,
616 exit_ignore=exit_ignore)
617 exit_ignore=exit_ignore)
617 t1 = clock2()
618 t1 = clock2()
618 t_usr = t1[0] - t0[0]
619 t_usr = t1[0] - t0[0]
619 t_sys = t1[1] - t0[1]
620 t_sys = t1[1] - t0[1]
620 print "\nIPython CPU timings (estimated):"
621 print "\nIPython CPU timings (estimated):"
621 print "Total runs performed:", nruns
622 print "Total runs performed:", nruns
622 print " Times : %10.2f %10.2f" % ('Total', 'Per run')
623 print " Times : %10.2f %10.2f" % ('Total', 'Per run')
623 print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns)
624 print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns)
624 print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns)
625 print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns)
625 twall1 = time.time()
626 twall1 = time.time()
626 print "Wall time: %10.2f s." % (twall1 - twall0)
627 print "Wall time: %10.2f s." % (twall1 - twall0)
627
628
628 else:
629 else:
629 # regular execution
630 # regular execution
630 runner(filename, prog_ns, prog_ns, exit_ignore=exit_ignore)
631 runner(filename, prog_ns, prog_ns, exit_ignore=exit_ignore)
631
632
632 if 'i' in opts:
633 if 'i' in opts:
633 self.shell.user_ns['__name__'] = __name__save
634 self.shell.user_ns['__name__'] = __name__save
634 else:
635 else:
635 # The shell MUST hold a reference to prog_ns so after %run
636 # The shell MUST hold a reference to prog_ns so after %run
636 # exits, the python deletion mechanism doesn't zero it out
637 # exits, the python deletion mechanism doesn't zero it out
637 # (leaving dangling references).
638 # (leaving dangling references).
638 self.shell.cache_main_mod(prog_ns, filename)
639 self.shell.cache_main_mod(prog_ns, filename)
639 # update IPython interactive namespace
640 # update IPython interactive namespace
640
641
641 # Some forms of read errors on the file may mean the
642 # Some forms of read errors on the file may mean the
642 # __name__ key was never set; using pop we don't have to
643 # __name__ key was never set; using pop we don't have to
643 # worry about a possible KeyError.
644 # worry about a possible KeyError.
644 prog_ns.pop('__name__', None)
645 prog_ns.pop('__name__', None)
645
646
646 self.shell.user_ns.update(prog_ns)
647 self.shell.user_ns.update(prog_ns)
647 finally:
648 finally:
648 # It's a bit of a mystery why, but __builtins__ can change from
649 # It's a bit of a mystery why, but __builtins__ can change from
649 # being a module to becoming a dict missing some key data after
650 # being a module to becoming a dict missing some key data after
650 # %run. As best I can see, this is NOT something IPython is doing
651 # %run. As best I can see, this is NOT something IPython is doing
651 # at all, and similar problems have been reported before:
652 # at all, and similar problems have been reported before:
652 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
653 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
653 # Since this seems to be done by the interpreter itself, the best
654 # Since this seems to be done by the interpreter itself, the best
654 # we can do is to at least restore __builtins__ for the user on
655 # we can do is to at least restore __builtins__ for the user on
655 # exit.
656 # exit.
656 self.shell.user_ns['__builtins__'] = builtin_mod
657 self.shell.user_ns['__builtins__'] = builtin_mod
657
658
658 # Ensure key global structures are restored
659 # Ensure key global structures are restored
659 sys.argv = save_argv
660 sys.argv = save_argv
660 if restore_main:
661 if restore_main:
661 sys.modules['__main__'] = restore_main
662 sys.modules['__main__'] = restore_main
662 else:
663 else:
663 # Remove from sys.modules the reference to main_mod we'd
664 # Remove from sys.modules the reference to main_mod we'd
664 # added. Otherwise it will trap references to objects
665 # added. Otherwise it will trap references to objects
665 # contained therein.
666 # contained therein.
666 del sys.modules[main_mod_name]
667 del sys.modules[main_mod_name]
667
668
668 return stats
669 return stats
669
670
670 @skip_doctest
671 @skip_doctest
671 @line_cell_magic
672 @line_cell_magic
672 def timeit(self, line='', cell=None):
673 def timeit(self, line='', cell=None):
673 """Time execution of a Python statement or expression
674 """Time execution of a Python statement or expression
674
675
675 Usage, in line mode:
676 Usage, in line mode:
676 %timeit [-n<N> -r<R> [-t|-c]] statement
677 %timeit [-n<N> -r<R> [-t|-c]] statement
677 or in cell mode:
678 or in cell mode:
678 %%timeit [-n<N> -r<R> [-t|-c]] setup_code
679 %%timeit [-n<N> -r<R> [-t|-c]] setup_code
679 code
680 code
680 code...
681 code...
681
682
682 Time execution of a Python statement or expression using the timeit
683 Time execution of a Python statement or expression using the timeit
683 module. This function can be used both as a line and cell magic:
684 module. This function can be used both as a line and cell magic:
684
685
685 - In line mode you can time a single-line statement (though multiple
686 - In line mode you can time a single-line statement (though multiple
686 ones can be chained with using semicolons).
687 ones can be chained with using semicolons).
687
688
688 - In cell mode, the statement in the first line is used as setup code
689 - In cell mode, the statement in the first line is used as setup code
689 (executed but not timed) and the body of the cell is timed. The cell
690 (executed but not timed) and the body of the cell is timed. The cell
690 body has access to any variables created in the setup code.
691 body has access to any variables created in the setup code.
691
692
692 Options:
693 Options:
693 -n<N>: execute the given statement <N> times in a loop. If this value
694 -n<N>: execute the given statement <N> times in a loop. If this value
694 is not given, a fitting value is chosen.
695 is not given, a fitting value is chosen.
695
696
696 -r<R>: repeat the loop iteration <R> times and take the best result.
697 -r<R>: repeat the loop iteration <R> times and take the best result.
697 Default: 3
698 Default: 3
698
699
699 -t: use time.time to measure the time, which is the default on Unix.
700 -t: use time.time to measure the time, which is the default on Unix.
700 This function measures wall time.
701 This function measures wall time.
701
702
702 -c: use time.clock to measure the time, which is the default on
703 -c: use time.clock to measure the time, which is the default on
703 Windows and measures wall time. On Unix, resource.getrusage is used
704 Windows and measures wall time. On Unix, resource.getrusage is used
704 instead and returns the CPU user time.
705 instead and returns the CPU user time.
705
706
706 -p<P>: use a precision of <P> digits to display the timing result.
707 -p<P>: use a precision of <P> digits to display the timing result.
707 Default: 3
708 Default: 3
708
709
709
710
710 Examples
711 Examples
711 --------
712 --------
712 ::
713 ::
713
714
714 In [1]: %timeit pass
715 In [1]: %timeit pass
715 10000000 loops, best of 3: 53.3 ns per loop
716 10000000 loops, best of 3: 53.3 ns per loop
716
717
717 In [2]: u = None
718 In [2]: u = None
718
719
719 In [3]: %timeit u is None
720 In [3]: %timeit u is None
720 10000000 loops, best of 3: 184 ns per loop
721 10000000 loops, best of 3: 184 ns per loop
721
722
722 In [4]: %timeit -r 4 u == None
723 In [4]: %timeit -r 4 u == None
723 1000000 loops, best of 4: 242 ns per loop
724 1000000 loops, best of 4: 242 ns per loop
724
725
725 In [5]: import time
726 In [5]: import time
726
727
727 In [6]: %timeit -n1 time.sleep(2)
728 In [6]: %timeit -n1 time.sleep(2)
728 1 loops, best of 3: 2 s per loop
729 1 loops, best of 3: 2 s per loop
729
730
730
731
731 The times reported by %timeit will be slightly higher than those
732 The times reported by %timeit will be slightly higher than those
732 reported by the timeit.py script when variables are accessed. This is
733 reported by the timeit.py script when variables are accessed. This is
733 due to the fact that %timeit executes the statement in the namespace
734 due to the fact that %timeit executes the statement in the namespace
734 of the shell, compared with timeit.py, which uses a single setup
735 of the shell, compared with timeit.py, which uses a single setup
735 statement to import function or create variables. Generally, the bias
736 statement to import function or create variables. Generally, the bias
736 does not matter as long as results from timeit.py are not mixed with
737 does not matter as long as results from timeit.py are not mixed with
737 those from %timeit."""
738 those from %timeit."""
738
739
739 import timeit
740 import timeit
740 import math
741 import math
741
742
742 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
743 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
743 # certain terminals. Until we figure out a robust way of
744 # certain terminals. Until we figure out a robust way of
744 # auto-detecting if the terminal can deal with it, use plain 'us' for
745 # auto-detecting if the terminal can deal with it, use plain 'us' for
745 # microseconds. I am really NOT happy about disabling the proper
746 # microseconds. I am really NOT happy about disabling the proper
746 # 'micro' prefix, but crashing is worse... If anyone knows what the
747 # 'micro' prefix, but crashing is worse... If anyone knows what the
747 # right solution for this is, I'm all ears...
748 # right solution for this is, I'm all ears...
748 #
749 #
749 # Note: using
750 # Note: using
750 #
751 #
751 # s = u'\xb5'
752 # s = u'\xb5'
752 # s.encode(sys.getdefaultencoding())
753 # s.encode(sys.getdefaultencoding())
753 #
754 #
754 # is not sufficient, as I've seen terminals where that fails but
755 # is not sufficient, as I've seen terminals where that fails but
755 # print s
756 # print s
756 #
757 #
757 # succeeds
758 # succeeds
758 #
759 #
759 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
760 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
760
761
761 #units = [u"s", u"ms",u'\xb5',"ns"]
762 #units = [u"s", u"ms",u'\xb5',"ns"]
762 units = [u"s", u"ms",u'us',"ns"]
763 units = [u"s", u"ms",u'us',"ns"]
763
764
764 scaling = [1, 1e3, 1e6, 1e9]
765 scaling = [1, 1e3, 1e6, 1e9]
765
766
766 opts, stmt = self.parse_options(line,'n:r:tcp:',
767 opts, stmt = self.parse_options(line,'n:r:tcp:',
767 posix=False, strict=False)
768 posix=False, strict=False)
768 if stmt == "" and cell is None:
769 if stmt == "" and cell is None:
769 return
770 return
770 timefunc = timeit.default_timer
771 timefunc = timeit.default_timer
771 number = int(getattr(opts, "n", 0))
772 number = int(getattr(opts, "n", 0))
772 repeat = int(getattr(opts, "r", timeit.default_repeat))
773 repeat = int(getattr(opts, "r", timeit.default_repeat))
773 precision = int(getattr(opts, "p", 3))
774 precision = int(getattr(opts, "p", 3))
774 if hasattr(opts, "t"):
775 if hasattr(opts, "t"):
775 timefunc = time.time
776 timefunc = time.time
776 if hasattr(opts, "c"):
777 if hasattr(opts, "c"):
777 timefunc = clock
778 timefunc = clock
778
779
779 timer = timeit.Timer(timer=timefunc)
780 timer = timeit.Timer(timer=timefunc)
780 # this code has tight coupling to the inner workings of timeit.Timer,
781 # this code has tight coupling to the inner workings of timeit.Timer,
781 # but is there a better way to achieve that the code stmt has access
782 # but is there a better way to achieve that the code stmt has access
782 # to the shell namespace?
783 # to the shell namespace?
783 transform = self.shell.input_splitter.transform_cell
784 transform = self.shell.input_splitter.transform_cell
785
784 if cell is None:
786 if cell is None:
785 # called as line magic
787 # called as line magic
786 setup = 'pass'
788 ast_setup = ast.parse("pass")
787 stmt = timeit.reindent(transform(stmt), 8)
789 ast_stmt = ast.parse(transform(stmt))
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)
795 else:
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 # Track compilation time so it can be reported if too long
827 # Track compilation time so it can be reported if too long
799 # Minimum time above which compilation time will be reported
828 # Minimum time above which compilation time will be reported
800 tc_min = 0.1
829 tc_min = 0.1
801
830
802 t0 = clock()
831 t0 = clock()
803 code = compile(src, "<magic-timeit>", "exec")
832 code = compile(timeit_ast, "<magic-timeit>", "exec")
804 tc = clock()-t0
833 tc = clock()-t0
805
834
806 ns = {}
835 ns = {}
807 exec code in self.shell.user_ns, ns
836 exec code in self.shell.user_ns, ns
808 timer.inner = ns["inner"]
837 timer.inner = ns["inner"]
809
838
810 if number == 0:
839 if number == 0:
811 # determine number so that 0.2 <= total time < 2.0
840 # determine number so that 0.2 <= total time < 2.0
812 number = 1
841 number = 1
813 for i in range(1, 10):
842 for i in range(1, 10):
814 if timer.timeit(number) >= 0.2:
843 if timer.timeit(number) >= 0.2:
815 break
844 break
816 number *= 10
845 number *= 10
817
846
818 best = min(timer.repeat(repeat, number)) / number
847 best = min(timer.repeat(repeat, number)) / number
819
848
820 if best > 0.0 and best < 1000.0:
849 if best > 0.0 and best < 1000.0:
821 order = min(-int(math.floor(math.log10(best)) // 3), 3)
850 order = min(-int(math.floor(math.log10(best)) // 3), 3)
822 elif best >= 1000.0:
851 elif best >= 1000.0:
823 order = 0
852 order = 0
824 else:
853 else:
825 order = 3
854 order = 3
826 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
855 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
827 precision,
856 precision,
828 best * scaling[order],
857 best * scaling[order],
829 units[order])
858 units[order])
830 if tc > tc_min:
859 if tc > tc_min:
831 print "Compiler time: %.2f s" % tc
860 print "Compiler time: %.2f s" % tc
832
861
833 @skip_doctest
862 @skip_doctest
834 @needs_local_scope
863 @needs_local_scope
835 @line_magic
864 @line_magic
836 def time(self,parameter_s, local_ns=None):
865 def time(self,parameter_s, local_ns=None):
837 """Time execution of a Python statement or expression.
866 """Time execution of a Python statement or expression.
838
867
839 The CPU and wall clock times are printed, and the value of the
868 The CPU and wall clock times are printed, and the value of the
840 expression (if any) is returned. Note that under Win32, system time
869 expression (if any) is returned. Note that under Win32, system time
841 is always reported as 0, since it can not be measured.
870 is always reported as 0, since it can not be measured.
842
871
843 This function provides very basic timing functionality. In Python
872 This function provides very basic timing functionality. In Python
844 2.3, the timeit module offers more control and sophistication, so this
873 2.3, the timeit module offers more control and sophistication, so this
845 could be rewritten to use it (patches welcome).
874 could be rewritten to use it (patches welcome).
846
875
847 Examples
876 Examples
848 --------
877 --------
849 ::
878 ::
850
879
851 In [1]: time 2**128
880 In [1]: time 2**128
852 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
881 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
853 Wall time: 0.00
882 Wall time: 0.00
854 Out[1]: 340282366920938463463374607431768211456L
883 Out[1]: 340282366920938463463374607431768211456L
855
884
856 In [2]: n = 1000000
885 In [2]: n = 1000000
857
886
858 In [3]: time sum(range(n))
887 In [3]: time sum(range(n))
859 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
888 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
860 Wall time: 1.37
889 Wall time: 1.37
861 Out[3]: 499999500000L
890 Out[3]: 499999500000L
862
891
863 In [4]: time print 'hello world'
892 In [4]: time print 'hello world'
864 hello world
893 hello world
865 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
894 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
866 Wall time: 0.00
895 Wall time: 0.00
867
896
868 Note that the time needed by Python to compile the given expression
897 Note that the time needed by Python to compile the given expression
869 will be reported if it is more than 0.1s. In this example, the
898 will be reported if it is more than 0.1s. In this example, the
870 actual exponentiation is done by Python at compilation time, so while
899 actual exponentiation is done by Python at compilation time, so while
871 the expression can take a noticeable amount of time to compute, that
900 the expression can take a noticeable amount of time to compute, that
872 time is purely due to the compilation:
901 time is purely due to the compilation:
873
902
874 In [5]: time 3**9999;
903 In [5]: time 3**9999;
875 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
904 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
876 Wall time: 0.00 s
905 Wall time: 0.00 s
877
906
878 In [6]: time 3**999999;
907 In [6]: time 3**999999;
879 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
908 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
880 Wall time: 0.00 s
909 Wall time: 0.00 s
881 Compiler : 0.78 s
910 Compiler : 0.78 s
882 """
911 """
883
912
884 # fail immediately if the given expression can't be compiled
913 # fail immediately if the given expression can't be compiled
885
914
886 expr = self.shell.prefilter(parameter_s,False)
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 # Minimum time above which compilation time will be reported
927 # Minimum time above which compilation time will be reported
889 tc_min = 0.1
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 mode = 'eval'
931 mode = 'eval'
893 t0 = clock()
932 source = '<timed eval>'
894 code = compile(expr,'<timed eval>',mode)
933 expr_ast = ast.Expression(expr_ast.body[0].value)
895 tc = clock()-t0
934 else:
896 except SyntaxError:
897 mode = 'exec'
935 mode = 'exec'
898 t0 = clock()
936 source = '<timed exec>'
899 code = compile(expr,'<timed exec>',mode)
937 t0 = clock()
900 tc = clock()-t0
938 code = compile(expr_ast, source, mode)
939 tc = clock()-t0
940
901 # skew measurement as little as possible
941 # skew measurement as little as possible
902 glob = self.shell.user_ns
942 glob = self.shell.user_ns
903 wtime = time.time
943 wtime = time.time
904 # time execution
944 # time execution
905 wall_st = wtime()
945 wall_st = wtime()
906 if mode=='eval':
946 if mode=='eval':
907 st = clock2()
947 st = clock2()
908 out = eval(code, glob, local_ns)
948 out = eval(code, glob, local_ns)
909 end = clock2()
949 end = clock2()
910 else:
950 else:
911 st = clock2()
951 st = clock2()
912 exec code in glob, local_ns
952 exec code in glob, local_ns
913 end = clock2()
953 end = clock2()
914 out = None
954 out = None
915 wall_end = wtime()
955 wall_end = wtime()
916 # Compute actual times and report
956 # Compute actual times and report
917 wall_time = wall_end-wall_st
957 wall_time = wall_end-wall_st
918 cpu_user = end[0]-st[0]
958 cpu_user = end[0]-st[0]
919 cpu_sys = end[1]-st[1]
959 cpu_sys = end[1]-st[1]
920 cpu_tot = cpu_user+cpu_sys
960 cpu_tot = cpu_user+cpu_sys
921 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
961 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
922 (cpu_user,cpu_sys,cpu_tot)
962 (cpu_user,cpu_sys,cpu_tot)
923 print "Wall time: %.2f s" % wall_time
963 print "Wall time: %.2f s" % wall_time
924 if tc > tc_min:
964 if tc > tc_min:
925 print "Compiler : %.2f s" % tc
965 print "Compiler : %.2f s" % tc
966 if tp > tp_min:
967 print "Parser : %.2f s" % tp
926 return out
968 return out
927
969
928 @skip_doctest
970 @skip_doctest
929 @line_magic
971 @line_magic
930 def macro(self, parameter_s=''):
972 def macro(self, parameter_s=''):
931 """Define a macro for future re-execution. It accepts ranges of history,
973 """Define a macro for future re-execution. It accepts ranges of history,
932 filenames or string objects.
974 filenames or string objects.
933
975
934 Usage:\\
976 Usage:\\
935 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
977 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
936
978
937 Options:
979 Options:
938
980
939 -r: use 'raw' input. By default, the 'processed' history is used,
981 -r: use 'raw' input. By default, the 'processed' history is used,
940 so that magics are loaded in their transformed version to valid
982 so that magics are loaded in their transformed version to valid
941 Python. If this option is given, the raw input as typed as the
983 Python. If this option is given, the raw input as typed as the
942 command line is used instead.
984 command line is used instead.
943
985
944 This will define a global variable called `name` which is a string
986 This will define a global variable called `name` which is a string
945 made of joining the slices and lines you specify (n1,n2,... numbers
987 made of joining the slices and lines you specify (n1,n2,... numbers
946 above) from your input history into a single string. This variable
988 above) from your input history into a single string. This variable
947 acts like an automatic function which re-executes those lines as if
989 acts like an automatic function which re-executes those lines as if
948 you had typed them. You just type 'name' at the prompt and the code
990 you had typed them. You just type 'name' at the prompt and the code
949 executes.
991 executes.
950
992
951 The syntax for indicating input ranges is described in %history.
993 The syntax for indicating input ranges is described in %history.
952
994
953 Note: as a 'hidden' feature, you can also use traditional python slice
995 Note: as a 'hidden' feature, you can also use traditional python slice
954 notation, where N:M means numbers N through M-1.
996 notation, where N:M means numbers N through M-1.
955
997
956 For example, if your history contains (%hist prints it)::
998 For example, if your history contains (%hist prints it)::
957
999
958 44: x=1
1000 44: x=1
959 45: y=3
1001 45: y=3
960 46: z=x+y
1002 46: z=x+y
961 47: print x
1003 47: print x
962 48: a=5
1004 48: a=5
963 49: print 'x',x,'y',y
1005 49: print 'x',x,'y',y
964
1006
965 you can create a macro with lines 44 through 47 (included) and line 49
1007 you can create a macro with lines 44 through 47 (included) and line 49
966 called my_macro with::
1008 called my_macro with::
967
1009
968 In [55]: %macro my_macro 44-47 49
1010 In [55]: %macro my_macro 44-47 49
969
1011
970 Now, typing `my_macro` (without quotes) will re-execute all this code
1012 Now, typing `my_macro` (without quotes) will re-execute all this code
971 in one pass.
1013 in one pass.
972
1014
973 You don't need to give the line-numbers in order, and any given line
1015 You don't need to give the line-numbers in order, and any given line
974 number can appear multiple times. You can assemble macros with any
1016 number can appear multiple times. You can assemble macros with any
975 lines from your input history in any order.
1017 lines from your input history in any order.
976
1018
977 The macro is a simple object which holds its value in an attribute,
1019 The macro is a simple object which holds its value in an attribute,
978 but IPython's display system checks for macros and executes them as
1020 but IPython's display system checks for macros and executes them as
979 code instead of printing them when you type their name.
1021 code instead of printing them when you type their name.
980
1022
981 You can view a macro's contents by explicitly printing it with::
1023 You can view a macro's contents by explicitly printing it with::
982
1024
983 print macro_name
1025 print macro_name
984
1026
985 """
1027 """
986 opts,args = self.parse_options(parameter_s,'r',mode='list')
1028 opts,args = self.parse_options(parameter_s,'r',mode='list')
987 if not args: # List existing macros
1029 if not args: # List existing macros
988 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
1030 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
989 isinstance(v, Macro))
1031 isinstance(v, Macro))
990 if len(args) == 1:
1032 if len(args) == 1:
991 raise UsageError(
1033 raise UsageError(
992 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1034 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
993 name, codefrom = args[0], " ".join(args[1:])
1035 name, codefrom = args[0], " ".join(args[1:])
994
1036
995 #print 'rng',ranges # dbg
1037 #print 'rng',ranges # dbg
996 try:
1038 try:
997 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1039 lines = self.shell.find_user_code(codefrom, 'r' in opts)
998 except (ValueError, TypeError) as e:
1040 except (ValueError, TypeError) as e:
999 print e.args[0]
1041 print e.args[0]
1000 return
1042 return
1001 macro = Macro(lines)
1043 macro = Macro(lines)
1002 self.shell.define_macro(name, macro)
1044 self.shell.define_macro(name, macro)
1003 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1045 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1004 print '=== Macro contents: ==='
1046 print '=== Macro contents: ==='
1005 print macro,
1047 print macro,
1006
1048
1007 @magic_arguments.magic_arguments()
1049 @magic_arguments.magic_arguments()
1008 @magic_arguments.argument('output', type=str, default='', nargs='?',
1050 @magic_arguments.argument('output', type=str, default='', nargs='?',
1009 help="""The name of the variable in which to store output.
1051 help="""The name of the variable in which to store output.
1010 This is a utils.io.CapturedIO object with stdout/err attributes
1052 This is a utils.io.CapturedIO object with stdout/err attributes
1011 for the text of the captured output.
1053 for the text of the captured output.
1012
1054
1013 CapturedOutput also has a show() method for displaying the output,
1055 CapturedOutput also has a show() method for displaying the output,
1014 and __call__ as well, so you can use that to quickly display the
1056 and __call__ as well, so you can use that to quickly display the
1015 output.
1057 output.
1016
1058
1017 If unspecified, captured output is discarded.
1059 If unspecified, captured output is discarded.
1018 """
1060 """
1019 )
1061 )
1020 @magic_arguments.argument('--no-stderr', action="store_true",
1062 @magic_arguments.argument('--no-stderr', action="store_true",
1021 help="""Don't capture stderr."""
1063 help="""Don't capture stderr."""
1022 )
1064 )
1023 @magic_arguments.argument('--no-stdout', action="store_true",
1065 @magic_arguments.argument('--no-stdout', action="store_true",
1024 help="""Don't capture stdout."""
1066 help="""Don't capture stdout."""
1025 )
1067 )
1026 @cell_magic
1068 @cell_magic
1027 def capture(self, line, cell):
1069 def capture(self, line, cell):
1028 """run the cell, capturing stdout/err"""
1070 """run the cell, capturing stdout/err"""
1029 args = magic_arguments.parse_argstring(self.capture, line)
1071 args = magic_arguments.parse_argstring(self.capture, line)
1030 out = not args.no_stdout
1072 out = not args.no_stdout
1031 err = not args.no_stderr
1073 err = not args.no_stderr
1032 with capture_output(out, err) as io:
1074 with capture_output(out, err) as io:
1033 self.shell.run_cell(cell)
1075 self.shell.run_cell(cell)
1034 if args.output:
1076 if args.output:
1035 self.shell.user_ns[args.output] = io
1077 self.shell.user_ns[args.output] = io
@@ -1,432 +1,559 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Tests for the key interactiveshell module.
2 """Tests for the key interactiveshell module.
3
3
4 Historically the main classes in interactiveshell have been under-tested. This
4 Historically the main classes in interactiveshell have been under-tested. This
5 module should grow as many single-method tests as possible to trap many of the
5 module should grow as many single-method tests as possible to trap many of the
6 recurring bugs we seem to encounter with high-level interaction.
6 recurring bugs we seem to encounter with high-level interaction.
7
7
8 Authors
8 Authors
9 -------
9 -------
10 * Fernando Perez
10 * Fernando Perez
11 """
11 """
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Copyright (C) 2011 The IPython Development Team
13 # Copyright (C) 2011 The IPython Development Team
14 #
14 #
15 # Distributed under the terms of the BSD License. The full license is in
15 # Distributed under the terms of the BSD License. The full license is in
16 # the file COPYING, distributed as part of this software.
16 # the file COPYING, distributed as part of this software.
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20 # Imports
20 # Imports
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22 # stdlib
22 # stdlib
23 import ast
23 import os
24 import os
24 import shutil
25 import shutil
25 import sys
26 import sys
26 import tempfile
27 import tempfile
27 import unittest
28 import unittest
28 from os.path import join
29 from os.path import join
29 from StringIO import StringIO
30 from StringIO import StringIO
30
31
31 # third-party
32 # third-party
32 import nose.tools as nt
33 import nose.tools as nt
33
34
34 # Our own
35 # Our own
35 from IPython.testing.decorators import skipif
36 from IPython.testing.decorators import skipif
36 from IPython.testing import tools as tt
37 from IPython.testing import tools as tt
37 from IPython.utils import io
38 from IPython.utils import io
38
39
39 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
40 # Globals
41 # Globals
41 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
42 # This is used by every single test, no point repeating it ad nauseam
43 # This is used by every single test, no point repeating it ad nauseam
43 ip = get_ipython()
44 ip = get_ipython()
44
45
45 #-----------------------------------------------------------------------------
46 #-----------------------------------------------------------------------------
46 # Tests
47 # Tests
47 #-----------------------------------------------------------------------------
48 #-----------------------------------------------------------------------------
48
49
49 class InteractiveShellTestCase(unittest.TestCase):
50 class InteractiveShellTestCase(unittest.TestCase):
50 def test_naked_string_cells(self):
51 def test_naked_string_cells(self):
51 """Test that cells with only naked strings are fully executed"""
52 """Test that cells with only naked strings are fully executed"""
52 # First, single-line inputs
53 # First, single-line inputs
53 ip.run_cell('"a"\n')
54 ip.run_cell('"a"\n')
54 self.assertEqual(ip.user_ns['_'], 'a')
55 self.assertEqual(ip.user_ns['_'], 'a')
55 # And also multi-line cells
56 # And also multi-line cells
56 ip.run_cell('"""a\nb"""\n')
57 ip.run_cell('"""a\nb"""\n')
57 self.assertEqual(ip.user_ns['_'], 'a\nb')
58 self.assertEqual(ip.user_ns['_'], 'a\nb')
58
59
59 def test_run_empty_cell(self):
60 def test_run_empty_cell(self):
60 """Just make sure we don't get a horrible error with a blank
61 """Just make sure we don't get a horrible error with a blank
61 cell of input. Yes, I did overlook that."""
62 cell of input. Yes, I did overlook that."""
62 old_xc = ip.execution_count
63 old_xc = ip.execution_count
63 ip.run_cell('')
64 ip.run_cell('')
64 self.assertEqual(ip.execution_count, old_xc)
65 self.assertEqual(ip.execution_count, old_xc)
65
66
66 def test_run_cell_multiline(self):
67 def test_run_cell_multiline(self):
67 """Multi-block, multi-line cells must execute correctly.
68 """Multi-block, multi-line cells must execute correctly.
68 """
69 """
69 src = '\n'.join(["x=1",
70 src = '\n'.join(["x=1",
70 "y=2",
71 "y=2",
71 "if 1:",
72 "if 1:",
72 " x += 1",
73 " x += 1",
73 " y += 1",])
74 " y += 1",])
74 ip.run_cell(src)
75 ip.run_cell(src)
75 self.assertEqual(ip.user_ns['x'], 2)
76 self.assertEqual(ip.user_ns['x'], 2)
76 self.assertEqual(ip.user_ns['y'], 3)
77 self.assertEqual(ip.user_ns['y'], 3)
77
78
78 def test_multiline_string_cells(self):
79 def test_multiline_string_cells(self):
79 "Code sprinkled with multiline strings should execute (GH-306)"
80 "Code sprinkled with multiline strings should execute (GH-306)"
80 ip.run_cell('tmp=0')
81 ip.run_cell('tmp=0')
81 self.assertEqual(ip.user_ns['tmp'], 0)
82 self.assertEqual(ip.user_ns['tmp'], 0)
82 ip.run_cell('tmp=1;"""a\nb"""\n')
83 ip.run_cell('tmp=1;"""a\nb"""\n')
83 self.assertEqual(ip.user_ns['tmp'], 1)
84 self.assertEqual(ip.user_ns['tmp'], 1)
84
85
85 def test_dont_cache_with_semicolon(self):
86 def test_dont_cache_with_semicolon(self):
86 "Ending a line with semicolon should not cache the returned object (GH-307)"
87 "Ending a line with semicolon should not cache the returned object (GH-307)"
87 oldlen = len(ip.user_ns['Out'])
88 oldlen = len(ip.user_ns['Out'])
88 a = ip.run_cell('1;', store_history=True)
89 a = ip.run_cell('1;', store_history=True)
89 newlen = len(ip.user_ns['Out'])
90 newlen = len(ip.user_ns['Out'])
90 self.assertEqual(oldlen, newlen)
91 self.assertEqual(oldlen, newlen)
91 #also test the default caching behavior
92 #also test the default caching behavior
92 ip.run_cell('1', store_history=True)
93 ip.run_cell('1', store_history=True)
93 newlen = len(ip.user_ns['Out'])
94 newlen = len(ip.user_ns['Out'])
94 self.assertEqual(oldlen+1, newlen)
95 self.assertEqual(oldlen+1, newlen)
95
96
96 def test_In_variable(self):
97 def test_In_variable(self):
97 "Verify that In variable grows with user input (GH-284)"
98 "Verify that In variable grows with user input (GH-284)"
98 oldlen = len(ip.user_ns['In'])
99 oldlen = len(ip.user_ns['In'])
99 ip.run_cell('1;', store_history=True)
100 ip.run_cell('1;', store_history=True)
100 newlen = len(ip.user_ns['In'])
101 newlen = len(ip.user_ns['In'])
101 self.assertEqual(oldlen+1, newlen)
102 self.assertEqual(oldlen+1, newlen)
102 self.assertEqual(ip.user_ns['In'][-1],'1;')
103 self.assertEqual(ip.user_ns['In'][-1],'1;')
103
104
104 def test_magic_names_in_string(self):
105 def test_magic_names_in_string(self):
105 ip.run_cell('a = """\n%exit\n"""')
106 ip.run_cell('a = """\n%exit\n"""')
106 self.assertEqual(ip.user_ns['a'], '\n%exit\n')
107 self.assertEqual(ip.user_ns['a'], '\n%exit\n')
107
108
108 def test_alias_crash(self):
109 def test_alias_crash(self):
109 """Errors in prefilter can't crash IPython"""
110 """Errors in prefilter can't crash IPython"""
110 ip.run_cell('%alias parts echo first %s second %s')
111 ip.run_cell('%alias parts echo first %s second %s')
111 # capture stderr:
112 # capture stderr:
112 save_err = io.stderr
113 save_err = io.stderr
113 io.stderr = StringIO()
114 io.stderr = StringIO()
114 ip.run_cell('parts 1')
115 ip.run_cell('parts 1')
115 err = io.stderr.getvalue()
116 err = io.stderr.getvalue()
116 io.stderr = save_err
117 io.stderr = save_err
117 self.assertEqual(err.split(':')[0], 'ERROR')
118 self.assertEqual(err.split(':')[0], 'ERROR')
118
119
119 def test_trailing_newline(self):
120 def test_trailing_newline(self):
120 """test that running !(command) does not raise a SyntaxError"""
121 """test that running !(command) does not raise a SyntaxError"""
121 ip.run_cell('!(true)\n', False)
122 ip.run_cell('!(true)\n', False)
122 ip.run_cell('!(true)\n\n\n', False)
123 ip.run_cell('!(true)\n\n\n', False)
123
124
124 def test_gh_597(self):
125 def test_gh_597(self):
125 """Pretty-printing lists of objects with non-ascii reprs may cause
126 """Pretty-printing lists of objects with non-ascii reprs may cause
126 problems."""
127 problems."""
127 class Spam(object):
128 class Spam(object):
128 def __repr__(self):
129 def __repr__(self):
129 return "\xe9"*50
130 return "\xe9"*50
130 import IPython.core.formatters
131 import IPython.core.formatters
131 f = IPython.core.formatters.PlainTextFormatter()
132 f = IPython.core.formatters.PlainTextFormatter()
132 f([Spam(),Spam()])
133 f([Spam(),Spam()])
133
134
134
135
135 def test_future_flags(self):
136 def test_future_flags(self):
136 """Check that future flags are used for parsing code (gh-777)"""
137 """Check that future flags are used for parsing code (gh-777)"""
137 ip.run_cell('from __future__ import print_function')
138 ip.run_cell('from __future__ import print_function')
138 try:
139 try:
139 ip.run_cell('prfunc_return_val = print(1,2, sep=" ")')
140 ip.run_cell('prfunc_return_val = print(1,2, sep=" ")')
140 assert 'prfunc_return_val' in ip.user_ns
141 assert 'prfunc_return_val' in ip.user_ns
141 finally:
142 finally:
142 # Reset compiler flags so we don't mess up other tests.
143 # Reset compiler flags so we don't mess up other tests.
143 ip.compile.reset_compiler_flags()
144 ip.compile.reset_compiler_flags()
144
145
145 def test_future_unicode(self):
146 def test_future_unicode(self):
146 """Check that unicode_literals is imported from __future__ (gh #786)"""
147 """Check that unicode_literals is imported from __future__ (gh #786)"""
147 try:
148 try:
148 ip.run_cell(u'byte_str = "a"')
149 ip.run_cell(u'byte_str = "a"')
149 assert isinstance(ip.user_ns['byte_str'], str) # string literals are byte strings by default
150 assert isinstance(ip.user_ns['byte_str'], str) # string literals are byte strings by default
150 ip.run_cell('from __future__ import unicode_literals')
151 ip.run_cell('from __future__ import unicode_literals')
151 ip.run_cell(u'unicode_str = "a"')
152 ip.run_cell(u'unicode_str = "a"')
152 assert isinstance(ip.user_ns['unicode_str'], unicode) # strings literals are now unicode
153 assert isinstance(ip.user_ns['unicode_str'], unicode) # strings literals are now unicode
153 finally:
154 finally:
154 # Reset compiler flags so we don't mess up other tests.
155 # Reset compiler flags so we don't mess up other tests.
155 ip.compile.reset_compiler_flags()
156 ip.compile.reset_compiler_flags()
156
157
157 def test_can_pickle(self):
158 def test_can_pickle(self):
158 "Can we pickle objects defined interactively (GH-29)"
159 "Can we pickle objects defined interactively (GH-29)"
159 ip = get_ipython()
160 ip = get_ipython()
160 ip.reset()
161 ip.reset()
161 ip.run_cell(("class Mylist(list):\n"
162 ip.run_cell(("class Mylist(list):\n"
162 " def __init__(self,x=[]):\n"
163 " def __init__(self,x=[]):\n"
163 " list.__init__(self,x)"))
164 " list.__init__(self,x)"))
164 ip.run_cell("w=Mylist([1,2,3])")
165 ip.run_cell("w=Mylist([1,2,3])")
165
166
166 from cPickle import dumps
167 from cPickle import dumps
167
168
168 # We need to swap in our main module - this is only necessary
169 # We need to swap in our main module - this is only necessary
169 # inside the test framework, because IPython puts the interactive module
170 # inside the test framework, because IPython puts the interactive module
170 # in place (but the test framework undoes this).
171 # in place (but the test framework undoes this).
171 _main = sys.modules['__main__']
172 _main = sys.modules['__main__']
172 sys.modules['__main__'] = ip.user_module
173 sys.modules['__main__'] = ip.user_module
173 try:
174 try:
174 res = dumps(ip.user_ns["w"])
175 res = dumps(ip.user_ns["w"])
175 finally:
176 finally:
176 sys.modules['__main__'] = _main
177 sys.modules['__main__'] = _main
177 self.assertTrue(isinstance(res, bytes))
178 self.assertTrue(isinstance(res, bytes))
178
179
179 def test_global_ns(self):
180 def test_global_ns(self):
180 "Code in functions must be able to access variables outside them."
181 "Code in functions must be able to access variables outside them."
181 ip = get_ipython()
182 ip = get_ipython()
182 ip.run_cell("a = 10")
183 ip.run_cell("a = 10")
183 ip.run_cell(("def f(x):\n"
184 ip.run_cell(("def f(x):\n"
184 " return x + a"))
185 " return x + a"))
185 ip.run_cell("b = f(12)")
186 ip.run_cell("b = f(12)")
186 self.assertEqual(ip.user_ns["b"], 22)
187 self.assertEqual(ip.user_ns["b"], 22)
187
188
188 def test_bad_custom_tb(self):
189 def test_bad_custom_tb(self):
189 """Check that InteractiveShell is protected from bad custom exception handlers"""
190 """Check that InteractiveShell is protected from bad custom exception handlers"""
190 from IPython.utils import io
191 from IPython.utils import io
191 save_stderr = io.stderr
192 save_stderr = io.stderr
192 try:
193 try:
193 # capture stderr
194 # capture stderr
194 io.stderr = StringIO()
195 io.stderr = StringIO()
195 ip.set_custom_exc((IOError,), lambda etype,value,tb: 1/0)
196 ip.set_custom_exc((IOError,), lambda etype,value,tb: 1/0)
196 self.assertEqual(ip.custom_exceptions, (IOError,))
197 self.assertEqual(ip.custom_exceptions, (IOError,))
197 ip.run_cell(u'raise IOError("foo")')
198 ip.run_cell(u'raise IOError("foo")')
198 self.assertEqual(ip.custom_exceptions, ())
199 self.assertEqual(ip.custom_exceptions, ())
199 self.assertTrue("Custom TB Handler failed" in io.stderr.getvalue())
200 self.assertTrue("Custom TB Handler failed" in io.stderr.getvalue())
200 finally:
201 finally:
201 io.stderr = save_stderr
202 io.stderr = save_stderr
202
203
203 def test_bad_custom_tb_return(self):
204 def test_bad_custom_tb_return(self):
204 """Check that InteractiveShell is protected from bad return types in custom exception handlers"""
205 """Check that InteractiveShell is protected from bad return types in custom exception handlers"""
205 from IPython.utils import io
206 from IPython.utils import io
206 save_stderr = io.stderr
207 save_stderr = io.stderr
207 try:
208 try:
208 # capture stderr
209 # capture stderr
209 io.stderr = StringIO()
210 io.stderr = StringIO()
210 ip.set_custom_exc((NameError,),lambda etype,value,tb, tb_offset=None: 1)
211 ip.set_custom_exc((NameError,),lambda etype,value,tb, tb_offset=None: 1)
211 self.assertEqual(ip.custom_exceptions, (NameError,))
212 self.assertEqual(ip.custom_exceptions, (NameError,))
212 ip.run_cell(u'a=abracadabra')
213 ip.run_cell(u'a=abracadabra')
213 self.assertEqual(ip.custom_exceptions, ())
214 self.assertEqual(ip.custom_exceptions, ())
214 self.assertTrue("Custom TB Handler failed" in io.stderr.getvalue())
215 self.assertTrue("Custom TB Handler failed" in io.stderr.getvalue())
215 finally:
216 finally:
216 io.stderr = save_stderr
217 io.stderr = save_stderr
217
218
218 def test_drop_by_id(self):
219 def test_drop_by_id(self):
219 myvars = {"a":object(), "b":object(), "c": object()}
220 myvars = {"a":object(), "b":object(), "c": object()}
220 ip.push(myvars, interactive=False)
221 ip.push(myvars, interactive=False)
221 for name in myvars:
222 for name in myvars:
222 assert name in ip.user_ns, name
223 assert name in ip.user_ns, name
223 assert name in ip.user_ns_hidden, name
224 assert name in ip.user_ns_hidden, name
224 ip.user_ns['b'] = 12
225 ip.user_ns['b'] = 12
225 ip.drop_by_id(myvars)
226 ip.drop_by_id(myvars)
226 for name in ["a", "c"]:
227 for name in ["a", "c"]:
227 assert name not in ip.user_ns, name
228 assert name not in ip.user_ns, name
228 assert name not in ip.user_ns_hidden, name
229 assert name not in ip.user_ns_hidden, name
229 assert ip.user_ns['b'] == 12
230 assert ip.user_ns['b'] == 12
230 ip.reset()
231 ip.reset()
231
232
232 def test_var_expand(self):
233 def test_var_expand(self):
233 ip.user_ns['f'] = u'Ca\xf1o'
234 ip.user_ns['f'] = u'Ca\xf1o'
234 self.assertEqual(ip.var_expand(u'echo $f'), u'echo Ca\xf1o')
235 self.assertEqual(ip.var_expand(u'echo $f'), u'echo Ca\xf1o')
235 self.assertEqual(ip.var_expand(u'echo {f}'), u'echo Ca\xf1o')
236 self.assertEqual(ip.var_expand(u'echo {f}'), u'echo Ca\xf1o')
236 self.assertEqual(ip.var_expand(u'echo {f[:-1]}'), u'echo Ca\xf1')
237 self.assertEqual(ip.var_expand(u'echo {f[:-1]}'), u'echo Ca\xf1')
237 self.assertEqual(ip.var_expand(u'echo {1*2}'), u'echo 2')
238 self.assertEqual(ip.var_expand(u'echo {1*2}'), u'echo 2')
238
239
239 ip.user_ns['f'] = b'Ca\xc3\xb1o'
240 ip.user_ns['f'] = b'Ca\xc3\xb1o'
240 # This should not raise any exception:
241 # This should not raise any exception:
241 ip.var_expand(u'echo $f')
242 ip.var_expand(u'echo $f')
242
243
243 def test_var_expand_local(self):
244 def test_var_expand_local(self):
244 """Test local variable expansion in !system and %magic calls"""
245 """Test local variable expansion in !system and %magic calls"""
245 # !system
246 # !system
246 ip.run_cell('def test():\n'
247 ip.run_cell('def test():\n'
247 ' lvar = "ttt"\n'
248 ' lvar = "ttt"\n'
248 ' ret = !echo {lvar}\n'
249 ' ret = !echo {lvar}\n'
249 ' return ret[0]\n')
250 ' return ret[0]\n')
250 res = ip.user_ns['test']()
251 res = ip.user_ns['test']()
251 nt.assert_in('ttt', res)
252 nt.assert_in('ttt', res)
252
253
253 # %magic
254 # %magic
254 ip.run_cell('def makemacro():\n'
255 ip.run_cell('def makemacro():\n'
255 ' macroname = "macro_var_expand_locals"\n'
256 ' macroname = "macro_var_expand_locals"\n'
256 ' %macro {macroname} codestr\n')
257 ' %macro {macroname} codestr\n')
257 ip.user_ns['codestr'] = "str(12)"
258 ip.user_ns['codestr'] = "str(12)"
258 ip.run_cell('makemacro()')
259 ip.run_cell('makemacro()')
259 nt.assert_in('macro_var_expand_locals', ip.user_ns)
260 nt.assert_in('macro_var_expand_locals', ip.user_ns)
260
261
261 def test_var_expand_self(self):
262 def test_var_expand_self(self):
262 """Test variable expansion with the name 'self', which was failing.
263 """Test variable expansion with the name 'self', which was failing.
263
264
264 See https://github.com/ipython/ipython/issues/1878#issuecomment-7698218
265 See https://github.com/ipython/ipython/issues/1878#issuecomment-7698218
265 """
266 """
266 ip.run_cell('class cTest:\n'
267 ip.run_cell('class cTest:\n'
267 ' classvar="see me"\n'
268 ' classvar="see me"\n'
268 ' def test(self):\n'
269 ' def test(self):\n'
269 ' res = !echo Variable: {self.classvar}\n'
270 ' res = !echo Variable: {self.classvar}\n'
270 ' return res[0]\n')
271 ' return res[0]\n')
271 nt.assert_in('see me', ip.user_ns['cTest']().test())
272 nt.assert_in('see me', ip.user_ns['cTest']().test())
272
273
273 def test_bad_var_expand(self):
274 def test_bad_var_expand(self):
274 """var_expand on invalid formats shouldn't raise"""
275 """var_expand on invalid formats shouldn't raise"""
275 # SyntaxError
276 # SyntaxError
276 self.assertEqual(ip.var_expand(u"{'a':5}"), u"{'a':5}")
277 self.assertEqual(ip.var_expand(u"{'a':5}"), u"{'a':5}")
277 # NameError
278 # NameError
278 self.assertEqual(ip.var_expand(u"{asdf}"), u"{asdf}")
279 self.assertEqual(ip.var_expand(u"{asdf}"), u"{asdf}")
279 # ZeroDivisionError
280 # ZeroDivisionError
280 self.assertEqual(ip.var_expand(u"{1/0}"), u"{1/0}")
281 self.assertEqual(ip.var_expand(u"{1/0}"), u"{1/0}")
281
282
282 def test_silent_nopostexec(self):
283 def test_silent_nopostexec(self):
283 """run_cell(silent=True) doesn't invoke post-exec funcs"""
284 """run_cell(silent=True) doesn't invoke post-exec funcs"""
284 d = dict(called=False)
285 d = dict(called=False)
285 def set_called():
286 def set_called():
286 d['called'] = True
287 d['called'] = True
287
288
288 ip.register_post_execute(set_called)
289 ip.register_post_execute(set_called)
289 ip.run_cell("1", silent=True)
290 ip.run_cell("1", silent=True)
290 self.assertFalse(d['called'])
291 self.assertFalse(d['called'])
291 # double-check that non-silent exec did what we expected
292 # double-check that non-silent exec did what we expected
292 # silent to avoid
293 # silent to avoid
293 ip.run_cell("1")
294 ip.run_cell("1")
294 self.assertTrue(d['called'])
295 self.assertTrue(d['called'])
295 # remove post-exec
296 # remove post-exec
296 ip._post_execute.pop(set_called)
297 ip._post_execute.pop(set_called)
297
298
298 def test_silent_noadvance(self):
299 def test_silent_noadvance(self):
299 """run_cell(silent=True) doesn't advance execution_count"""
300 """run_cell(silent=True) doesn't advance execution_count"""
300 ec = ip.execution_count
301 ec = ip.execution_count
301 # silent should force store_history=False
302 # silent should force store_history=False
302 ip.run_cell("1", store_history=True, silent=True)
303 ip.run_cell("1", store_history=True, silent=True)
303
304
304 self.assertEqual(ec, ip.execution_count)
305 self.assertEqual(ec, ip.execution_count)
305 # double-check that non-silent exec did what we expected
306 # double-check that non-silent exec did what we expected
306 # silent to avoid
307 # silent to avoid
307 ip.run_cell("1", store_history=True)
308 ip.run_cell("1", store_history=True)
308 self.assertEqual(ec+1, ip.execution_count)
309 self.assertEqual(ec+1, ip.execution_count)
309
310
310 def test_silent_nodisplayhook(self):
311 def test_silent_nodisplayhook(self):
311 """run_cell(silent=True) doesn't trigger displayhook"""
312 """run_cell(silent=True) doesn't trigger displayhook"""
312 d = dict(called=False)
313 d = dict(called=False)
313
314
314 trap = ip.display_trap
315 trap = ip.display_trap
315 save_hook = trap.hook
316 save_hook = trap.hook
316
317
317 def failing_hook(*args, **kwargs):
318 def failing_hook(*args, **kwargs):
318 d['called'] = True
319 d['called'] = True
319
320
320 try:
321 try:
321 trap.hook = failing_hook
322 trap.hook = failing_hook
322 ip.run_cell("1", silent=True)
323 ip.run_cell("1", silent=True)
323 self.assertFalse(d['called'])
324 self.assertFalse(d['called'])
324 # double-check that non-silent exec did what we expected
325 # double-check that non-silent exec did what we expected
325 # silent to avoid
326 # silent to avoid
326 ip.run_cell("1")
327 ip.run_cell("1")
327 self.assertTrue(d['called'])
328 self.assertTrue(d['called'])
328 finally:
329 finally:
329 trap.hook = save_hook
330 trap.hook = save_hook
330
331
331 @skipif(sys.version_info[0] >= 3, "softspace removed in py3")
332 @skipif(sys.version_info[0] >= 3, "softspace removed in py3")
332 def test_print_softspace(self):
333 def test_print_softspace(self):
333 """Verify that softspace is handled correctly when executing multiple
334 """Verify that softspace is handled correctly when executing multiple
334 statements.
335 statements.
335
336
336 In [1]: print 1; print 2
337 In [1]: print 1; print 2
337 1
338 1
338 2
339 2
339
340
340 In [2]: print 1,; print 2
341 In [2]: print 1,; print 2
341 1 2
342 1 2
342 """
343 """
343
344
344 def test_ofind_line_magic(self):
345 def test_ofind_line_magic(self):
345 from IPython.core.magic import register_line_magic
346 from IPython.core.magic import register_line_magic
346
347
347 @register_line_magic
348 @register_line_magic
348 def lmagic(line):
349 def lmagic(line):
349 "A line magic"
350 "A line magic"
350
351
351 # Get info on line magic
352 # Get info on line magic
352 lfind = ip._ofind('lmagic')
353 lfind = ip._ofind('lmagic')
353 info = dict(found=True, isalias=False, ismagic=True,
354 info = dict(found=True, isalias=False, ismagic=True,
354 namespace = 'IPython internal', obj= lmagic.__wrapped__,
355 namespace = 'IPython internal', obj= lmagic.__wrapped__,
355 parent = None)
356 parent = None)
356 nt.assert_equal(lfind, info)
357 nt.assert_equal(lfind, info)
357
358
358 def test_ofind_cell_magic(self):
359 def test_ofind_cell_magic(self):
359 from IPython.core.magic import register_cell_magic
360 from IPython.core.magic import register_cell_magic
360
361
361 @register_cell_magic
362 @register_cell_magic
362 def cmagic(line, cell):
363 def cmagic(line, cell):
363 "A cell magic"
364 "A cell magic"
364
365
365 # Get info on cell magic
366 # Get info on cell magic
366 find = ip._ofind('cmagic')
367 find = ip._ofind('cmagic')
367 info = dict(found=True, isalias=False, ismagic=True,
368 info = dict(found=True, isalias=False, ismagic=True,
368 namespace = 'IPython internal', obj= cmagic.__wrapped__,
369 namespace = 'IPython internal', obj= cmagic.__wrapped__,
369 parent = None)
370 parent = None)
370 nt.assert_equal(find, info)
371 nt.assert_equal(find, info)
371
372
372 def test_custom_exception(self):
373 def test_custom_exception(self):
373 called = []
374 called = []
374 def my_handler(shell, etype, value, tb, tb_offset=None):
375 def my_handler(shell, etype, value, tb, tb_offset=None):
375 called.append(etype)
376 called.append(etype)
376 shell.showtraceback((etype, value, tb), tb_offset=tb_offset)
377 shell.showtraceback((etype, value, tb), tb_offset=tb_offset)
377
378
378 ip.set_custom_exc((ValueError,), my_handler)
379 ip.set_custom_exc((ValueError,), my_handler)
379 try:
380 try:
380 ip.run_cell("raise ValueError('test')")
381 ip.run_cell("raise ValueError('test')")
381 # Check that this was called, and only once.
382 # Check that this was called, and only once.
382 self.assertEqual(called, [ValueError])
383 self.assertEqual(called, [ValueError])
383 finally:
384 finally:
384 # Reset the custom exception hook
385 # Reset the custom exception hook
385 ip.set_custom_exc((), None)
386 ip.set_custom_exc((), None)
386
387
387
388
388 class TestSafeExecfileNonAsciiPath(unittest.TestCase):
389 class TestSafeExecfileNonAsciiPath(unittest.TestCase):
389
390
390 def setUp(self):
391 def setUp(self):
391 self.BASETESTDIR = tempfile.mkdtemp()
392 self.BASETESTDIR = tempfile.mkdtemp()
392 self.TESTDIR = join(self.BASETESTDIR, u"Γ₯Àâ")
393 self.TESTDIR = join(self.BASETESTDIR, u"Γ₯Àâ")
393 os.mkdir(self.TESTDIR)
394 os.mkdir(self.TESTDIR)
394 with open(join(self.TESTDIR, u"Γ₯Àâtestscript.py"), "w") as sfile:
395 with open(join(self.TESTDIR, u"Γ₯Àâtestscript.py"), "w") as sfile:
395 sfile.write("pass\n")
396 sfile.write("pass\n")
396 self.oldpath = os.getcwdu()
397 self.oldpath = os.getcwdu()
397 os.chdir(self.TESTDIR)
398 os.chdir(self.TESTDIR)
398 self.fname = u"Γ₯Àâtestscript.py"
399 self.fname = u"Γ₯Àâtestscript.py"
399
400
400 def tearDown(self):
401 def tearDown(self):
401 os.chdir(self.oldpath)
402 os.chdir(self.oldpath)
402 shutil.rmtree(self.BASETESTDIR)
403 shutil.rmtree(self.BASETESTDIR)
403
404
404 def test_1(self):
405 def test_1(self):
405 """Test safe_execfile with non-ascii path
406 """Test safe_execfile with non-ascii path
406 """
407 """
407 ip.safe_execfile(self.fname, {}, raise_exceptions=True)
408 ip.safe_execfile(self.fname, {}, raise_exceptions=True)
408
409
409
410
410 class TestSystemRaw(unittest.TestCase):
411 class TestSystemRaw(unittest.TestCase):
411 def test_1(self):
412 def test_1(self):
412 """Test system_raw with non-ascii cmd
413 """Test system_raw with non-ascii cmd
413 """
414 """
414 cmd = ur'''python -c "'Γ₯Àâ'" '''
415 cmd = ur'''python -c "'Γ₯Àâ'" '''
415 ip.system_raw(cmd)
416 ip.system_raw(cmd)
416
417
417 class TestModules(unittest.TestCase, tt.TempFileMixin):
418 class TestModules(unittest.TestCase, tt.TempFileMixin):
418 def test_extraneous_loads(self):
419 def test_extraneous_loads(self):
419 """Test we're not loading modules on startup that we shouldn't.
420 """Test we're not loading modules on startup that we shouldn't.
420 """
421 """
421 self.mktmp("import sys\n"
422 self.mktmp("import sys\n"
422 "print('numpy' in sys.modules)\n"
423 "print('numpy' in sys.modules)\n"
423 "print('IPython.parallel' in sys.modules)\n"
424 "print('IPython.parallel' in sys.modules)\n"
424 "print('IPython.zmq' in sys.modules)\n"
425 "print('IPython.zmq' in sys.modules)\n"
425 )
426 )
426 out = "False\nFalse\nFalse\n"
427 out = "False\nFalse\nFalse\n"
427 tt.ipexec_validate(self.fname, out)
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 def test__IPYTHON__():
557 def test__IPYTHON__():
431 # This shouldn't raise a NameError, that's all
558 # This shouldn't raise a NameError, that's all
432 __IPYTHON__
559 __IPYTHON__
@@ -1,393 +1,393 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 The :class:`~IPython.core.application.Application` object for the command
4 The :class:`~IPython.core.application.Application` object for the command
5 line :command:`ipython` program.
5 line :command:`ipython` program.
6
6
7 Authors
7 Authors
8 -------
8 -------
9
9
10 * Brian Granger
10 * Brian Granger
11 * Fernando Perez
11 * Fernando Perez
12 * Min Ragan-Kelley
12 * Min Ragan-Kelley
13 """
13 """
14
14
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 # Copyright (C) 2008-2011 The IPython Development Team
16 # Copyright (C) 2008-2011 The IPython Development Team
17 #
17 #
18 # Distributed under the terms of the BSD License. The full license is in
18 # Distributed under the terms of the BSD License. The full license is in
19 # the file COPYING, distributed as part of this software.
19 # the file COPYING, distributed as part of this software.
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21
21
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23 # Imports
23 # Imports
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26 from __future__ import absolute_import
26 from __future__ import absolute_import
27
27
28 import logging
28 import logging
29 import os
29 import os
30 import sys
30 import sys
31
31
32 from IPython.config.loader import (
32 from IPython.config.loader import (
33 Config, PyFileConfigLoader, ConfigFileNotFound
33 Config, PyFileConfigLoader, ConfigFileNotFound
34 )
34 )
35 from IPython.config.application import boolean_flag, catch_config_error
35 from IPython.config.application import boolean_flag, catch_config_error
36 from IPython.core import release
36 from IPython.core import release
37 from IPython.core import usage
37 from IPython.core import usage
38 from IPython.core.completer import IPCompleter
38 from IPython.core.completer import IPCompleter
39 from IPython.core.crashhandler import CrashHandler
39 from IPython.core.crashhandler import CrashHandler
40 from IPython.core.formatters import PlainTextFormatter
40 from IPython.core.formatters import PlainTextFormatter
41 from IPython.core.history import HistoryManager
41 from IPython.core.history import HistoryManager
42 from IPython.core.prompts import PromptManager
42 from IPython.core.prompts import PromptManager
43 from IPython.core.application import (
43 from IPython.core.application import (
44 ProfileDir, BaseIPythonApplication, base_flags, base_aliases
44 ProfileDir, BaseIPythonApplication, base_flags, base_aliases
45 )
45 )
46 from IPython.core.magics import ScriptMagics
46 from IPython.core.magics import ScriptMagics
47 from IPython.core.shellapp import (
47 from IPython.core.shellapp import (
48 InteractiveShellApp, shell_flags, shell_aliases
48 InteractiveShellApp, shell_flags, shell_aliases
49 )
49 )
50 from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
50 from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
51 from IPython.lib import inputhook
51 from IPython.lib import inputhook
52 from IPython.utils import warn
52 from IPython.utils import warn
53 from IPython.utils.path import get_ipython_dir, check_for_old_config
53 from IPython.utils.path import get_ipython_dir, check_for_old_config
54 from IPython.utils.traitlets import (
54 from IPython.utils.traitlets import (
55 Bool, List, Dict, CaselessStrEnum
55 Bool, List, Dict, CaselessStrEnum
56 )
56 )
57
57
58 #-----------------------------------------------------------------------------
58 #-----------------------------------------------------------------------------
59 # Globals, utilities and helpers
59 # Globals, utilities and helpers
60 #-----------------------------------------------------------------------------
60 #-----------------------------------------------------------------------------
61
61
62 #: The default config file name for this application.
62 #: The default config file name for this application.
63 default_config_file_name = u'ipython_config.py'
63 default_config_file_name = u'ipython_config.py'
64
64
65 _examples = """
65 _examples = """
66 ipython --pylab # start in pylab mode
66 ipython --pylab # start in pylab mode
67 ipython --pylab=qt # start in pylab mode with the qt4 backend
67 ipython --pylab=qt # start in pylab mode with the qt4 backend
68 ipython --log-level=DEBUG # set logging to DEBUG
68 ipython --log-level=DEBUG # set logging to DEBUG
69 ipython --profile=foo # start with profile foo
69 ipython --profile=foo # start with profile foo
70
70
71 ipython qtconsole # start the qtconsole GUI application
71 ipython qtconsole # start the qtconsole GUI application
72 ipython help qtconsole # show the help for the qtconsole subcmd
72 ipython help qtconsole # show the help for the qtconsole subcmd
73
73
74 ipython console # start the terminal-based console application
74 ipython console # start the terminal-based console application
75 ipython help console # show the help for the console subcmd
75 ipython help console # show the help for the console subcmd
76
76
77 ipython notebook # start the IPython notebook
77 ipython notebook # start the IPython notebook
78 ipython help notebook # show the help for the notebook subcmd
78 ipython help notebook # show the help for the notebook subcmd
79
79
80 ipython profile create foo # create profile foo w/ default config files
80 ipython profile create foo # create profile foo w/ default config files
81 ipython help profile # show the help for the profile subcmd
81 ipython help profile # show the help for the profile subcmd
82
82
83 ipython locate # print the path to the IPython directory
83 ipython locate # print the path to the IPython directory
84 ipython locate profile foo # print the path to the directory for profile `foo`
84 ipython locate profile foo # print the path to the directory for profile `foo`
85 """
85 """
86
86
87 #-----------------------------------------------------------------------------
87 #-----------------------------------------------------------------------------
88 # Crash handler for this application
88 # Crash handler for this application
89 #-----------------------------------------------------------------------------
89 #-----------------------------------------------------------------------------
90
90
91 class IPAppCrashHandler(CrashHandler):
91 class IPAppCrashHandler(CrashHandler):
92 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
92 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
93
93
94 def __init__(self, app):
94 def __init__(self, app):
95 contact_name = release.authors['Fernando'][0]
95 contact_name = release.authors['Fernando'][0]
96 contact_email = release.author_email
96 contact_email = release.author_email
97 bug_tracker = 'https://github.com/ipython/ipython/issues'
97 bug_tracker = 'https://github.com/ipython/ipython/issues'
98 super(IPAppCrashHandler,self).__init__(
98 super(IPAppCrashHandler,self).__init__(
99 app, contact_name, contact_email, bug_tracker
99 app, contact_name, contact_email, bug_tracker
100 )
100 )
101
101
102 def make_report(self,traceback):
102 def make_report(self,traceback):
103 """Return a string containing a crash report."""
103 """Return a string containing a crash report."""
104
104
105 sec_sep = self.section_sep
105 sec_sep = self.section_sep
106 # Start with parent report
106 # Start with parent report
107 report = [super(IPAppCrashHandler, self).make_report(traceback)]
107 report = [super(IPAppCrashHandler, self).make_report(traceback)]
108 # Add interactive-specific info we may have
108 # Add interactive-specific info we may have
109 rpt_add = report.append
109 rpt_add = report.append
110 try:
110 try:
111 rpt_add(sec_sep+"History of session input:")
111 rpt_add(sec_sep+"History of session input:")
112 for line in self.app.shell.user_ns['_ih']:
112 for line in self.app.shell.user_ns['_ih']:
113 rpt_add(line)
113 rpt_add(line)
114 rpt_add('\n*** Last line of input (may not be in above history):\n')
114 rpt_add('\n*** Last line of input (may not be in above history):\n')
115 rpt_add(self.app.shell._last_input_line+'\n')
115 rpt_add(self.app.shell._last_input_line+'\n')
116 except:
116 except:
117 pass
117 pass
118
118
119 return ''.join(report)
119 return ''.join(report)
120
120
121 #-----------------------------------------------------------------------------
121 #-----------------------------------------------------------------------------
122 # Aliases and Flags
122 # Aliases and Flags
123 #-----------------------------------------------------------------------------
123 #-----------------------------------------------------------------------------
124 flags = dict(base_flags)
124 flags = dict(base_flags)
125 flags.update(shell_flags)
125 flags.update(shell_flags)
126 frontend_flags = {}
126 frontend_flags = {}
127 addflag = lambda *args: frontend_flags.update(boolean_flag(*args))
127 addflag = lambda *args: frontend_flags.update(boolean_flag(*args))
128 addflag('autoedit-syntax', 'TerminalInteractiveShell.autoedit_syntax',
128 addflag('autoedit-syntax', 'TerminalInteractiveShell.autoedit_syntax',
129 'Turn on auto editing of files with syntax errors.',
129 'Turn on auto editing of files with syntax errors.',
130 'Turn off auto editing of files with syntax errors.'
130 'Turn off auto editing of files with syntax errors.'
131 )
131 )
132 addflag('banner', 'TerminalIPythonApp.display_banner',
132 addflag('banner', 'TerminalIPythonApp.display_banner',
133 "Display a banner upon starting IPython.",
133 "Display a banner upon starting IPython.",
134 "Don't display a banner upon starting IPython."
134 "Don't display a banner upon starting IPython."
135 )
135 )
136 addflag('confirm-exit', 'TerminalInteractiveShell.confirm_exit',
136 addflag('confirm-exit', 'TerminalInteractiveShell.confirm_exit',
137 """Set to confirm when you try to exit IPython with an EOF (Control-D
137 """Set to confirm when you try to exit IPython with an EOF (Control-D
138 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
138 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
139 you can force a direct exit without any confirmation.""",
139 you can force a direct exit without any confirmation.""",
140 "Don't prompt the user when exiting."
140 "Don't prompt the user when exiting."
141 )
141 )
142 addflag('term-title', 'TerminalInteractiveShell.term_title',
142 addflag('term-title', 'TerminalInteractiveShell.term_title',
143 "Enable auto setting the terminal title.",
143 "Enable auto setting the terminal title.",
144 "Disable auto setting the terminal title."
144 "Disable auto setting the terminal title."
145 )
145 )
146 classic_config = Config()
146 classic_config = Config()
147 classic_config.InteractiveShell.cache_size = 0
147 classic_config.InteractiveShell.cache_size = 0
148 classic_config.PlainTextFormatter.pprint = False
148 classic_config.PlainTextFormatter.pprint = False
149 classic_config.PromptManager.in_template = '>>> '
149 classic_config.PromptManager.in_template = '>>> '
150 classic_config.PromptManager.in2_template = '... '
150 classic_config.PromptManager.in2_template = '... '
151 classic_config.PromptManager.out_template = ''
151 classic_config.PromptManager.out_template = ''
152 classic_config.InteractiveShell.separate_in = ''
152 classic_config.InteractiveShell.separate_in = ''
153 classic_config.InteractiveShell.separate_out = ''
153 classic_config.InteractiveShell.separate_out = ''
154 classic_config.InteractiveShell.separate_out2 = ''
154 classic_config.InteractiveShell.separate_out2 = ''
155 classic_config.InteractiveShell.colors = 'NoColor'
155 classic_config.InteractiveShell.colors = 'NoColor'
156 classic_config.InteractiveShell.xmode = 'Plain'
156 classic_config.InteractiveShell.xmode = 'Plain'
157
157
158 frontend_flags['classic']=(
158 frontend_flags['classic']=(
159 classic_config,
159 classic_config,
160 "Gives IPython a similar feel to the classic Python prompt."
160 "Gives IPython a similar feel to the classic Python prompt."
161 )
161 )
162 # # log doesn't make so much sense this way anymore
162 # # log doesn't make so much sense this way anymore
163 # paa('--log','-l',
163 # paa('--log','-l',
164 # action='store_true', dest='InteractiveShell.logstart',
164 # action='store_true', dest='InteractiveShell.logstart',
165 # help="Start logging to the default log file (./ipython_log.py).")
165 # help="Start logging to the default log file (./ipython_log.py).")
166 #
166 #
167 # # quick is harder to implement
167 # # quick is harder to implement
168 frontend_flags['quick']=(
168 frontend_flags['quick']=(
169 {'TerminalIPythonApp' : {'quick' : True}},
169 {'TerminalIPythonApp' : {'quick' : True}},
170 "Enable quick startup with no config files."
170 "Enable quick startup with no config files."
171 )
171 )
172
172
173 frontend_flags['i'] = (
173 frontend_flags['i'] = (
174 {'TerminalIPythonApp' : {'force_interact' : True}},
174 {'TerminalIPythonApp' : {'force_interact' : True}},
175 """If running code from the command line, become interactive afterwards.
175 """If running code from the command line, become interactive afterwards.
176 Note: can also be given simply as '-i.'"""
176 Note: can also be given simply as '-i.'"""
177 )
177 )
178 flags.update(frontend_flags)
178 flags.update(frontend_flags)
179
179
180 aliases = dict(base_aliases)
180 aliases = dict(base_aliases)
181 aliases.update(shell_aliases)
181 aliases.update(shell_aliases)
182
182
183 #-----------------------------------------------------------------------------
183 #-----------------------------------------------------------------------------
184 # Main classes and functions
184 # Main classes and functions
185 #-----------------------------------------------------------------------------
185 #-----------------------------------------------------------------------------
186
186
187
187
188 class LocateIPythonApp(BaseIPythonApplication):
188 class LocateIPythonApp(BaseIPythonApplication):
189 description = """print the path to the IPython dir"""
189 description = """print the path to the IPython dir"""
190 subcommands = Dict(dict(
190 subcommands = Dict(dict(
191 profile=('IPython.core.profileapp.ProfileLocate',
191 profile=('IPython.core.profileapp.ProfileLocate',
192 "print the path to an IPython profile directory",
192 "print the path to an IPython profile directory",
193 ),
193 ),
194 ))
194 ))
195 def start(self):
195 def start(self):
196 if self.subapp is not None:
196 if self.subapp is not None:
197 return self.subapp.start()
197 return self.subapp.start()
198 else:
198 else:
199 print self.ipython_dir
199 print self.ipython_dir
200
200
201
201
202 class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):
202 class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):
203 name = u'ipython'
203 name = u'ipython'
204 description = usage.cl_usage
204 description = usage.cl_usage
205 default_config_file_name = default_config_file_name
205 default_config_file_name = default_config_file_name
206 crash_handler_class = IPAppCrashHandler
206 crash_handler_class = IPAppCrashHandler
207 examples = _examples
207 examples = _examples
208
208
209 flags = Dict(flags)
209 flags = Dict(flags)
210 aliases = Dict(aliases)
210 aliases = Dict(aliases)
211 classes = List()
211 classes = List()
212 def _classes_default(self):
212 def _classes_default(self):
213 """This has to be in a method, for TerminalIPythonApp to be available."""
213 """This has to be in a method, for TerminalIPythonApp to be available."""
214 return [
214 return [
215 InteractiveShellApp, # ShellApp comes before TerminalApp, because
215 InteractiveShellApp, # ShellApp comes before TerminalApp, because
216 self.__class__, # it will also affect subclasses (e.g. QtConsole)
216 self.__class__, # it will also affect subclasses (e.g. QtConsole)
217 TerminalInteractiveShell,
217 TerminalInteractiveShell,
218 PromptManager,
218 PromptManager,
219 HistoryManager,
219 HistoryManager,
220 ProfileDir,
220 ProfileDir,
221 PlainTextFormatter,
221 PlainTextFormatter,
222 IPCompleter,
222 IPCompleter,
223 ScriptMagics,
223 ScriptMagics,
224 ]
224 ]
225
225
226 subcommands = Dict(dict(
226 subcommands = Dict(dict(
227 qtconsole=('IPython.frontend.qt.console.qtconsoleapp.IPythonQtConsoleApp',
227 qtconsole=('IPython.frontend.qt.console.qtconsoleapp.IPythonQtConsoleApp',
228 """Launch the IPython Qt Console."""
228 """Launch the IPython Qt Console."""
229 ),
229 ),
230 notebook=('IPython.frontend.html.notebook.notebookapp.NotebookApp',
230 notebook=('IPython.frontend.html.notebook.notebookapp.NotebookApp',
231 """Launch the IPython HTML Notebook Server."""
231 """Launch the IPython HTML Notebook Server."""
232 ),
232 ),
233 profile = ("IPython.core.profileapp.ProfileApp",
233 profile = ("IPython.core.profileapp.ProfileApp",
234 "Create and manage IPython profiles."
234 "Create and manage IPython profiles."
235 ),
235 ),
236 kernel = ("IPython.zmq.ipkernel.IPKernelApp",
236 kernel = ("IPython.zmq.ipkernel.IPKernelApp",
237 "Start a kernel without an attached frontend."
237 "Start a kernel without an attached frontend."
238 ),
238 ),
239 console=('IPython.frontend.terminal.console.app.ZMQTerminalIPythonApp',
239 console=('IPython.frontend.terminal.console.app.ZMQTerminalIPythonApp',
240 """Launch the IPython terminal-based Console."""
240 """Launch the IPython terminal-based Console."""
241 ),
241 ),
242 locate=('IPython.frontend.terminal.ipapp.LocateIPythonApp',
242 locate=('IPython.frontend.terminal.ipapp.LocateIPythonApp',
243 LocateIPythonApp.description
243 LocateIPythonApp.description
244 ),
244 ),
245 ))
245 ))
246
246
247 # *do* autocreate requested profile, but don't create the config file.
247 # *do* autocreate requested profile, but don't create the config file.
248 auto_create=Bool(True)
248 auto_create=Bool(True)
249 # configurables
249 # configurables
250 ignore_old_config=Bool(False, config=True,
250 ignore_old_config=Bool(False, config=True,
251 help="Suppress warning messages about legacy config files"
251 help="Suppress warning messages about legacy config files"
252 )
252 )
253 quick = Bool(False, config=True,
253 quick = Bool(False, config=True,
254 help="""Start IPython quickly by skipping the loading of config files."""
254 help="""Start IPython quickly by skipping the loading of config files."""
255 )
255 )
256 def _quick_changed(self, name, old, new):
256 def _quick_changed(self, name, old, new):
257 if new:
257 if new:
258 self.load_config_file = lambda *a, **kw: None
258 self.load_config_file = lambda *a, **kw: None
259 self.ignore_old_config=True
259 self.ignore_old_config=True
260
260
261 display_banner = Bool(True, config=True,
261 display_banner = Bool(True, config=True,
262 help="Whether to display a banner upon starting IPython."
262 help="Whether to display a banner upon starting IPython."
263 )
263 )
264
264
265 # if there is code of files to run from the cmd line, don't interact
265 # if there is code of files to run from the cmd line, don't interact
266 # unless the --i flag (App.force_interact) is true.
266 # unless the --i flag (App.force_interact) is true.
267 force_interact = Bool(False, config=True,
267 force_interact = Bool(False, config=True,
268 help="""If a command or file is given via the command-line,
268 help="""If a command or file is given via the command-line,
269 e.g. 'ipython foo.py"""
269 e.g. 'ipython foo.py"""
270 )
270 )
271 def _force_interact_changed(self, name, old, new):
271 def _force_interact_changed(self, name, old, new):
272 if new:
272 if new:
273 self.interact = True
273 self.interact = True
274
274
275 def _file_to_run_changed(self, name, old, new):
275 def _file_to_run_changed(self, name, old, new):
276 if new:
276 if new:
277 self.something_to_run = True
277 self.something_to_run = True
278 if new and not self.force_interact:
278 if new and not self.force_interact:
279 self.interact = False
279 self.interact = False
280 _code_to_run_changed = _file_to_run_changed
280 _code_to_run_changed = _file_to_run_changed
281 _module_to_run_changed = _file_to_run_changed
281 _module_to_run_changed = _file_to_run_changed
282
282
283 # internal, not-configurable
283 # internal, not-configurable
284 interact=Bool(True)
284 interact=Bool(True)
285 something_to_run=Bool(False)
285 something_to_run=Bool(False)
286
286
287 def parse_command_line(self, argv=None):
287 def parse_command_line(self, argv=None):
288 """override to allow old '-pylab' flag with deprecation warning"""
288 """override to allow old '-pylab' flag with deprecation warning"""
289
289
290 argv = sys.argv[1:] if argv is None else argv
290 argv = sys.argv[1:] if argv is None else argv
291
291
292 if '-pylab' in argv:
292 if '-pylab' in argv:
293 # deprecated `-pylab` given,
293 # deprecated `-pylab` given,
294 # warn and transform into current syntax
294 # warn and transform into current syntax
295 argv = argv[:] # copy, don't clobber
295 argv = argv[:] # copy, don't clobber
296 idx = argv.index('-pylab')
296 idx = argv.index('-pylab')
297 warn.warn("`-pylab` flag has been deprecated.\n"
297 warn.warn("`-pylab` flag has been deprecated.\n"
298 " Use `--pylab` instead, or `--pylab=foo` to specify a backend.")
298 " Use `--pylab` instead, or `--pylab=foo` to specify a backend.")
299 sub = '--pylab'
299 sub = '--pylab'
300 if len(argv) > idx+1:
300 if len(argv) > idx+1:
301 # check for gui arg, as in '-pylab qt'
301 # check for gui arg, as in '-pylab qt'
302 gui = argv[idx+1]
302 gui = argv[idx+1]
303 if gui in ('wx', 'qt', 'qt4', 'gtk', 'auto'):
303 if gui in ('wx', 'qt', 'qt4', 'gtk', 'auto'):
304 sub = '--pylab='+gui
304 sub = '--pylab='+gui
305 argv.pop(idx+1)
305 argv.pop(idx+1)
306 argv[idx] = sub
306 argv[idx] = sub
307
307
308 return super(TerminalIPythonApp, self).parse_command_line(argv)
308 return super(TerminalIPythonApp, self).parse_command_line(argv)
309
309
310 @catch_config_error
310 @catch_config_error
311 def initialize(self, argv=None):
311 def initialize(self, argv=None):
312 """Do actions after construct, but before starting the app."""
312 """Do actions after construct, but before starting the app."""
313 super(TerminalIPythonApp, self).initialize(argv)
313 super(TerminalIPythonApp, self).initialize(argv)
314 if self.subapp is not None:
314 if self.subapp is not None:
315 # don't bother initializing further, starting subapp
315 # don't bother initializing further, starting subapp
316 return
316 return
317 if not self.ignore_old_config:
317 if not self.ignore_old_config:
318 check_for_old_config(self.ipython_dir)
318 check_for_old_config(self.ipython_dir)
319 # print self.extra_args
319 # print self.extra_args
320 if self.extra_args and not self.something_to_run:
320 if self.extra_args and not self.something_to_run:
321 self.file_to_run = self.extra_args[0]
321 self.file_to_run = self.extra_args[0]
322 self.init_path()
322 self.init_path()
323 # create the shell
323 # create the shell
324 self.init_shell()
324 self.init_shell()
325 # and draw the banner
325 # and draw the banner
326 self.init_banner()
326 self.init_banner()
327 # Now a variety of things that happen after the banner is printed.
327 # Now a variety of things that happen after the banner is printed.
328 self.init_gui_pylab()
328 self.init_gui_pylab()
329 self.init_extensions()
329 self.init_extensions()
330 self.init_code()
330 self.init_code()
331
331
332 def init_shell(self):
332 def init_shell(self):
333 """initialize the InteractiveShell instance"""
333 """initialize the InteractiveShell instance"""
334 # Create an InteractiveShell instance.
334 # Create an InteractiveShell instance.
335 # shell.display_banner should always be False for the terminal
335 # shell.display_banner should always be False for the terminal
336 # based app, because we call shell.show_banner() by hand below
336 # based app, because we call shell.show_banner() by hand below
337 # so the banner shows *before* all extension loading stuff.
337 # so the banner shows *before* all extension loading stuff.
338 self.shell = TerminalInteractiveShell.instance(config=self.config,
338 self.shell = TerminalInteractiveShell.instance(config=self.config,
339 display_banner=False, profile_dir=self.profile_dir,
339 display_banner=False, profile_dir=self.profile_dir,
340 ipython_dir=self.ipython_dir)
340 ipython_dir=self.ipython_dir)
341 self.shell.configurables.append(self)
341 self.shell.configurables.append(self)
342
342
343 def init_banner(self):
343 def init_banner(self):
344 """optionally display the banner"""
344 """optionally display the banner"""
345 if self.display_banner and self.interact:
345 if self.display_banner and self.interact:
346 self.shell.show_banner()
346 self.shell.show_banner()
347 # Make sure there is a space below the banner.
347 # Make sure there is a space below the banner.
348 if self.log_level <= logging.INFO: print
348 if self.log_level <= logging.INFO: print
349
349
350 def _pylab_changed(self, name, old, new):
350 def _pylab_changed(self, name, old, new):
351 """Replace --pylab='inline' with --pylab='auto'"""
351 """Replace --pylab='inline' with --pylab='auto'"""
352 if new == 'inline':
352 if new == 'inline':
353 warn.warn("'inline' not available as pylab backend, "
353 warn.warn("'inline' not available as pylab backend, "
354 "using 'auto' instead.\n")
354 "using 'auto' instead.")
355 self.pylab = 'auto'
355 self.pylab = 'auto'
356
356
357 def start(self):
357 def start(self):
358 if self.subapp is not None:
358 if self.subapp is not None:
359 return self.subapp.start()
359 return self.subapp.start()
360 # perform any prexec steps:
360 # perform any prexec steps:
361 if self.interact:
361 if self.interact:
362 self.log.debug("Starting IPython's mainloop...")
362 self.log.debug("Starting IPython's mainloop...")
363 self.shell.mainloop()
363 self.shell.mainloop()
364 else:
364 else:
365 self.log.debug("IPython not interactive...")
365 self.log.debug("IPython not interactive...")
366
366
367
367
368 def load_default_config(ipython_dir=None):
368 def load_default_config(ipython_dir=None):
369 """Load the default config file from the default ipython_dir.
369 """Load the default config file from the default ipython_dir.
370
370
371 This is useful for embedded shells.
371 This is useful for embedded shells.
372 """
372 """
373 if ipython_dir is None:
373 if ipython_dir is None:
374 ipython_dir = get_ipython_dir()
374 ipython_dir = get_ipython_dir()
375 profile_dir = os.path.join(ipython_dir, 'profile_default')
375 profile_dir = os.path.join(ipython_dir, 'profile_default')
376 cl = PyFileConfigLoader(default_config_file_name, profile_dir)
376 cl = PyFileConfigLoader(default_config_file_name, profile_dir)
377 try:
377 try:
378 config = cl.load_config()
378 config = cl.load_config()
379 except ConfigFileNotFound:
379 except ConfigFileNotFound:
380 # no config found
380 # no config found
381 config = Config()
381 config = Config()
382 return config
382 return config
383
383
384
384
385 def launch_new_instance():
385 def launch_new_instance():
386 """Create and run a full blown IPython instance"""
386 """Create and run a full blown IPython instance"""
387 app = TerminalIPythonApp.instance()
387 app = TerminalIPythonApp.instance()
388 app.initialize()
388 app.initialize()
389 app.start()
389 app.start()
390
390
391
391
392 if __name__ == '__main__':
392 if __name__ == '__main__':
393 launch_new_instance()
393 launch_new_instance()
@@ -1,529 +1,529 b''
1 # coding: utf-8
1 # coding: utf-8
2 """
2 """
3 Inputhook management for GUI event loop integration.
3 Inputhook management for GUI event loop integration.
4 """
4 """
5
5
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (C) 2008-2011 The IPython Development Team
7 # Copyright (C) 2008-2011 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 try:
17 try:
18 import ctypes
18 import ctypes
19 except ImportError:
19 except ImportError:
20 ctypes = None
20 ctypes = None
21 import os
21 import os
22 import sys
22 import sys
23 from distutils.version import LooseVersion as V
23 from distutils.version import LooseVersion as V
24
24
25 from IPython.utils.warn import warn
25 from IPython.utils.warn import warn
26
26
27 #-----------------------------------------------------------------------------
27 #-----------------------------------------------------------------------------
28 # Constants
28 # Constants
29 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
30
30
31 # Constants for identifying the GUI toolkits.
31 # Constants for identifying the GUI toolkits.
32 GUI_WX = 'wx'
32 GUI_WX = 'wx'
33 GUI_QT = 'qt'
33 GUI_QT = 'qt'
34 GUI_QT4 = 'qt4'
34 GUI_QT4 = 'qt4'
35 GUI_GTK = 'gtk'
35 GUI_GTK = 'gtk'
36 GUI_TK = 'tk'
36 GUI_TK = 'tk'
37 GUI_OSX = 'osx'
37 GUI_OSX = 'osx'
38 GUI_GLUT = 'glut'
38 GUI_GLUT = 'glut'
39 GUI_PYGLET = 'pyglet'
39 GUI_PYGLET = 'pyglet'
40 GUI_GTK3 = 'gtk3'
40 GUI_GTK3 = 'gtk3'
41 GUI_NONE = 'none' # i.e. disable
41 GUI_NONE = 'none' # i.e. disable
42
42
43 #-----------------------------------------------------------------------------
43 #-----------------------------------------------------------------------------
44 # Utilities
44 # Utilities
45 #-----------------------------------------------------------------------------
45 #-----------------------------------------------------------------------------
46
46
47 def _stdin_ready_posix():
47 def _stdin_ready_posix():
48 """Return True if there's something to read on stdin (posix version)."""
48 """Return True if there's something to read on stdin (posix version)."""
49 infds, outfds, erfds = select.select([sys.stdin],[],[],0)
49 infds, outfds, erfds = select.select([sys.stdin],[],[],0)
50 return bool(infds)
50 return bool(infds)
51
51
52 def _stdin_ready_nt():
52 def _stdin_ready_nt():
53 """Return True if there's something to read on stdin (nt version)."""
53 """Return True if there's something to read on stdin (nt version)."""
54 return msvcrt.kbhit()
54 return msvcrt.kbhit()
55
55
56 def _stdin_ready_other():
56 def _stdin_ready_other():
57 """Return True, assuming there's something to read on stdin."""
57 """Return True, assuming there's something to read on stdin."""
58 return True #
58 return True #
59
59
60
60
61 def _ignore_CTRL_C_posix():
61 def _ignore_CTRL_C_posix():
62 """Ignore CTRL+C (SIGINT)."""
62 """Ignore CTRL+C (SIGINT)."""
63 signal.signal(signal.SIGINT, signal.SIG_IGN)
63 signal.signal(signal.SIGINT, signal.SIG_IGN)
64
64
65 def _allow_CTRL_C_posix():
65 def _allow_CTRL_C_posix():
66 """Take CTRL+C into account (SIGINT)."""
66 """Take CTRL+C into account (SIGINT)."""
67 signal.signal(signal.SIGINT, signal.default_int_handler)
67 signal.signal(signal.SIGINT, signal.default_int_handler)
68
68
69 def _ignore_CTRL_C_other():
69 def _ignore_CTRL_C_other():
70 """Ignore CTRL+C (not implemented)."""
70 """Ignore CTRL+C (not implemented)."""
71 pass
71 pass
72
72
73 def _allow_CTRL_C_other():
73 def _allow_CTRL_C_other():
74 """Take CTRL+C into account (not implemented)."""
74 """Take CTRL+C into account (not implemented)."""
75 pass
75 pass
76
76
77 if os.name == 'posix':
77 if os.name == 'posix':
78 import select
78 import select
79 import signal
79 import signal
80 stdin_ready = _stdin_ready_posix
80 stdin_ready = _stdin_ready_posix
81 ignore_CTRL_C = _ignore_CTRL_C_posix
81 ignore_CTRL_C = _ignore_CTRL_C_posix
82 allow_CTRL_C = _allow_CTRL_C_posix
82 allow_CTRL_C = _allow_CTRL_C_posix
83 elif os.name == 'nt':
83 elif os.name == 'nt':
84 import msvcrt
84 import msvcrt
85 stdin_ready = _stdin_ready_nt
85 stdin_ready = _stdin_ready_nt
86 ignore_CTRL_C = _ignore_CTRL_C_other
86 ignore_CTRL_C = _ignore_CTRL_C_other
87 allow_CTRL_C = _allow_CTRL_C_other
87 allow_CTRL_C = _allow_CTRL_C_other
88 else:
88 else:
89 stdin_ready = _stdin_ready_other
89 stdin_ready = _stdin_ready_other
90 ignore_CTRL_C = _ignore_CTRL_C_other
90 ignore_CTRL_C = _ignore_CTRL_C_other
91 allow_CTRL_C = _allow_CTRL_C_other
91 allow_CTRL_C = _allow_CTRL_C_other
92
92
93
93
94 #-----------------------------------------------------------------------------
94 #-----------------------------------------------------------------------------
95 # Main InputHookManager class
95 # Main InputHookManager class
96 #-----------------------------------------------------------------------------
96 #-----------------------------------------------------------------------------
97
97
98
98
99 class InputHookManager(object):
99 class InputHookManager(object):
100 """Manage PyOS_InputHook for different GUI toolkits.
100 """Manage PyOS_InputHook for different GUI toolkits.
101
101
102 This class installs various hooks under ``PyOSInputHook`` to handle
102 This class installs various hooks under ``PyOSInputHook`` to handle
103 GUI event loop integration.
103 GUI event loop integration.
104 """
104 """
105
105
106 def __init__(self):
106 def __init__(self):
107 if ctypes is None:
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 return
109 return
110 self.PYFUNC = ctypes.PYFUNCTYPE(ctypes.c_int)
110 self.PYFUNC = ctypes.PYFUNCTYPE(ctypes.c_int)
111 self._apps = {}
111 self._apps = {}
112 self._reset()
112 self._reset()
113
113
114 def _reset(self):
114 def _reset(self):
115 self._callback_pyfunctype = None
115 self._callback_pyfunctype = None
116 self._callback = None
116 self._callback = None
117 self._installed = False
117 self._installed = False
118 self._current_gui = None
118 self._current_gui = None
119
119
120 def get_pyos_inputhook(self):
120 def get_pyos_inputhook(self):
121 """Return the current PyOS_InputHook as a ctypes.c_void_p."""
121 """Return the current PyOS_InputHook as a ctypes.c_void_p."""
122 return ctypes.c_void_p.in_dll(ctypes.pythonapi,"PyOS_InputHook")
122 return ctypes.c_void_p.in_dll(ctypes.pythonapi,"PyOS_InputHook")
123
123
124 def get_pyos_inputhook_as_func(self):
124 def get_pyos_inputhook_as_func(self):
125 """Return the current PyOS_InputHook as a ctypes.PYFUNCYPE."""
125 """Return the current PyOS_InputHook as a ctypes.PYFUNCYPE."""
126 return self.PYFUNC.in_dll(ctypes.pythonapi,"PyOS_InputHook")
126 return self.PYFUNC.in_dll(ctypes.pythonapi,"PyOS_InputHook")
127
127
128 def set_inputhook(self, callback):
128 def set_inputhook(self, callback):
129 """Set PyOS_InputHook to callback and return the previous one."""
129 """Set PyOS_InputHook to callback and return the previous one."""
130 # On platforms with 'readline' support, it's all too likely to
130 # On platforms with 'readline' support, it's all too likely to
131 # have a KeyboardInterrupt signal delivered *even before* an
131 # have a KeyboardInterrupt signal delivered *even before* an
132 # initial ``try:`` clause in the callback can be executed, so
132 # initial ``try:`` clause in the callback can be executed, so
133 # we need to disable CTRL+C in this situation.
133 # we need to disable CTRL+C in this situation.
134 ignore_CTRL_C()
134 ignore_CTRL_C()
135 self._callback = callback
135 self._callback = callback
136 self._callback_pyfunctype = self.PYFUNC(callback)
136 self._callback_pyfunctype = self.PYFUNC(callback)
137 pyos_inputhook_ptr = self.get_pyos_inputhook()
137 pyos_inputhook_ptr = self.get_pyos_inputhook()
138 original = self.get_pyos_inputhook_as_func()
138 original = self.get_pyos_inputhook_as_func()
139 pyos_inputhook_ptr.value = \
139 pyos_inputhook_ptr.value = \
140 ctypes.cast(self._callback_pyfunctype, ctypes.c_void_p).value
140 ctypes.cast(self._callback_pyfunctype, ctypes.c_void_p).value
141 self._installed = True
141 self._installed = True
142 return original
142 return original
143
143
144 def clear_inputhook(self, app=None):
144 def clear_inputhook(self, app=None):
145 """Set PyOS_InputHook to NULL and return the previous one.
145 """Set PyOS_InputHook to NULL and return the previous one.
146
146
147 Parameters
147 Parameters
148 ----------
148 ----------
149 app : optional, ignored
149 app : optional, ignored
150 This parameter is allowed only so that clear_inputhook() can be
150 This parameter is allowed only so that clear_inputhook() can be
151 called with a similar interface as all the ``enable_*`` methods. But
151 called with a similar interface as all the ``enable_*`` methods. But
152 the actual value of the parameter is ignored. This uniform interface
152 the actual value of the parameter is ignored. This uniform interface
153 makes it easier to have user-level entry points in the main IPython
153 makes it easier to have user-level entry points in the main IPython
154 app like :meth:`enable_gui`."""
154 app like :meth:`enable_gui`."""
155 pyos_inputhook_ptr = self.get_pyos_inputhook()
155 pyos_inputhook_ptr = self.get_pyos_inputhook()
156 original = self.get_pyos_inputhook_as_func()
156 original = self.get_pyos_inputhook_as_func()
157 pyos_inputhook_ptr.value = ctypes.c_void_p(None).value
157 pyos_inputhook_ptr.value = ctypes.c_void_p(None).value
158 allow_CTRL_C()
158 allow_CTRL_C()
159 self._reset()
159 self._reset()
160 return original
160 return original
161
161
162 def clear_app_refs(self, gui=None):
162 def clear_app_refs(self, gui=None):
163 """Clear IPython's internal reference to an application instance.
163 """Clear IPython's internal reference to an application instance.
164
164
165 Whenever we create an app for a user on qt4 or wx, we hold a
165 Whenever we create an app for a user on qt4 or wx, we hold a
166 reference to the app. This is needed because in some cases bad things
166 reference to the app. This is needed because in some cases bad things
167 can happen if a user doesn't hold a reference themselves. This
167 can happen if a user doesn't hold a reference themselves. This
168 method is provided to clear the references we are holding.
168 method is provided to clear the references we are holding.
169
169
170 Parameters
170 Parameters
171 ----------
171 ----------
172 gui : None or str
172 gui : None or str
173 If None, clear all app references. If ('wx', 'qt4') clear
173 If None, clear all app references. If ('wx', 'qt4') clear
174 the app for that toolkit. References are not held for gtk or tk
174 the app for that toolkit. References are not held for gtk or tk
175 as those toolkits don't have the notion of an app.
175 as those toolkits don't have the notion of an app.
176 """
176 """
177 if gui is None:
177 if gui is None:
178 self._apps = {}
178 self._apps = {}
179 elif gui in self._apps:
179 elif gui in self._apps:
180 del self._apps[gui]
180 del self._apps[gui]
181
181
182 def enable_wx(self, app=None):
182 def enable_wx(self, app=None):
183 """Enable event loop integration with wxPython.
183 """Enable event loop integration with wxPython.
184
184
185 Parameters
185 Parameters
186 ----------
186 ----------
187 app : WX Application, optional.
187 app : WX Application, optional.
188 Running application to use. If not given, we probe WX for an
188 Running application to use. If not given, we probe WX for an
189 existing application object, and create a new one if none is found.
189 existing application object, and create a new one if none is found.
190
190
191 Notes
191 Notes
192 -----
192 -----
193 This methods sets the ``PyOS_InputHook`` for wxPython, which allows
193 This methods sets the ``PyOS_InputHook`` for wxPython, which allows
194 the wxPython to integrate with terminal based applications like
194 the wxPython to integrate with terminal based applications like
195 IPython.
195 IPython.
196
196
197 If ``app`` is not given we probe for an existing one, and return it if
197 If ``app`` is not given we probe for an existing one, and return it if
198 found. If no existing app is found, we create an :class:`wx.App` as
198 found. If no existing app is found, we create an :class:`wx.App` as
199 follows::
199 follows::
200
200
201 import wx
201 import wx
202 app = wx.App(redirect=False, clearSigInt=False)
202 app = wx.App(redirect=False, clearSigInt=False)
203 """
203 """
204 import wx
204 import wx
205
205
206 wx_version = V(wx.__version__).version
206 wx_version = V(wx.__version__).version
207
207
208 if wx_version < [2, 8]:
208 if wx_version < [2, 8]:
209 raise ValueError("requires wxPython >= 2.8, but you have %s" % wx.__version__)
209 raise ValueError("requires wxPython >= 2.8, but you have %s" % wx.__version__)
210
210
211 from IPython.lib.inputhookwx import inputhook_wx
211 from IPython.lib.inputhookwx import inputhook_wx
212 self.set_inputhook(inputhook_wx)
212 self.set_inputhook(inputhook_wx)
213 self._current_gui = GUI_WX
213 self._current_gui = GUI_WX
214 import wx
214 import wx
215 if app is None:
215 if app is None:
216 app = wx.GetApp()
216 app = wx.GetApp()
217 if app is None:
217 if app is None:
218 app = wx.App(redirect=False, clearSigInt=False)
218 app = wx.App(redirect=False, clearSigInt=False)
219 app._in_event_loop = True
219 app._in_event_loop = True
220 self._apps[GUI_WX] = app
220 self._apps[GUI_WX] = app
221 return app
221 return app
222
222
223 def disable_wx(self):
223 def disable_wx(self):
224 """Disable event loop integration with wxPython.
224 """Disable event loop integration with wxPython.
225
225
226 This merely sets PyOS_InputHook to NULL.
226 This merely sets PyOS_InputHook to NULL.
227 """
227 """
228 if GUI_WX in self._apps:
228 if GUI_WX in self._apps:
229 self._apps[GUI_WX]._in_event_loop = False
229 self._apps[GUI_WX]._in_event_loop = False
230 self.clear_inputhook()
230 self.clear_inputhook()
231
231
232 def enable_qt4(self, app=None):
232 def enable_qt4(self, app=None):
233 """Enable event loop integration with PyQt4.
233 """Enable event loop integration with PyQt4.
234
234
235 Parameters
235 Parameters
236 ----------
236 ----------
237 app : Qt Application, optional.
237 app : Qt Application, optional.
238 Running application to use. If not given, we probe Qt for an
238 Running application to use. If not given, we probe Qt for an
239 existing application object, and create a new one if none is found.
239 existing application object, and create a new one if none is found.
240
240
241 Notes
241 Notes
242 -----
242 -----
243 This methods sets the PyOS_InputHook for PyQt4, which allows
243 This methods sets the PyOS_InputHook for PyQt4, which allows
244 the PyQt4 to integrate with terminal based applications like
244 the PyQt4 to integrate with terminal based applications like
245 IPython.
245 IPython.
246
246
247 If ``app`` is not given we probe for an existing one, and return it if
247 If ``app`` is not given we probe for an existing one, and return it if
248 found. If no existing app is found, we create an :class:`QApplication`
248 found. If no existing app is found, we create an :class:`QApplication`
249 as follows::
249 as follows::
250
250
251 from PyQt4 import QtCore
251 from PyQt4 import QtCore
252 app = QtGui.QApplication(sys.argv)
252 app = QtGui.QApplication(sys.argv)
253 """
253 """
254 from IPython.lib.inputhookqt4 import create_inputhook_qt4
254 from IPython.lib.inputhookqt4 import create_inputhook_qt4
255 app, inputhook_qt4 = create_inputhook_qt4(self, app)
255 app, inputhook_qt4 = create_inputhook_qt4(self, app)
256 self.set_inputhook(inputhook_qt4)
256 self.set_inputhook(inputhook_qt4)
257
257
258 self._current_gui = GUI_QT4
258 self._current_gui = GUI_QT4
259 app._in_event_loop = True
259 app._in_event_loop = True
260 self._apps[GUI_QT4] = app
260 self._apps[GUI_QT4] = app
261 return app
261 return app
262
262
263 def disable_qt4(self):
263 def disable_qt4(self):
264 """Disable event loop integration with PyQt4.
264 """Disable event loop integration with PyQt4.
265
265
266 This merely sets PyOS_InputHook to NULL.
266 This merely sets PyOS_InputHook to NULL.
267 """
267 """
268 if GUI_QT4 in self._apps:
268 if GUI_QT4 in self._apps:
269 self._apps[GUI_QT4]._in_event_loop = False
269 self._apps[GUI_QT4]._in_event_loop = False
270 self.clear_inputhook()
270 self.clear_inputhook()
271
271
272 def enable_gtk(self, app=None):
272 def enable_gtk(self, app=None):
273 """Enable event loop integration with PyGTK.
273 """Enable event loop integration with PyGTK.
274
274
275 Parameters
275 Parameters
276 ----------
276 ----------
277 app : ignored
277 app : ignored
278 Ignored, it's only a placeholder to keep the call signature of all
278 Ignored, it's only a placeholder to keep the call signature of all
279 gui activation methods consistent, which simplifies the logic of
279 gui activation methods consistent, which simplifies the logic of
280 supporting magics.
280 supporting magics.
281
281
282 Notes
282 Notes
283 -----
283 -----
284 This methods sets the PyOS_InputHook for PyGTK, which allows
284 This methods sets the PyOS_InputHook for PyGTK, which allows
285 the PyGTK to integrate with terminal based applications like
285 the PyGTK to integrate with terminal based applications like
286 IPython.
286 IPython.
287 """
287 """
288 import gtk
288 import gtk
289 try:
289 try:
290 gtk.set_interactive(True)
290 gtk.set_interactive(True)
291 self._current_gui = GUI_GTK
291 self._current_gui = GUI_GTK
292 except AttributeError:
292 except AttributeError:
293 # For older versions of gtk, use our own ctypes version
293 # For older versions of gtk, use our own ctypes version
294 from IPython.lib.inputhookgtk import inputhook_gtk
294 from IPython.lib.inputhookgtk import inputhook_gtk
295 self.set_inputhook(inputhook_gtk)
295 self.set_inputhook(inputhook_gtk)
296 self._current_gui = GUI_GTK
296 self._current_gui = GUI_GTK
297
297
298 def disable_gtk(self):
298 def disable_gtk(self):
299 """Disable event loop integration with PyGTK.
299 """Disable event loop integration with PyGTK.
300
300
301 This merely sets PyOS_InputHook to NULL.
301 This merely sets PyOS_InputHook to NULL.
302 """
302 """
303 self.clear_inputhook()
303 self.clear_inputhook()
304
304
305 def enable_tk(self, app=None):
305 def enable_tk(self, app=None):
306 """Enable event loop integration with Tk.
306 """Enable event loop integration with Tk.
307
307
308 Parameters
308 Parameters
309 ----------
309 ----------
310 app : toplevel :class:`Tkinter.Tk` widget, optional.
310 app : toplevel :class:`Tkinter.Tk` widget, optional.
311 Running toplevel widget to use. If not given, we probe Tk for an
311 Running toplevel widget to use. If not given, we probe Tk for an
312 existing one, and create a new one if none is found.
312 existing one, and create a new one if none is found.
313
313
314 Notes
314 Notes
315 -----
315 -----
316 If you have already created a :class:`Tkinter.Tk` object, the only
316 If you have already created a :class:`Tkinter.Tk` object, the only
317 thing done by this method is to register with the
317 thing done by this method is to register with the
318 :class:`InputHookManager`, since creating that object automatically
318 :class:`InputHookManager`, since creating that object automatically
319 sets ``PyOS_InputHook``.
319 sets ``PyOS_InputHook``.
320 """
320 """
321 self._current_gui = GUI_TK
321 self._current_gui = GUI_TK
322 if app is None:
322 if app is None:
323 import Tkinter
323 import Tkinter
324 app = Tkinter.Tk()
324 app = Tkinter.Tk()
325 app.withdraw()
325 app.withdraw()
326 self._apps[GUI_TK] = app
326 self._apps[GUI_TK] = app
327 return app
327 return app
328
328
329 def disable_tk(self):
329 def disable_tk(self):
330 """Disable event loop integration with Tkinter.
330 """Disable event loop integration with Tkinter.
331
331
332 This merely sets PyOS_InputHook to NULL.
332 This merely sets PyOS_InputHook to NULL.
333 """
333 """
334 self.clear_inputhook()
334 self.clear_inputhook()
335
335
336
336
337 def enable_glut(self, app=None):
337 def enable_glut(self, app=None):
338 """ Enable event loop integration with GLUT.
338 """ Enable event loop integration with GLUT.
339
339
340 Parameters
340 Parameters
341 ----------
341 ----------
342
342
343 app : ignored
343 app : ignored
344 Ignored, it's only a placeholder to keep the call signature of all
344 Ignored, it's only a placeholder to keep the call signature of all
345 gui activation methods consistent, which simplifies the logic of
345 gui activation methods consistent, which simplifies the logic of
346 supporting magics.
346 supporting magics.
347
347
348 Notes
348 Notes
349 -----
349 -----
350
350
351 This methods sets the PyOS_InputHook for GLUT, which allows the GLUT to
351 This methods sets the PyOS_InputHook for GLUT, which allows the GLUT to
352 integrate with terminal based applications like IPython. Due to GLUT
352 integrate with terminal based applications like IPython. Due to GLUT
353 limitations, it is currently not possible to start the event loop
353 limitations, it is currently not possible to start the event loop
354 without first creating a window. You should thus not create another
354 without first creating a window. You should thus not create another
355 window but use instead the created one. See 'gui-glut.py' in the
355 window but use instead the created one. See 'gui-glut.py' in the
356 docs/examples/lib directory.
356 docs/examples/lib directory.
357
357
358 The default screen mode is set to:
358 The default screen mode is set to:
359 glut.GLUT_DOUBLE | glut.GLUT_RGBA | glut.GLUT_DEPTH
359 glut.GLUT_DOUBLE | glut.GLUT_RGBA | glut.GLUT_DEPTH
360 """
360 """
361
361
362 import OpenGL.GLUT as glut
362 import OpenGL.GLUT as glut
363 from IPython.lib.inputhookglut import glut_display_mode, \
363 from IPython.lib.inputhookglut import glut_display_mode, \
364 glut_close, glut_display, \
364 glut_close, glut_display, \
365 glut_idle, inputhook_glut
365 glut_idle, inputhook_glut
366
366
367 if GUI_GLUT not in self._apps:
367 if GUI_GLUT not in self._apps:
368 glut.glutInit( sys.argv )
368 glut.glutInit( sys.argv )
369 glut.glutInitDisplayMode( glut_display_mode )
369 glut.glutInitDisplayMode( glut_display_mode )
370 # This is specific to freeglut
370 # This is specific to freeglut
371 if bool(glut.glutSetOption):
371 if bool(glut.glutSetOption):
372 glut.glutSetOption( glut.GLUT_ACTION_ON_WINDOW_CLOSE,
372 glut.glutSetOption( glut.GLUT_ACTION_ON_WINDOW_CLOSE,
373 glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS )
373 glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS )
374 glut.glutCreateWindow( sys.argv[0] )
374 glut.glutCreateWindow( sys.argv[0] )
375 glut.glutReshapeWindow( 1, 1 )
375 glut.glutReshapeWindow( 1, 1 )
376 glut.glutHideWindow( )
376 glut.glutHideWindow( )
377 glut.glutWMCloseFunc( glut_close )
377 glut.glutWMCloseFunc( glut_close )
378 glut.glutDisplayFunc( glut_display )
378 glut.glutDisplayFunc( glut_display )
379 glut.glutIdleFunc( glut_idle )
379 glut.glutIdleFunc( glut_idle )
380 else:
380 else:
381 glut.glutWMCloseFunc( glut_close )
381 glut.glutWMCloseFunc( glut_close )
382 glut.glutDisplayFunc( glut_display )
382 glut.glutDisplayFunc( glut_display )
383 glut.glutIdleFunc( glut_idle)
383 glut.glutIdleFunc( glut_idle)
384 self.set_inputhook( inputhook_glut )
384 self.set_inputhook( inputhook_glut )
385 self._current_gui = GUI_GLUT
385 self._current_gui = GUI_GLUT
386 self._apps[GUI_GLUT] = True
386 self._apps[GUI_GLUT] = True
387
387
388
388
389 def disable_glut(self):
389 def disable_glut(self):
390 """Disable event loop integration with glut.
390 """Disable event loop integration with glut.
391
391
392 This sets PyOS_InputHook to NULL and set the display function to a
392 This sets PyOS_InputHook to NULL and set the display function to a
393 dummy one and set the timer to a dummy timer that will be triggered
393 dummy one and set the timer to a dummy timer that will be triggered
394 very far in the future.
394 very far in the future.
395 """
395 """
396 import OpenGL.GLUT as glut
396 import OpenGL.GLUT as glut
397 from glut_support import glutMainLoopEvent
397 from glut_support import glutMainLoopEvent
398
398
399 glut.glutHideWindow() # This is an event to be processed below
399 glut.glutHideWindow() # This is an event to be processed below
400 glutMainLoopEvent()
400 glutMainLoopEvent()
401 self.clear_inputhook()
401 self.clear_inputhook()
402
402
403 def enable_pyglet(self, app=None):
403 def enable_pyglet(self, app=None):
404 """Enable event loop integration with pyglet.
404 """Enable event loop integration with pyglet.
405
405
406 Parameters
406 Parameters
407 ----------
407 ----------
408 app : ignored
408 app : ignored
409 Ignored, it's only a placeholder to keep the call signature of all
409 Ignored, it's only a placeholder to keep the call signature of all
410 gui activation methods consistent, which simplifies the logic of
410 gui activation methods consistent, which simplifies the logic of
411 supporting magics.
411 supporting magics.
412
412
413 Notes
413 Notes
414 -----
414 -----
415 This methods sets the ``PyOS_InputHook`` for pyglet, which allows
415 This methods sets the ``PyOS_InputHook`` for pyglet, which allows
416 pyglet to integrate with terminal based applications like
416 pyglet to integrate with terminal based applications like
417 IPython.
417 IPython.
418
418
419 """
419 """
420 import pyglet
420 import pyglet
421 from IPython.lib.inputhookpyglet import inputhook_pyglet
421 from IPython.lib.inputhookpyglet import inputhook_pyglet
422 self.set_inputhook(inputhook_pyglet)
422 self.set_inputhook(inputhook_pyglet)
423 self._current_gui = GUI_PYGLET
423 self._current_gui = GUI_PYGLET
424 return app
424 return app
425
425
426 def disable_pyglet(self):
426 def disable_pyglet(self):
427 """Disable event loop integration with pyglet.
427 """Disable event loop integration with pyglet.
428
428
429 This merely sets PyOS_InputHook to NULL.
429 This merely sets PyOS_InputHook to NULL.
430 """
430 """
431 self.clear_inputhook()
431 self.clear_inputhook()
432
432
433 def enable_gtk3(self, app=None):
433 def enable_gtk3(self, app=None):
434 """Enable event loop integration with Gtk3 (gir bindings).
434 """Enable event loop integration with Gtk3 (gir bindings).
435
435
436 Parameters
436 Parameters
437 ----------
437 ----------
438 app : ignored
438 app : ignored
439 Ignored, it's only a placeholder to keep the call signature of all
439 Ignored, it's only a placeholder to keep the call signature of all
440 gui activation methods consistent, which simplifies the logic of
440 gui activation methods consistent, which simplifies the logic of
441 supporting magics.
441 supporting magics.
442
442
443 Notes
443 Notes
444 -----
444 -----
445 This methods sets the PyOS_InputHook for Gtk3, which allows
445 This methods sets the PyOS_InputHook for Gtk3, which allows
446 the Gtk3 to integrate with terminal based applications like
446 the Gtk3 to integrate with terminal based applications like
447 IPython.
447 IPython.
448 """
448 """
449 from IPython.lib.inputhookgtk3 import inputhook_gtk3
449 from IPython.lib.inputhookgtk3 import inputhook_gtk3
450 self.set_inputhook(inputhook_gtk3)
450 self.set_inputhook(inputhook_gtk3)
451 self._current_gui = GUI_GTK
451 self._current_gui = GUI_GTK
452
452
453 def disable_gtk3(self):
453 def disable_gtk3(self):
454 """Disable event loop integration with PyGTK.
454 """Disable event loop integration with PyGTK.
455
455
456 This merely sets PyOS_InputHook to NULL.
456 This merely sets PyOS_InputHook to NULL.
457 """
457 """
458 self.clear_inputhook()
458 self.clear_inputhook()
459
459
460 def current_gui(self):
460 def current_gui(self):
461 """Return a string indicating the currently active GUI or None."""
461 """Return a string indicating the currently active GUI or None."""
462 return self._current_gui
462 return self._current_gui
463
463
464 inputhook_manager = InputHookManager()
464 inputhook_manager = InputHookManager()
465
465
466 enable_wx = inputhook_manager.enable_wx
466 enable_wx = inputhook_manager.enable_wx
467 disable_wx = inputhook_manager.disable_wx
467 disable_wx = inputhook_manager.disable_wx
468 enable_qt4 = inputhook_manager.enable_qt4
468 enable_qt4 = inputhook_manager.enable_qt4
469 disable_qt4 = inputhook_manager.disable_qt4
469 disable_qt4 = inputhook_manager.disable_qt4
470 enable_gtk = inputhook_manager.enable_gtk
470 enable_gtk = inputhook_manager.enable_gtk
471 disable_gtk = inputhook_manager.disable_gtk
471 disable_gtk = inputhook_manager.disable_gtk
472 enable_tk = inputhook_manager.enable_tk
472 enable_tk = inputhook_manager.enable_tk
473 disable_tk = inputhook_manager.disable_tk
473 disable_tk = inputhook_manager.disable_tk
474 enable_glut = inputhook_manager.enable_glut
474 enable_glut = inputhook_manager.enable_glut
475 disable_glut = inputhook_manager.disable_glut
475 disable_glut = inputhook_manager.disable_glut
476 enable_pyglet = inputhook_manager.enable_pyglet
476 enable_pyglet = inputhook_manager.enable_pyglet
477 disable_pyglet = inputhook_manager.disable_pyglet
477 disable_pyglet = inputhook_manager.disable_pyglet
478 enable_gtk3 = inputhook_manager.enable_gtk3
478 enable_gtk3 = inputhook_manager.enable_gtk3
479 disable_gtk3 = inputhook_manager.disable_gtk3
479 disable_gtk3 = inputhook_manager.disable_gtk3
480 clear_inputhook = inputhook_manager.clear_inputhook
480 clear_inputhook = inputhook_manager.clear_inputhook
481 set_inputhook = inputhook_manager.set_inputhook
481 set_inputhook = inputhook_manager.set_inputhook
482 current_gui = inputhook_manager.current_gui
482 current_gui = inputhook_manager.current_gui
483 clear_app_refs = inputhook_manager.clear_app_refs
483 clear_app_refs = inputhook_manager.clear_app_refs
484
484
485
485
486 # Convenience function to switch amongst them
486 # Convenience function to switch amongst them
487 def enable_gui(gui=None, app=None):
487 def enable_gui(gui=None, app=None):
488 """Switch amongst GUI input hooks by name.
488 """Switch amongst GUI input hooks by name.
489
489
490 This is just a utility wrapper around the methods of the InputHookManager
490 This is just a utility wrapper around the methods of the InputHookManager
491 object.
491 object.
492
492
493 Parameters
493 Parameters
494 ----------
494 ----------
495 gui : optional, string or None
495 gui : optional, string or None
496 If None (or 'none'), clears input hook, otherwise it must be one
496 If None (or 'none'), clears input hook, otherwise it must be one
497 of the recognized GUI names (see ``GUI_*`` constants in module).
497 of the recognized GUI names (see ``GUI_*`` constants in module).
498
498
499 app : optional, existing application object.
499 app : optional, existing application object.
500 For toolkits that have the concept of a global app, you can supply an
500 For toolkits that have the concept of a global app, you can supply an
501 existing one. If not given, the toolkit will be probed for one, and if
501 existing one. If not given, the toolkit will be probed for one, and if
502 none is found, a new one will be created. Note that GTK does not have
502 none is found, a new one will be created. Note that GTK does not have
503 this concept, and passing an app if `gui`=="GTK" will raise an error.
503 this concept, and passing an app if `gui`=="GTK" will raise an error.
504
504
505 Returns
505 Returns
506 -------
506 -------
507 The output of the underlying gui switch routine, typically the actual
507 The output of the underlying gui switch routine, typically the actual
508 PyOS_InputHook wrapper object or the GUI toolkit app created, if there was
508 PyOS_InputHook wrapper object or the GUI toolkit app created, if there was
509 one.
509 one.
510 """
510 """
511 guis = {None: clear_inputhook,
511 guis = {None: clear_inputhook,
512 GUI_NONE: clear_inputhook,
512 GUI_NONE: clear_inputhook,
513 GUI_OSX: lambda app=False: None,
513 GUI_OSX: lambda app=False: None,
514 GUI_TK: enable_tk,
514 GUI_TK: enable_tk,
515 GUI_GTK: enable_gtk,
515 GUI_GTK: enable_gtk,
516 GUI_WX: enable_wx,
516 GUI_WX: enable_wx,
517 GUI_QT: enable_qt4, # qt3 not supported
517 GUI_QT: enable_qt4, # qt3 not supported
518 GUI_QT4: enable_qt4,
518 GUI_QT4: enable_qt4,
519 GUI_GLUT: enable_glut,
519 GUI_GLUT: enable_glut,
520 GUI_PYGLET: enable_pyglet,
520 GUI_PYGLET: enable_pyglet,
521 GUI_GTK3: enable_gtk3,
521 GUI_GTK3: enable_gtk3,
522 }
522 }
523 try:
523 try:
524 gui_hook = guis[gui]
524 gui_hook = guis[gui]
525 except KeyError:
525 except KeyError:
526 e = "Invalid GUI request %r, valid ones are:%s" % (gui, guis.keys())
526 e = "Invalid GUI request %r, valid ones are:%s" % (gui, guis.keys())
527 raise ValueError(e)
527 raise ValueError(e)
528 return gui_hook(app)
528 return gui_hook(app)
529
529
@@ -1,595 +1,595 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """IPython Test Suite Runner.
2 """IPython Test Suite Runner.
3
3
4 This module provides a main entry point to a user script to test IPython
4 This module provides a main entry point to a user script to test IPython
5 itself from the command line. There are two ways of running this script:
5 itself from the command line. There are two ways of running this script:
6
6
7 1. With the syntax `iptest all`. This runs our entire test suite by
7 1. With the syntax `iptest all`. This runs our entire test suite by
8 calling this script (with different arguments) recursively. This
8 calling this script (with different arguments) recursively. This
9 causes modules and package to be tested in different processes, using nose
9 causes modules and package to be tested in different processes, using nose
10 or trial where appropriate.
10 or trial where appropriate.
11 2. With the regular nose syntax, like `iptest -vvs IPython`. In this form
11 2. With the regular nose syntax, like `iptest -vvs IPython`. In this form
12 the script simply calls nose, but with special command line flags and
12 the script simply calls nose, but with special command line flags and
13 plugins loaded.
13 plugins loaded.
14
14
15 """
15 """
16
16
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18 # Copyright (C) 2009-2011 The IPython Development Team
18 # Copyright (C) 2009-2011 The IPython Development Team
19 #
19 #
20 # Distributed under the terms of the BSD License. The full license is in
20 # Distributed under the terms of the BSD License. The full license is in
21 # the file COPYING, distributed as part of this software.
21 # the file COPYING, distributed as part of this software.
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Imports
25 # Imports
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27 from __future__ import print_function
27 from __future__ import print_function
28
28
29 # Stdlib
29 # Stdlib
30 import glob
30 import glob
31 import os
31 import os
32 import os.path as path
32 import os.path as path
33 import signal
33 import signal
34 import sys
34 import sys
35 import subprocess
35 import subprocess
36 import tempfile
36 import tempfile
37 import time
37 import time
38 import warnings
38 import warnings
39
39
40 # Note: monkeypatch!
40 # Note: monkeypatch!
41 # We need to monkeypatch a small problem in nose itself first, before importing
41 # We need to monkeypatch a small problem in nose itself first, before importing
42 # it for actual use. This should get into nose upstream, but its release cycle
42 # it for actual use. This should get into nose upstream, but its release cycle
43 # is slow and we need it for our parametric tests to work correctly.
43 # is slow and we need it for our parametric tests to work correctly.
44 from IPython.testing import nosepatch
44 from IPython.testing import nosepatch
45
45
46 # Monkeypatch extra assert methods into nose.tools if they're not already there.
46 # Monkeypatch extra assert methods into nose.tools if they're not already there.
47 # This can be dropped once we no longer test on Python 2.6
47 # This can be dropped once we no longer test on Python 2.6
48 from IPython.testing import nose_assert_methods
48 from IPython.testing import nose_assert_methods
49
49
50 # Now, proceed to import nose itself
50 # Now, proceed to import nose itself
51 import nose.plugins.builtin
51 import nose.plugins.builtin
52 from nose.plugins.xunit import Xunit
52 from nose.plugins.xunit import Xunit
53 from nose import SkipTest
53 from nose import SkipTest
54 from nose.core import TestProgram
54 from nose.core import TestProgram
55
55
56 # Our own imports
56 # Our own imports
57 from IPython.utils import py3compat
57 from IPython.utils import py3compat
58 from IPython.utils.importstring import import_item
58 from IPython.utils.importstring import import_item
59 from IPython.utils.path import get_ipython_module_path, get_ipython_package_dir
59 from IPython.utils.path import get_ipython_module_path, get_ipython_package_dir
60 from IPython.utils.process import find_cmd, pycmd2argv
60 from IPython.utils.process import find_cmd, pycmd2argv
61 from IPython.utils.sysinfo import sys_info
61 from IPython.utils.sysinfo import sys_info
62 from IPython.utils.tempdir import TemporaryDirectory
62 from IPython.utils.tempdir import TemporaryDirectory
63 from IPython.utils.warn import warn
63 from IPython.utils.warn import warn
64
64
65 from IPython.testing import globalipapp
65 from IPython.testing import globalipapp
66 from IPython.testing.plugin.ipdoctest import IPythonDoctest
66 from IPython.testing.plugin.ipdoctest import IPythonDoctest
67 from IPython.external.decorators import KnownFailure, knownfailureif
67 from IPython.external.decorators import KnownFailure, knownfailureif
68
68
69 pjoin = path.join
69 pjoin = path.join
70
70
71
71
72 #-----------------------------------------------------------------------------
72 #-----------------------------------------------------------------------------
73 # Globals
73 # Globals
74 #-----------------------------------------------------------------------------
74 #-----------------------------------------------------------------------------
75
75
76
76
77 #-----------------------------------------------------------------------------
77 #-----------------------------------------------------------------------------
78 # Warnings control
78 # Warnings control
79 #-----------------------------------------------------------------------------
79 #-----------------------------------------------------------------------------
80
80
81 # Twisted generates annoying warnings with Python 2.6, as will do other code
81 # Twisted generates annoying warnings with Python 2.6, as will do other code
82 # that imports 'sets' as of today
82 # that imports 'sets' as of today
83 warnings.filterwarnings('ignore', 'the sets module is deprecated',
83 warnings.filterwarnings('ignore', 'the sets module is deprecated',
84 DeprecationWarning )
84 DeprecationWarning )
85
85
86 # This one also comes from Twisted
86 # This one also comes from Twisted
87 warnings.filterwarnings('ignore', 'the sha module is deprecated',
87 warnings.filterwarnings('ignore', 'the sha module is deprecated',
88 DeprecationWarning)
88 DeprecationWarning)
89
89
90 # Wx on Fedora11 spits these out
90 # Wx on Fedora11 spits these out
91 warnings.filterwarnings('ignore', 'wxPython/wxWidgets release number mismatch',
91 warnings.filterwarnings('ignore', 'wxPython/wxWidgets release number mismatch',
92 UserWarning)
92 UserWarning)
93
93
94 # ------------------------------------------------------------------------------
94 # ------------------------------------------------------------------------------
95 # Monkeypatch Xunit to count known failures as skipped.
95 # Monkeypatch Xunit to count known failures as skipped.
96 # ------------------------------------------------------------------------------
96 # ------------------------------------------------------------------------------
97 def monkeypatch_xunit():
97 def monkeypatch_xunit():
98 try:
98 try:
99 knownfailureif(True)(lambda: None)()
99 knownfailureif(True)(lambda: None)()
100 except Exception as e:
100 except Exception as e:
101 KnownFailureTest = type(e)
101 KnownFailureTest = type(e)
102
102
103 def addError(self, test, err, capt=None):
103 def addError(self, test, err, capt=None):
104 if issubclass(err[0], KnownFailureTest):
104 if issubclass(err[0], KnownFailureTest):
105 err = (SkipTest,) + err[1:]
105 err = (SkipTest,) + err[1:]
106 return self.orig_addError(test, err, capt)
106 return self.orig_addError(test, err, capt)
107
107
108 Xunit.orig_addError = Xunit.addError
108 Xunit.orig_addError = Xunit.addError
109 Xunit.addError = addError
109 Xunit.addError = addError
110
110
111 #-----------------------------------------------------------------------------
111 #-----------------------------------------------------------------------------
112 # Logic for skipping doctests
112 # Logic for skipping doctests
113 #-----------------------------------------------------------------------------
113 #-----------------------------------------------------------------------------
114 def extract_version(mod):
114 def extract_version(mod):
115 return mod.__version__
115 return mod.__version__
116
116
117 def test_for(item, min_version=None, callback=extract_version):
117 def test_for(item, min_version=None, callback=extract_version):
118 """Test to see if item is importable, and optionally check against a minimum
118 """Test to see if item is importable, and optionally check against a minimum
119 version.
119 version.
120
120
121 If min_version is given, the default behavior is to check against the
121 If min_version is given, the default behavior is to check against the
122 `__version__` attribute of the item, but specifying `callback` allows you to
122 `__version__` attribute of the item, but specifying `callback` allows you to
123 extract the value you are interested in. e.g::
123 extract the value you are interested in. e.g::
124
124
125 In [1]: import sys
125 In [1]: import sys
126
126
127 In [2]: from IPython.testing.iptest import test_for
127 In [2]: from IPython.testing.iptest import test_for
128
128
129 In [3]: test_for('sys', (2,6), callback=lambda sys: sys.version_info)
129 In [3]: test_for('sys', (2,6), callback=lambda sys: sys.version_info)
130 Out[3]: True
130 Out[3]: True
131
131
132 """
132 """
133 try:
133 try:
134 check = import_item(item)
134 check = import_item(item)
135 except (ImportError, RuntimeError):
135 except (ImportError, RuntimeError):
136 # GTK reports Runtime error if it can't be initialized even if it's
136 # GTK reports Runtime error if it can't be initialized even if it's
137 # importable.
137 # importable.
138 return False
138 return False
139 else:
139 else:
140 if min_version:
140 if min_version:
141 if callback:
141 if callback:
142 # extra processing step to get version to compare
142 # extra processing step to get version to compare
143 check = callback(check)
143 check = callback(check)
144
144
145 return check >= min_version
145 return check >= min_version
146 else:
146 else:
147 return True
147 return True
148
148
149 # Global dict where we can store information on what we have and what we don't
149 # Global dict where we can store information on what we have and what we don't
150 # have available at test run time
150 # have available at test run time
151 have = {}
151 have = {}
152
152
153 have['curses'] = test_for('_curses')
153 have['curses'] = test_for('_curses')
154 have['matplotlib'] = test_for('matplotlib')
154 have['matplotlib'] = test_for('matplotlib')
155 have['numpy'] = test_for('numpy')
155 have['numpy'] = test_for('numpy')
156 have['pexpect'] = test_for('IPython.external.pexpect')
156 have['pexpect'] = test_for('IPython.external.pexpect')
157 have['pymongo'] = test_for('pymongo')
157 have['pymongo'] = test_for('pymongo')
158 have['pygments'] = test_for('pygments')
158 have['pygments'] = test_for('pygments')
159 have['qt'] = test_for('IPython.external.qt')
159 have['qt'] = test_for('IPython.external.qt')
160 have['rpy2'] = test_for('rpy2')
160 have['rpy2'] = test_for('rpy2')
161 have['sqlite3'] = test_for('sqlite3')
161 have['sqlite3'] = test_for('sqlite3')
162 have['cython'] = test_for('Cython')
162 have['cython'] = test_for('Cython')
163 have['oct2py'] = test_for('oct2py')
163 have['oct2py'] = test_for('oct2py')
164 have['tornado'] = test_for('tornado.version_info', (2,1,0), callback=None)
164 have['tornado'] = test_for('tornado.version_info', (2,1,0), callback=None)
165 have['wx'] = test_for('wx')
165 have['wx'] = test_for('wx')
166 have['wx.aui'] = test_for('wx.aui')
166 have['wx.aui'] = test_for('wx.aui')
167 have['azure'] = test_for('azure')
167 have['azure'] = test_for('azure')
168
168
169 if os.name == 'nt':
169 if os.name == 'nt':
170 min_zmq = (2,1,7)
170 min_zmq = (2,1,7)
171 else:
171 else:
172 min_zmq = (2,1,4)
172 min_zmq = (2,1,4)
173
173
174 def version_tuple(mod):
174 def version_tuple(mod):
175 "turn '2.1.9' into (2,1,9), and '2.1dev' into (2,1,999)"
175 "turn '2.1.9' into (2,1,9), and '2.1dev' into (2,1,999)"
176 # turn 'dev' into 999, because Python3 rejects str-int comparisons
176 # turn 'dev' into 999, because Python3 rejects str-int comparisons
177 vs = mod.__version__.replace('dev', '.999')
177 vs = mod.__version__.replace('dev', '.999')
178 tup = tuple([int(v) for v in vs.split('.') ])
178 tup = tuple([int(v) for v in vs.split('.') ])
179 return tup
179 return tup
180
180
181 have['zmq'] = test_for('zmq', min_zmq, version_tuple)
181 have['zmq'] = test_for('zmq', min_zmq, version_tuple)
182
182
183 #-----------------------------------------------------------------------------
183 #-----------------------------------------------------------------------------
184 # Functions and classes
184 # Functions and classes
185 #-----------------------------------------------------------------------------
185 #-----------------------------------------------------------------------------
186
186
187 def report():
187 def report():
188 """Return a string with a summary report of test-related variables."""
188 """Return a string with a summary report of test-related variables."""
189
189
190 out = [ sys_info(), '\n']
190 out = [ sys_info(), '\n']
191
191
192 avail = []
192 avail = []
193 not_avail = []
193 not_avail = []
194
194
195 for k, is_avail in have.items():
195 for k, is_avail in have.items():
196 if is_avail:
196 if is_avail:
197 avail.append(k)
197 avail.append(k)
198 else:
198 else:
199 not_avail.append(k)
199 not_avail.append(k)
200
200
201 if avail:
201 if avail:
202 out.append('\nTools and libraries available at test time:\n')
202 out.append('\nTools and libraries available at test time:\n')
203 avail.sort()
203 avail.sort()
204 out.append(' ' + ' '.join(avail)+'\n')
204 out.append(' ' + ' '.join(avail)+'\n')
205
205
206 if not_avail:
206 if not_avail:
207 out.append('\nTools and libraries NOT available at test time:\n')
207 out.append('\nTools and libraries NOT available at test time:\n')
208 not_avail.sort()
208 not_avail.sort()
209 out.append(' ' + ' '.join(not_avail)+'\n')
209 out.append(' ' + ' '.join(not_avail)+'\n')
210
210
211 return ''.join(out)
211 return ''.join(out)
212
212
213
213
214 def make_exclude():
214 def make_exclude():
215 """Make patterns of modules and packages to exclude from testing.
215 """Make patterns of modules and packages to exclude from testing.
216
216
217 For the IPythonDoctest plugin, we need to exclude certain patterns that
217 For the IPythonDoctest plugin, we need to exclude certain patterns that
218 cause testing problems. We should strive to minimize the number of
218 cause testing problems. We should strive to minimize the number of
219 skipped modules, since this means untested code.
219 skipped modules, since this means untested code.
220
220
221 These modules and packages will NOT get scanned by nose at all for tests.
221 These modules and packages will NOT get scanned by nose at all for tests.
222 """
222 """
223 # Simple utility to make IPython paths more readably, we need a lot of
223 # Simple utility to make IPython paths more readably, we need a lot of
224 # these below
224 # these below
225 ipjoin = lambda *paths: pjoin('IPython', *paths)
225 ipjoin = lambda *paths: pjoin('IPython', *paths)
226
226
227 exclusions = [ipjoin('external'),
227 exclusions = [ipjoin('external'),
228 ipjoin('quarantine'),
228 ipjoin('quarantine'),
229 ipjoin('deathrow'),
229 ipjoin('deathrow'),
230 # This guy is probably attic material
230 # This guy is probably attic material
231 ipjoin('testing', 'mkdoctests'),
231 ipjoin('testing', 'mkdoctests'),
232 # Testing inputhook will need a lot of thought, to figure out
232 # Testing inputhook will need a lot of thought, to figure out
233 # how to have tests that don't lock up with the gui event
233 # how to have tests that don't lock up with the gui event
234 # loops in the picture
234 # loops in the picture
235 ipjoin('lib', 'inputhook'),
235 ipjoin('lib', 'inputhook'),
236 # Config files aren't really importable stand-alone
236 # Config files aren't really importable stand-alone
237 ipjoin('config', 'profile'),
237 ipjoin('config', 'profile'),
238 # The notebook 'static' directory contains JS, css and other
238 # The notebook 'static' directory contains JS, css and other
239 # files for web serving. Occasionally projects may put a .py
239 # files for web serving. Occasionally projects may put a .py
240 # file in there (MathJax ships a conf.py), so we might as
240 # file in there (MathJax ships a conf.py), so we might as
241 # well play it safe and skip the whole thing.
241 # well play it safe and skip the whole thing.
242 ipjoin('frontend', 'html', 'notebook', 'static')
242 ipjoin('frontend', 'html', 'notebook', 'static')
243 ]
243 ]
244 if not have['sqlite3']:
244 if not have['sqlite3']:
245 exclusions.append(ipjoin('core', 'tests', 'test_history'))
245 exclusions.append(ipjoin('core', 'tests', 'test_history'))
246 exclusions.append(ipjoin('core', 'history'))
246 exclusions.append(ipjoin('core', 'history'))
247 if not have['wx']:
247 if not have['wx']:
248 exclusions.append(ipjoin('lib', 'inputhookwx'))
248 exclusions.append(ipjoin('lib', 'inputhookwx'))
249
249
250 # FIXME: temporarily disable autoreload tests, as they can produce
250 # FIXME: temporarily disable autoreload tests, as they can produce
251 # spurious failures in subsequent tests (cythonmagic).
251 # spurious failures in subsequent tests (cythonmagic).
252 exclusions.append(ipjoin('extensions', 'autoreload'))
252 exclusions.append(ipjoin('extensions', 'autoreload'))
253 exclusions.append(ipjoin('extensions', 'tests', 'test_autoreload'))
253 exclusions.append(ipjoin('extensions', 'tests', 'test_autoreload'))
254
254
255 # We do this unconditionally, so that the test suite doesn't import
255 # We do this unconditionally, so that the test suite doesn't import
256 # gtk, changing the default encoding and masking some unicode bugs.
256 # gtk, changing the default encoding and masking some unicode bugs.
257 exclusions.append(ipjoin('lib', 'inputhookgtk'))
257 exclusions.append(ipjoin('lib', 'inputhookgtk'))
258 exclusions.append(ipjoin('zmq', 'gui', 'gtkembed'))
258 exclusions.append(ipjoin('zmq', 'gui', 'gtkembed'))
259
259
260 # These have to be skipped on win32 because the use echo, rm, cd, etc.
260 # These have to be skipped on win32 because the use echo, rm, cd, etc.
261 # See ticket https://github.com/ipython/ipython/issues/87
261 # See ticket https://github.com/ipython/ipython/issues/87
262 if sys.platform == 'win32':
262 if sys.platform == 'win32':
263 exclusions.append(ipjoin('testing', 'plugin', 'test_exampleip'))
263 exclusions.append(ipjoin('testing', 'plugin', 'test_exampleip'))
264 exclusions.append(ipjoin('testing', 'plugin', 'dtexample'))
264 exclusions.append(ipjoin('testing', 'plugin', 'dtexample'))
265
265
266 if not have['pexpect']:
266 if not have['pexpect']:
267 exclusions.extend([ipjoin('lib', 'irunner'),
267 exclusions.extend([ipjoin('lib', 'irunner'),
268 ipjoin('lib', 'tests', 'test_irunner'),
268 ipjoin('lib', 'tests', 'test_irunner'),
269 ipjoin('frontend', 'terminal', 'console'),
269 ipjoin('frontend', 'terminal', 'console'),
270 ])
270 ])
271
271
272 if not have['zmq']:
272 if not have['zmq']:
273 exclusions.append(ipjoin('zmq'))
273 exclusions.append(ipjoin('zmq'))
274 exclusions.append(ipjoin('frontend', 'qt'))
274 exclusions.append(ipjoin('frontend', 'qt'))
275 exclusions.append(ipjoin('frontend', 'html'))
275 exclusions.append(ipjoin('frontend', 'html'))
276 exclusions.append(ipjoin('frontend', 'consoleapp.py'))
276 exclusions.append(ipjoin('frontend', 'consoleapp.py'))
277 exclusions.append(ipjoin('frontend', 'terminal', 'console'))
277 exclusions.append(ipjoin('frontend', 'terminal', 'console'))
278 exclusions.append(ipjoin('parallel'))
278 exclusions.append(ipjoin('parallel'))
279 elif not have['qt'] or not have['pygments']:
279 elif not have['qt'] or not have['pygments']:
280 exclusions.append(ipjoin('frontend', 'qt'))
280 exclusions.append(ipjoin('frontend', 'qt'))
281
281
282 if not have['pymongo']:
282 if not have['pymongo']:
283 exclusions.append(ipjoin('parallel', 'controller', 'mongodb'))
283 exclusions.append(ipjoin('parallel', 'controller', 'mongodb'))
284 exclusions.append(ipjoin('parallel', 'tests', 'test_mongodb'))
284 exclusions.append(ipjoin('parallel', 'tests', 'test_mongodb'))
285
285
286 if not have['matplotlib']:
286 if not have['matplotlib']:
287 exclusions.extend([ipjoin('core', 'pylabtools'),
287 exclusions.extend([ipjoin('core', 'pylabtools'),
288 ipjoin('core', 'tests', 'test_pylabtools'),
288 ipjoin('core', 'tests', 'test_pylabtools'),
289 ipjoin('zmq', 'pylab'),
289 ipjoin('zmq', 'pylab'),
290 ])
290 ])
291
291
292 if not have['cython']:
292 if not have['cython']:
293 exclusions.extend([ipjoin('extensions', 'cythonmagic')])
293 exclusions.extend([ipjoin('extensions', 'cythonmagic')])
294 exclusions.extend([ipjoin('extensions', 'tests', 'test_cythonmagic')])
294 exclusions.extend([ipjoin('extensions', 'tests', 'test_cythonmagic')])
295
295
296 if not have['oct2py']:
296 if not have['oct2py']:
297 exclusions.extend([ipjoin('extensions', 'octavemagic')])
297 exclusions.extend([ipjoin('extensions', 'octavemagic')])
298 exclusions.extend([ipjoin('extensions', 'tests', 'test_octavemagic')])
298 exclusions.extend([ipjoin('extensions', 'tests', 'test_octavemagic')])
299
299
300 if not have['tornado']:
300 if not have['tornado']:
301 exclusions.append(ipjoin('frontend', 'html'))
301 exclusions.append(ipjoin('frontend', 'html'))
302
302
303 if not have['rpy2'] or not have['numpy']:
303 if not have['rpy2'] or not have['numpy']:
304 exclusions.append(ipjoin('extensions', 'rmagic'))
304 exclusions.append(ipjoin('extensions', 'rmagic'))
305 exclusions.append(ipjoin('extensions', 'tests', 'test_rmagic'))
305 exclusions.append(ipjoin('extensions', 'tests', 'test_rmagic'))
306
306
307 if not have['azure']:
307 if not have['azure']:
308 exclusions.append(ipjoin('frontend', 'html', 'notebook', 'azurenbmanager'))
308 exclusions.append(ipjoin('frontend', 'html', 'notebook', 'azurenbmanager'))
309
309
310 # This is needed for the reg-exp to match on win32 in the ipdoctest plugin.
310 # This is needed for the reg-exp to match on win32 in the ipdoctest plugin.
311 if sys.platform == 'win32':
311 if sys.platform == 'win32':
312 exclusions = [s.replace('\\','\\\\') for s in exclusions]
312 exclusions = [s.replace('\\','\\\\') for s in exclusions]
313
313
314 # check for any exclusions that don't seem to exist:
314 # check for any exclusions that don't seem to exist:
315 parent, _ = os.path.split(get_ipython_package_dir())
315 parent, _ = os.path.split(get_ipython_package_dir())
316 for exclusion in exclusions:
316 for exclusion in exclusions:
317 if exclusion.endswith(('deathrow', 'quarantine')):
317 if exclusion.endswith(('deathrow', 'quarantine')):
318 # ignore deathrow/quarantine, which exist in dev, but not install
318 # ignore deathrow/quarantine, which exist in dev, but not install
319 continue
319 continue
320 fullpath = pjoin(parent, exclusion)
320 fullpath = pjoin(parent, exclusion)
321 if not os.path.exists(fullpath) and not glob.glob(fullpath + '.*'):
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 return exclusions
324 return exclusions
325
325
326
326
327 class IPTester(object):
327 class IPTester(object):
328 """Call that calls iptest or trial in a subprocess.
328 """Call that calls iptest or trial in a subprocess.
329 """
329 """
330 #: string, name of test runner that will be called
330 #: string, name of test runner that will be called
331 runner = None
331 runner = None
332 #: list, parameters for test runner
332 #: list, parameters for test runner
333 params = None
333 params = None
334 #: list, arguments of system call to be made to call test runner
334 #: list, arguments of system call to be made to call test runner
335 call_args = None
335 call_args = None
336 #: list, subprocesses we start (for cleanup)
336 #: list, subprocesses we start (for cleanup)
337 processes = None
337 processes = None
338 #: str, coverage xml output file
338 #: str, coverage xml output file
339 coverage_xml = None
339 coverage_xml = None
340
340
341 def __init__(self, runner='iptest', params=None):
341 def __init__(self, runner='iptest', params=None):
342 """Create new test runner."""
342 """Create new test runner."""
343 p = os.path
343 p = os.path
344 if runner == 'iptest':
344 if runner == 'iptest':
345 iptest_app = get_ipython_module_path('IPython.testing.iptest')
345 iptest_app = get_ipython_module_path('IPython.testing.iptest')
346 self.runner = pycmd2argv(iptest_app) + sys.argv[1:]
346 self.runner = pycmd2argv(iptest_app) + sys.argv[1:]
347 else:
347 else:
348 raise Exception('Not a valid test runner: %s' % repr(runner))
348 raise Exception('Not a valid test runner: %s' % repr(runner))
349 if params is None:
349 if params is None:
350 params = []
350 params = []
351 if isinstance(params, str):
351 if isinstance(params, str):
352 params = [params]
352 params = [params]
353 self.params = params
353 self.params = params
354
354
355 # Assemble call
355 # Assemble call
356 self.call_args = self.runner+self.params
356 self.call_args = self.runner+self.params
357
357
358 # Find the section we're testing (IPython.foo)
358 # Find the section we're testing (IPython.foo)
359 for sect in self.params:
359 for sect in self.params:
360 if sect.startswith('IPython'): break
360 if sect.startswith('IPython'): break
361 else:
361 else:
362 raise ValueError("Section not found", self.params)
362 raise ValueError("Section not found", self.params)
363
363
364 if '--with-xunit' in self.call_args:
364 if '--with-xunit' in self.call_args:
365
365
366 self.call_args.append('--xunit-file')
366 self.call_args.append('--xunit-file')
367 # FIXME: when Windows uses subprocess.call, these extra quotes are unnecessary:
367 # FIXME: when Windows uses subprocess.call, these extra quotes are unnecessary:
368 xunit_file = path.abspath(sect+'.xunit.xml')
368 xunit_file = path.abspath(sect+'.xunit.xml')
369 if sys.platform == 'win32':
369 if sys.platform == 'win32':
370 xunit_file = '"%s"' % xunit_file
370 xunit_file = '"%s"' % xunit_file
371 self.call_args.append(xunit_file)
371 self.call_args.append(xunit_file)
372
372
373 if '--with-xml-coverage' in self.call_args:
373 if '--with-xml-coverage' in self.call_args:
374 self.coverage_xml = path.abspath(sect+".coverage.xml")
374 self.coverage_xml = path.abspath(sect+".coverage.xml")
375 self.call_args.remove('--with-xml-coverage')
375 self.call_args.remove('--with-xml-coverage')
376 self.call_args = ["coverage", "run", "--source="+sect] + self.call_args[1:]
376 self.call_args = ["coverage", "run", "--source="+sect] + self.call_args[1:]
377
377
378 # Store anything we start to clean up on deletion
378 # Store anything we start to clean up on deletion
379 self.processes = []
379 self.processes = []
380
380
381 def _run_cmd(self):
381 def _run_cmd(self):
382 with TemporaryDirectory() as IPYTHONDIR:
382 with TemporaryDirectory() as IPYTHONDIR:
383 env = os.environ.copy()
383 env = os.environ.copy()
384 env['IPYTHONDIR'] = IPYTHONDIR
384 env['IPYTHONDIR'] = IPYTHONDIR
385 # print >> sys.stderr, '*** CMD:', ' '.join(self.call_args) # dbg
385 # print >> sys.stderr, '*** CMD:', ' '.join(self.call_args) # dbg
386 subp = subprocess.Popen(self.call_args, env=env)
386 subp = subprocess.Popen(self.call_args, env=env)
387 self.processes.append(subp)
387 self.processes.append(subp)
388 # If this fails, the process will be left in self.processes and
388 # If this fails, the process will be left in self.processes and
389 # cleaned up later, but if the wait call succeeds, then we can
389 # cleaned up later, but if the wait call succeeds, then we can
390 # clear the stored process.
390 # clear the stored process.
391 retcode = subp.wait()
391 retcode = subp.wait()
392 self.processes.pop()
392 self.processes.pop()
393 return retcode
393 return retcode
394
394
395 def run(self):
395 def run(self):
396 """Run the stored commands"""
396 """Run the stored commands"""
397 try:
397 try:
398 retcode = self._run_cmd()
398 retcode = self._run_cmd()
399 except KeyboardInterrupt:
399 except KeyboardInterrupt:
400 return -signal.SIGINT
400 return -signal.SIGINT
401 except:
401 except:
402 import traceback
402 import traceback
403 traceback.print_exc()
403 traceback.print_exc()
404 return 1 # signal failure
404 return 1 # signal failure
405
405
406 if self.coverage_xml:
406 if self.coverage_xml:
407 subprocess.call(["coverage", "xml", "-o", self.coverage_xml])
407 subprocess.call(["coverage", "xml", "-o", self.coverage_xml])
408 return retcode
408 return retcode
409
409
410 def __del__(self):
410 def __del__(self):
411 """Cleanup on exit by killing any leftover processes."""
411 """Cleanup on exit by killing any leftover processes."""
412 for subp in self.processes:
412 for subp in self.processes:
413 if subp.poll() is not None:
413 if subp.poll() is not None:
414 continue # process is already dead
414 continue # process is already dead
415
415
416 try:
416 try:
417 print('Cleaning up stale PID: %d' % subp.pid)
417 print('Cleaning up stale PID: %d' % subp.pid)
418 subp.kill()
418 subp.kill()
419 except: # (OSError, WindowsError) ?
419 except: # (OSError, WindowsError) ?
420 # This is just a best effort, if we fail or the process was
420 # This is just a best effort, if we fail or the process was
421 # really gone, ignore it.
421 # really gone, ignore it.
422 pass
422 pass
423 else:
423 else:
424 for i in range(10):
424 for i in range(10):
425 if subp.poll() is None:
425 if subp.poll() is None:
426 time.sleep(0.1)
426 time.sleep(0.1)
427 else:
427 else:
428 break
428 break
429
429
430 if subp.poll() is None:
430 if subp.poll() is None:
431 # The process did not die...
431 # The process did not die...
432 print('... failed. Manual cleanup may be required.')
432 print('... failed. Manual cleanup may be required.')
433
433
434 def make_runners(inc_slow=False):
434 def make_runners(inc_slow=False):
435 """Define the top-level packages that need to be tested.
435 """Define the top-level packages that need to be tested.
436 """
436 """
437
437
438 # Packages to be tested via nose, that only depend on the stdlib
438 # Packages to be tested via nose, that only depend on the stdlib
439 nose_pkg_names = ['config', 'core', 'extensions', 'frontend', 'lib',
439 nose_pkg_names = ['config', 'core', 'extensions', 'frontend', 'lib',
440 'testing', 'utils', 'nbformat' ]
440 'testing', 'utils', 'nbformat' ]
441
441
442 if have['zmq']:
442 if have['zmq']:
443 nose_pkg_names.append('zmq')
443 nose_pkg_names.append('zmq')
444 if inc_slow:
444 if inc_slow:
445 nose_pkg_names.append('parallel')
445 nose_pkg_names.append('parallel')
446
446
447 # For debugging this code, only load quick stuff
447 # For debugging this code, only load quick stuff
448 #nose_pkg_names = ['core', 'extensions'] # dbg
448 #nose_pkg_names = ['core', 'extensions'] # dbg
449
449
450 # Make fully qualified package names prepending 'IPython.' to our name lists
450 # Make fully qualified package names prepending 'IPython.' to our name lists
451 nose_packages = ['IPython.%s' % m for m in nose_pkg_names ]
451 nose_packages = ['IPython.%s' % m for m in nose_pkg_names ]
452
452
453 # Make runners
453 # Make runners
454 runners = [ (v, IPTester('iptest', params=v)) for v in nose_packages ]
454 runners = [ (v, IPTester('iptest', params=v)) for v in nose_packages ]
455
455
456 return runners
456 return runners
457
457
458
458
459 def run_iptest():
459 def run_iptest():
460 """Run the IPython test suite using nose.
460 """Run the IPython test suite using nose.
461
461
462 This function is called when this script is **not** called with the form
462 This function is called when this script is **not** called with the form
463 `iptest all`. It simply calls nose with appropriate command line flags
463 `iptest all`. It simply calls nose with appropriate command line flags
464 and accepts all of the standard nose arguments.
464 and accepts all of the standard nose arguments.
465 """
465 """
466 # Apply our monkeypatch to Xunit
466 # Apply our monkeypatch to Xunit
467 if '--with-xunit' in sys.argv and not hasattr(Xunit, 'orig_addError'):
467 if '--with-xunit' in sys.argv and not hasattr(Xunit, 'orig_addError'):
468 monkeypatch_xunit()
468 monkeypatch_xunit()
469
469
470 warnings.filterwarnings('ignore',
470 warnings.filterwarnings('ignore',
471 'This will be removed soon. Use IPython.testing.util instead')
471 'This will be removed soon. Use IPython.testing.util instead')
472
472
473 argv = sys.argv + [ '--detailed-errors', # extra info in tracebacks
473 argv = sys.argv + [ '--detailed-errors', # extra info in tracebacks
474
474
475 '--with-ipdoctest',
475 '--with-ipdoctest',
476 '--ipdoctest-tests','--ipdoctest-extension=txt',
476 '--ipdoctest-tests','--ipdoctest-extension=txt',
477
477
478 # We add --exe because of setuptools' imbecility (it
478 # We add --exe because of setuptools' imbecility (it
479 # blindly does chmod +x on ALL files). Nose does the
479 # blindly does chmod +x on ALL files). Nose does the
480 # right thing and it tries to avoid executables,
480 # right thing and it tries to avoid executables,
481 # setuptools unfortunately forces our hand here. This
481 # setuptools unfortunately forces our hand here. This
482 # has been discussed on the distutils list and the
482 # has been discussed on the distutils list and the
483 # setuptools devs refuse to fix this problem!
483 # setuptools devs refuse to fix this problem!
484 '--exe',
484 '--exe',
485 ]
485 ]
486 if '-a' not in argv and '-A' not in argv:
486 if '-a' not in argv and '-A' not in argv:
487 argv = argv + ['-a', '!crash']
487 argv = argv + ['-a', '!crash']
488
488
489 if nose.__version__ >= '0.11':
489 if nose.__version__ >= '0.11':
490 # I don't fully understand why we need this one, but depending on what
490 # I don't fully understand why we need this one, but depending on what
491 # directory the test suite is run from, if we don't give it, 0 tests
491 # directory the test suite is run from, if we don't give it, 0 tests
492 # get run. Specifically, if the test suite is run from the source dir
492 # get run. Specifically, if the test suite is run from the source dir
493 # with an argument (like 'iptest.py IPython.core', 0 tests are run,
493 # with an argument (like 'iptest.py IPython.core', 0 tests are run,
494 # even if the same call done in this directory works fine). It appears
494 # even if the same call done in this directory works fine). It appears
495 # that if the requested package is in the current dir, nose bails early
495 # that if the requested package is in the current dir, nose bails early
496 # by default. Since it's otherwise harmless, leave it in by default
496 # by default. Since it's otherwise harmless, leave it in by default
497 # for nose >= 0.11, though unfortunately nose 0.10 doesn't support it.
497 # for nose >= 0.11, though unfortunately nose 0.10 doesn't support it.
498 argv.append('--traverse-namespace')
498 argv.append('--traverse-namespace')
499
499
500 # use our plugin for doctesting. It will remove the standard doctest plugin
500 # use our plugin for doctesting. It will remove the standard doctest plugin
501 # if it finds it enabled
501 # if it finds it enabled
502 plugins = [IPythonDoctest(make_exclude()), KnownFailure()]
502 plugins = [IPythonDoctest(make_exclude()), KnownFailure()]
503 # We need a global ipython running in this process
503 # We need a global ipython running in this process
504 globalipapp.start_ipython()
504 globalipapp.start_ipython()
505 # Now nose can run
505 # Now nose can run
506 TestProgram(argv=argv, addplugins=plugins)
506 TestProgram(argv=argv, addplugins=plugins)
507
507
508
508
509 def run_iptestall(inc_slow=False):
509 def run_iptestall(inc_slow=False):
510 """Run the entire IPython test suite by calling nose and trial.
510 """Run the entire IPython test suite by calling nose and trial.
511
511
512 This function constructs :class:`IPTester` instances for all IPython
512 This function constructs :class:`IPTester` instances for all IPython
513 modules and package and then runs each of them. This causes the modules
513 modules and package and then runs each of them. This causes the modules
514 and packages of IPython to be tested each in their own subprocess using
514 and packages of IPython to be tested each in their own subprocess using
515 nose.
515 nose.
516
516
517 Parameters
517 Parameters
518 ----------
518 ----------
519
519
520 inc_slow : bool, optional
520 inc_slow : bool, optional
521 Include slow tests, like IPython.parallel. By default, these tests aren't
521 Include slow tests, like IPython.parallel. By default, these tests aren't
522 run.
522 run.
523 """
523 """
524
524
525 runners = make_runners(inc_slow=inc_slow)
525 runners = make_runners(inc_slow=inc_slow)
526
526
527 # Run the test runners in a temporary dir so we can nuke it when finished
527 # Run the test runners in a temporary dir so we can nuke it when finished
528 # to clean up any junk files left over by accident. This also makes it
528 # to clean up any junk files left over by accident. This also makes it
529 # robust against being run in non-writeable directories by mistake, as the
529 # robust against being run in non-writeable directories by mistake, as the
530 # temp dir will always be user-writeable.
530 # temp dir will always be user-writeable.
531 curdir = os.getcwdu()
531 curdir = os.getcwdu()
532 testdir = tempfile.gettempdir()
532 testdir = tempfile.gettempdir()
533 os.chdir(testdir)
533 os.chdir(testdir)
534
534
535 # Run all test runners, tracking execution time
535 # Run all test runners, tracking execution time
536 failed = []
536 failed = []
537 t_start = time.time()
537 t_start = time.time()
538 try:
538 try:
539 for (name, runner) in runners:
539 for (name, runner) in runners:
540 print('*'*70)
540 print('*'*70)
541 print('IPython test group:',name)
541 print('IPython test group:',name)
542 res = runner.run()
542 res = runner.run()
543 if res:
543 if res:
544 failed.append( (name, runner) )
544 failed.append( (name, runner) )
545 if res == -signal.SIGINT:
545 if res == -signal.SIGINT:
546 print("Interrupted")
546 print("Interrupted")
547 break
547 break
548 finally:
548 finally:
549 os.chdir(curdir)
549 os.chdir(curdir)
550 t_end = time.time()
550 t_end = time.time()
551 t_tests = t_end - t_start
551 t_tests = t_end - t_start
552 nrunners = len(runners)
552 nrunners = len(runners)
553 nfail = len(failed)
553 nfail = len(failed)
554 # summarize results
554 # summarize results
555 print()
555 print()
556 print('*'*70)
556 print('*'*70)
557 print('Test suite completed for system with the following information:')
557 print('Test suite completed for system with the following information:')
558 print(report())
558 print(report())
559 print('Ran %s test groups in %.3fs' % (nrunners, t_tests))
559 print('Ran %s test groups in %.3fs' % (nrunners, t_tests))
560 print()
560 print()
561 print('Status:')
561 print('Status:')
562 if not failed:
562 if not failed:
563 print('OK')
563 print('OK')
564 else:
564 else:
565 # If anything went wrong, point out what command to rerun manually to
565 # If anything went wrong, point out what command to rerun manually to
566 # see the actual errors and individual summary
566 # see the actual errors and individual summary
567 print('ERROR - %s out of %s test groups failed.' % (nfail, nrunners))
567 print('ERROR - %s out of %s test groups failed.' % (nfail, nrunners))
568 for name, failed_runner in failed:
568 for name, failed_runner in failed:
569 print('-'*40)
569 print('-'*40)
570 print('Runner failed:',name)
570 print('Runner failed:',name)
571 print('You may wish to rerun this one individually, with:')
571 print('You may wish to rerun this one individually, with:')
572 failed_call_args = [py3compat.cast_unicode(x) for x in failed_runner.call_args]
572 failed_call_args = [py3compat.cast_unicode(x) for x in failed_runner.call_args]
573 print(u' '.join(failed_call_args))
573 print(u' '.join(failed_call_args))
574 print()
574 print()
575 # Ensure that our exit code indicates failure
575 # Ensure that our exit code indicates failure
576 sys.exit(1)
576 sys.exit(1)
577
577
578
578
579 def main():
579 def main():
580 for arg in sys.argv[1:]:
580 for arg in sys.argv[1:]:
581 if arg.startswith('IPython'):
581 if arg.startswith('IPython'):
582 # This is in-process
582 # This is in-process
583 run_iptest()
583 run_iptest()
584 else:
584 else:
585 if "--all" in sys.argv:
585 if "--all" in sys.argv:
586 sys.argv.remove("--all")
586 sys.argv.remove("--all")
587 inc_slow = True
587 inc_slow = True
588 else:
588 else:
589 inc_slow = False
589 inc_slow = False
590 # This starts subprocesses
590 # This starts subprocesses
591 run_iptestall(inc_slow=inc_slow)
591 run_iptestall(inc_slow=inc_slow)
592
592
593
593
594 if __name__ == '__main__':
594 if __name__ == '__main__':
595 main()
595 main()
@@ -1,167 +1,167 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 Older utilities that are not being used.
3 Older utilities that are not being used.
4
4
5 WARNING: IF YOU NEED TO USE ONE OF THESE FUNCTIONS, PLEASE FIRST MOVE IT
5 WARNING: IF YOU NEED TO USE ONE OF THESE FUNCTIONS, PLEASE FIRST MOVE IT
6 TO ANOTHER APPROPRIATE MODULE IN IPython.utils.
6 TO ANOTHER APPROPRIATE MODULE IN IPython.utils.
7 """
7 """
8
8
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10 # Copyright (C) 2008-2011 The IPython Development Team
10 # Copyright (C) 2008-2011 The IPython Development Team
11 #
11 #
12 # Distributed under the terms of the BSD License. The full license is in
12 # Distributed under the terms of the BSD License. The full license is in
13 # the file COPYING, distributed as part of this software.
13 # the file COPYING, distributed as part of this software.
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15
15
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17 # Imports
17 # Imports
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19
19
20 import sys
20 import sys
21 import warnings
21 import warnings
22
22
23 from IPython.utils.warn import warn
23 from IPython.utils.warn import warn
24
24
25 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
26 # Code
26 # Code
27 #-----------------------------------------------------------------------------
27 #-----------------------------------------------------------------------------
28
28
29
29
30 def mutex_opts(dict,ex_op):
30 def mutex_opts(dict,ex_op):
31 """Check for presence of mutually exclusive keys in a dict.
31 """Check for presence of mutually exclusive keys in a dict.
32
32
33 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
33 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
34 for op1,op2 in ex_op:
34 for op1,op2 in ex_op:
35 if op1 in dict and op2 in dict:
35 if op1 in dict and op2 in dict:
36 raise ValueError('\n*** ERROR in Arguments *** '\
36 raise ValueError('\n*** ERROR in Arguments *** '\
37 'Options '+op1+' and '+op2+' are mutually exclusive.')
37 'Options '+op1+' and '+op2+' are mutually exclusive.')
38
38
39
39
40 class EvalDict:
40 class EvalDict:
41 """
41 """
42 Emulate a dict which evaluates its contents in the caller's frame.
42 Emulate a dict which evaluates its contents in the caller's frame.
43
43
44 Usage:
44 Usage:
45 >>> number = 19
45 >>> number = 19
46
46
47 >>> text = "python"
47 >>> text = "python"
48
48
49 >>> print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
49 >>> print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
50 Python 2.1 rules!
50 Python 2.1 rules!
51 """
51 """
52
52
53 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
53 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
54 # modified (shorter) version of:
54 # modified (shorter) version of:
55 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
55 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
56 # Skip Montanaro (skip@pobox.com).
56 # Skip Montanaro (skip@pobox.com).
57
57
58 def __getitem__(self, name):
58 def __getitem__(self, name):
59 frame = sys._getframe(1)
59 frame = sys._getframe(1)
60 return eval(name, frame.f_globals, frame.f_locals)
60 return eval(name, frame.f_globals, frame.f_locals)
61
61
62 EvalString = EvalDict # for backwards compatibility
62 EvalString = EvalDict # for backwards compatibility
63
63
64
64
65 def all_belong(candidates,checklist):
65 def all_belong(candidates,checklist):
66 """Check whether a list of items ALL appear in a given list of options.
66 """Check whether a list of items ALL appear in a given list of options.
67
67
68 Returns a single 1 or 0 value."""
68 Returns a single 1 or 0 value."""
69
69
70 return 1-(0 in [x in checklist for x in candidates])
70 return 1-(0 in [x in checklist for x in candidates])
71
71
72
72
73 def belong(candidates,checklist):
73 def belong(candidates,checklist):
74 """Check whether a list of items appear in a given list of options.
74 """Check whether a list of items appear in a given list of options.
75
75
76 Returns a list of 1 and 0, one for each candidate given."""
76 Returns a list of 1 and 0, one for each candidate given."""
77
77
78 return [x in checklist for x in candidates]
78 return [x in checklist for x in candidates]
79
79
80
80
81 def with_obj(object, **args):
81 def with_obj(object, **args):
82 """Set multiple attributes for an object, similar to Pascal's with.
82 """Set multiple attributes for an object, similar to Pascal's with.
83
83
84 Example:
84 Example:
85 with_obj(jim,
85 with_obj(jim,
86 born = 1960,
86 born = 1960,
87 haircolour = 'Brown',
87 haircolour = 'Brown',
88 eyecolour = 'Green')
88 eyecolour = 'Green')
89
89
90 Credit: Greg Ewing, in
90 Credit: Greg Ewing, in
91 http://mail.python.org/pipermail/python-list/2001-May/040703.html.
91 http://mail.python.org/pipermail/python-list/2001-May/040703.html.
92
92
93 NOTE: up until IPython 0.7.2, this was called simply 'with', but 'with'
93 NOTE: up until IPython 0.7.2, this was called simply 'with', but 'with'
94 has become a keyword for Python 2.5, so we had to rename it."""
94 has become a keyword for Python 2.5, so we had to rename it."""
95
95
96 object.__dict__.update(args)
96 object.__dict__.update(args)
97
97
98
98
99 def map_method(method,object_list,*argseq,**kw):
99 def map_method(method,object_list,*argseq,**kw):
100 """map_method(method,object_list,*args,**kw) -> list
100 """map_method(method,object_list,*args,**kw) -> list
101
101
102 Return a list of the results of applying the methods to the items of the
102 Return a list of the results of applying the methods to the items of the
103 argument sequence(s). If more than one sequence is given, the method is
103 argument sequence(s). If more than one sequence is given, the method is
104 called with an argument list consisting of the corresponding item of each
104 called with an argument list consisting of the corresponding item of each
105 sequence. All sequences must be of the same length.
105 sequence. All sequences must be of the same length.
106
106
107 Keyword arguments are passed verbatim to all objects called.
107 Keyword arguments are passed verbatim to all objects called.
108
108
109 This is Python code, so it's not nearly as fast as the builtin map()."""
109 This is Python code, so it's not nearly as fast as the builtin map()."""
110
110
111 out_list = []
111 out_list = []
112 idx = 0
112 idx = 0
113 for object in object_list:
113 for object in object_list:
114 try:
114 try:
115 handler = getattr(object, method)
115 handler = getattr(object, method)
116 except AttributeError:
116 except AttributeError:
117 out_list.append(None)
117 out_list.append(None)
118 else:
118 else:
119 if argseq:
119 if argseq:
120 args = map(lambda lst:lst[idx],argseq)
120 args = map(lambda lst:lst[idx],argseq)
121 #print 'ob',object,'hand',handler,'ar',args # dbg
121 #print 'ob',object,'hand',handler,'ar',args # dbg
122 out_list.append(handler(args,**kw))
122 out_list.append(handler(args,**kw))
123 else:
123 else:
124 out_list.append(handler(**kw))
124 out_list.append(handler(**kw))
125 idx += 1
125 idx += 1
126 return out_list
126 return out_list
127
127
128
128
129 def import_fail_info(mod_name,fns=None):
129 def import_fail_info(mod_name,fns=None):
130 """Inform load failure for a module."""
130 """Inform load failure for a module."""
131
131
132 if fns == None:
132 if fns == None:
133 warn("Loading of %s failed.\n" % (mod_name,))
133 warn("Loading of %s failed." % (mod_name,))
134 else:
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 class NotGiven: pass
138 class NotGiven: pass
139
139
140 def popkey(dct,key,default=NotGiven):
140 def popkey(dct,key,default=NotGiven):
141 """Return dct[key] and delete dct[key].
141 """Return dct[key] and delete dct[key].
142
142
143 If default is given, return it if dct[key] doesn't exist, otherwise raise
143 If default is given, return it if dct[key] doesn't exist, otherwise raise
144 KeyError. """
144 KeyError. """
145
145
146 try:
146 try:
147 val = dct[key]
147 val = dct[key]
148 except KeyError:
148 except KeyError:
149 if default is NotGiven:
149 if default is NotGiven:
150 raise
150 raise
151 else:
151 else:
152 return default
152 return default
153 else:
153 else:
154 del dct[key]
154 del dct[key]
155 return val
155 return val
156
156
157
157
158 def wrap_deprecated(func, suggest = '<nothing>'):
158 def wrap_deprecated(func, suggest = '<nothing>'):
159 def newFunc(*args, **kwargs):
159 def newFunc(*args, **kwargs):
160 warnings.warn("Call to deprecated function %s, use %s instead" %
160 warnings.warn("Call to deprecated function %s, use %s instead" %
161 ( func.__name__, suggest),
161 ( func.__name__, suggest),
162 category=DeprecationWarning,
162 category=DeprecationWarning,
163 stacklevel = 2)
163 stacklevel = 2)
164 return func(*args, **kwargs)
164 return func(*args, **kwargs)
165 return newFunc
165 return newFunc
166
166
167
167
@@ -1,67 +1,67 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 Utilities for warnings. Shoudn't we just use the built in warnings module.
3 Utilities for warnings. Shoudn't we just use the built in warnings module.
4 """
4 """
5
5
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (C) 2008-2011 The IPython Development Team
7 # Copyright (C) 2008-2011 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 from __future__ import print_function
16 from __future__ import print_function
17
17
18 import sys
18 import sys
19
19
20 from IPython.utils import io
20 from IPython.utils import io
21
21
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23 # Code
23 # Code
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26 def warn(msg,level=2,exit_val=1):
26 def warn(msg,level=2,exit_val=1):
27 """Standard warning printer. Gives formatting consistency.
27 """Standard warning printer. Gives formatting consistency.
28
28
29 Output is sent to io.stderr (sys.stderr by default).
29 Output is sent to io.stderr (sys.stderr by default).
30
30
31 Options:
31 Options:
32
32
33 -level(2): allows finer control:
33 -level(2): allows finer control:
34 0 -> Do nothing, dummy function.
34 0 -> Do nothing, dummy function.
35 1 -> Print message.
35 1 -> Print message.
36 2 -> Print 'WARNING:' + message. (Default level).
36 2 -> Print 'WARNING:' + message. (Default level).
37 3 -> Print 'ERROR:' + message.
37 3 -> Print 'ERROR:' + message.
38 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
38 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
39
39
40 -exit_val (1): exit value returned by sys.exit() for a level 4
40 -exit_val (1): exit value returned by sys.exit() for a level 4
41 warning. Ignored for all other levels."""
41 warning. Ignored for all other levels."""
42
42
43 if level>0:
43 if level>0:
44 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
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 if level == 4:
46 if level == 4:
47 print('Exiting.\n', file=io.stderr)
47 print('Exiting.\n', file=io.stderr)
48 sys.exit(exit_val)
48 sys.exit(exit_val)
49
49
50
50
51 def info(msg):
51 def info(msg):
52 """Equivalent to warn(msg,level=1)."""
52 """Equivalent to warn(msg,level=1)."""
53
53
54 warn(msg,level=1)
54 warn(msg,level=1)
55
55
56
56
57 def error(msg):
57 def error(msg):
58 """Equivalent to warn(msg,level=3)."""
58 """Equivalent to warn(msg,level=3)."""
59
59
60 warn(msg,level=3)
60 warn(msg,level=3)
61
61
62
62
63 def fatal(msg,exit_val=1):
63 def fatal(msg,exit_val=1):
64 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
64 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
65
65
66 warn(msg,exit_val=exit_val,level=4)
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