##// END OF EJS Templates
Terminal IPython working with newapp
MinRK -
Show More
@@ -1,802 +1,799
1 """ History related magics and functionality """
1 """ History related magics and functionality """
2 #-----------------------------------------------------------------------------
2 #-----------------------------------------------------------------------------
3 # Copyright (C) 2010 The IPython Development Team.
3 # Copyright (C) 2010 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 import sqlite3
20 import sqlite3
21 import threading
21 import threading
22
22
23 # Our own packages
23 # Our own packages
24 from IPython.config.configurable import Configurable
24 from IPython.config.configurable import Configurable
25
25
26 from IPython.testing.skipdoctest import skip_doctest
26 from IPython.testing.skipdoctest import skip_doctest
27 from IPython.utils import io
27 from IPython.utils import io
28 from IPython.utils.traitlets import Bool, Dict, Instance, Int, List, Unicode
28 from IPython.utils.traitlets import Bool, Dict, Instance, Int, List, Unicode
29 from IPython.utils.warn import warn
29 from IPython.utils.warn import warn
30
30
31 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
32 # Classes and functions
32 # Classes and functions
33 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
34
34
35 class HistoryManager(Configurable):
35 class HistoryManager(Configurable):
36 """A class to organize all history-related functionality in one place.
36 """A class to organize all history-related functionality in one place.
37 """
37 """
38 # Public interface
38 # Public interface
39
39
40 # An instance of the IPython shell we are attached to
40 # An instance of the IPython shell we are attached to
41 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
41 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
42 # Lists to hold processed and raw history. These start with a blank entry
42 # Lists to hold processed and raw history. These start with a blank entry
43 # so that we can index them starting from 1
43 # so that we can index them starting from 1
44 input_hist_parsed = List([""])
44 input_hist_parsed = List([""])
45 input_hist_raw = List([""])
45 input_hist_raw = List([""])
46 # A list of directories visited during session
46 # A list of directories visited during session
47 dir_hist = List()
47 dir_hist = List()
48 def _dir_hist_default(self):
48 def _dir_hist_default(self):
49 try:
49 try:
50 return [os.getcwd()]
50 return [os.getcwd()]
51 except OSError:
51 except OSError:
52 return []
52 return []
53
53
54 # A dict of output history, keyed with ints from the shell's
54 # A dict of output history, keyed with ints from the shell's
55 # execution count.
55 # execution count.
56 output_hist = Dict()
56 output_hist = Dict()
57 # The text/plain repr of outputs.
57 # The text/plain repr of outputs.
58 output_hist_reprs = Dict()
58 output_hist_reprs = Dict()
59
59
60 # String holding the path to the history file
60 # String holding the path to the history file
61 hist_file = Unicode(config=True)
61 hist_file = Unicode(config=True)
62
62
63 # The SQLite database
63 # The SQLite database
64 db = Instance(sqlite3.Connection)
64 db = Instance(sqlite3.Connection)
65 # The number of the current session in the history database
65 # The number of the current session in the history database
66 session_number = Int()
66 session_number = Int()
67 # Should we log output to the database? (default no)
67 # Should we log output to the database? (default no)
68 db_log_output = Bool(False, config=True)
68 db_log_output = Bool(False, config=True)
69 # Write to database every x commands (higher values save disk access & power)
69 # Write to database every x commands (higher values save disk access & power)
70 # Values of 1 or less effectively disable caching.
70 # Values of 1 or less effectively disable caching.
71 db_cache_size = Int(0, config=True)
71 db_cache_size = Int(0, config=True)
72 # The input and output caches
72 # The input and output caches
73 db_input_cache = List()
73 db_input_cache = List()
74 db_output_cache = List()
74 db_output_cache = List()
75
75
76 # History saving in separate thread
76 # History saving in separate thread
77 save_thread = Instance('IPython.core.history.HistorySavingThread')
77 save_thread = Instance('IPython.core.history.HistorySavingThread')
78 # N.B. Event is a function returning an instance of _Event.
78 # N.B. Event is a function returning an instance of _Event.
79 save_flag = Instance(threading._Event)
79 save_flag = Instance(threading._Event)
80
80
81 # Private interface
81 # Private interface
82 # Variables used to store the three last inputs from the user. On each new
82 # Variables used to store the three last inputs from the user. On each new
83 # history update, we populate the user's namespace with these, shifted as
83 # history update, we populate the user's namespace with these, shifted as
84 # necessary.
84 # necessary.
85 _i00 = Unicode(u'')
85 _i00 = Unicode(u'')
86 _i = Unicode(u'')
86 _i = Unicode(u'')
87 _ii = Unicode(u'')
87 _ii = Unicode(u'')
88 _iii = Unicode(u'')
88 _iii = Unicode(u'')
89
89
90 # A regex matching all forms of the exit command, so that we don't store
90 # A regex matching all forms of the exit command, so that we don't store
91 # them in the history (it's annoying to rewind the first entry and land on
91 # them in the history (it's annoying to rewind the first entry and land on
92 # an exit call).
92 # an exit call).
93 _exit_re = re.compile(r"(exit|quit)(\s*\(.*\))?$")
93 _exit_re = re.compile(r"(exit|quit)(\s*\(.*\))?$")
94
94
95 def __init__(self, shell, config=None, **traits):
95 def __init__(self, shell, config=None, **traits):
96 """Create a new history manager associated with a shell instance.
96 """Create a new history manager associated with a shell instance.
97 """
97 """
98 # We need a pointer back to the shell for various tasks.
98 # We need a pointer back to the shell for various tasks.
99 super(HistoryManager, self).__init__(shell=shell, config=config,
99 super(HistoryManager, self).__init__(shell=shell, config=config,
100 **traits)
100 **traits)
101
101
102 if self.hist_file == u'':
102 if self.hist_file == u'':
103 # No one has set the hist_file, yet.
103 # No one has set the hist_file, yet.
104 if shell.profile:
104 histfname = 'history'
105 histfname = 'history-%s' % shell.profile
105 self.hist_file = os.path.join(shell.profile_dir.location, histfname + '.sqlite')
106 else:
107 histfname = 'history'
108 self.hist_file = os.path.join(shell.ipython_dir, histfname + '.sqlite')
109
106
110 try:
107 try:
111 self.init_db()
108 self.init_db()
112 except sqlite3.DatabaseError:
109 except sqlite3.DatabaseError:
113 if os.path.isfile(self.hist_file):
110 if os.path.isfile(self.hist_file):
114 # Try to move the file out of the way.
111 # Try to move the file out of the way.
115 newpath = os.path.join(self.shell.ipython_dir, "hist-corrupt.sqlite")
112 newpath = os.path.join(self.shell.profile_dir.location, "hist-corrupt.sqlite")
116 os.rename(self.hist_file, newpath)
113 os.rename(self.hist_file, newpath)
117 print("ERROR! History file wasn't a valid SQLite database.",
114 print("ERROR! History file wasn't a valid SQLite database.",
118 "It was moved to %s" % newpath, "and a new file created.")
115 "It was moved to %s" % newpath, "and a new file created.")
119 self.init_db()
116 self.init_db()
120 else:
117 else:
121 # The hist_file is probably :memory: or something else.
118 # The hist_file is probably :memory: or something else.
122 raise
119 raise
123
120
124 self.save_flag = threading.Event()
121 self.save_flag = threading.Event()
125 self.db_input_cache_lock = threading.Lock()
122 self.db_input_cache_lock = threading.Lock()
126 self.db_output_cache_lock = threading.Lock()
123 self.db_output_cache_lock = threading.Lock()
127 self.save_thread = HistorySavingThread(self)
124 self.save_thread = HistorySavingThread(self)
128 self.save_thread.start()
125 self.save_thread.start()
129
126
130 self.new_session()
127 self.new_session()
131
128
132
129
133 def init_db(self):
130 def init_db(self):
134 """Connect to the database, and create tables if necessary."""
131 """Connect to the database, and create tables if necessary."""
135 self.db = sqlite3.connect(self.hist_file)
132 self.db = sqlite3.connect(self.hist_file)
136 self.db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer
133 self.db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer
137 primary key autoincrement, start timestamp,
134 primary key autoincrement, start timestamp,
138 end timestamp, num_cmds integer, remark text)""")
135 end timestamp, num_cmds integer, remark text)""")
139 self.db.execute("""CREATE TABLE IF NOT EXISTS history
136 self.db.execute("""CREATE TABLE IF NOT EXISTS history
140 (session integer, line integer, source text, source_raw text,
137 (session integer, line integer, source text, source_raw text,
141 PRIMARY KEY (session, line))""")
138 PRIMARY KEY (session, line))""")
142 # Output history is optional, but ensure the table's there so it can be
139 # Output history is optional, but ensure the table's there so it can be
143 # enabled later.
140 # enabled later.
144 self.db.execute("""CREATE TABLE IF NOT EXISTS output_history
141 self.db.execute("""CREATE TABLE IF NOT EXISTS output_history
145 (session integer, line integer, output text,
142 (session integer, line integer, output text,
146 PRIMARY KEY (session, line))""")
143 PRIMARY KEY (session, line))""")
147 self.db.commit()
144 self.db.commit()
148
145
149 def new_session(self, conn=None):
146 def new_session(self, conn=None):
150 """Get a new session number."""
147 """Get a new session number."""
151 if conn is None:
148 if conn is None:
152 conn = self.db
149 conn = self.db
153
150
154 with conn:
151 with conn:
155 cur = conn.execute("""INSERT INTO sessions VALUES (NULL, ?, NULL,
152 cur = conn.execute("""INSERT INTO sessions VALUES (NULL, ?, NULL,
156 NULL, "") """, (datetime.datetime.now(),))
153 NULL, "") """, (datetime.datetime.now(),))
157 self.session_number = cur.lastrowid
154 self.session_number = cur.lastrowid
158
155
159 def end_session(self):
156 def end_session(self):
160 """Close the database session, filling in the end time and line count."""
157 """Close the database session, filling in the end time and line count."""
161 self.writeout_cache()
158 self.writeout_cache()
162 with self.db:
159 with self.db:
163 self.db.execute("""UPDATE sessions SET end=?, num_cmds=? WHERE
160 self.db.execute("""UPDATE sessions SET end=?, num_cmds=? WHERE
164 session==?""", (datetime.datetime.now(),
161 session==?""", (datetime.datetime.now(),
165 len(self.input_hist_parsed)-1, self.session_number))
162 len(self.input_hist_parsed)-1, self.session_number))
166 self.session_number = 0
163 self.session_number = 0
167
164
168 def name_session(self, name):
165 def name_session(self, name):
169 """Give the current session a name in the history database."""
166 """Give the current session a name in the history database."""
170 with self.db:
167 with self.db:
171 self.db.execute("UPDATE sessions SET remark=? WHERE session==?",
168 self.db.execute("UPDATE sessions SET remark=? WHERE session==?",
172 (name, self.session_number))
169 (name, self.session_number))
173
170
174 def reset(self, new_session=True):
171 def reset(self, new_session=True):
175 """Clear the session history, releasing all object references, and
172 """Clear the session history, releasing all object references, and
176 optionally open a new session."""
173 optionally open a new session."""
177 self.output_hist.clear()
174 self.output_hist.clear()
178 # The directory history can't be completely empty
175 # The directory history can't be completely empty
179 self.dir_hist[:] = [os.getcwd()]
176 self.dir_hist[:] = [os.getcwd()]
180
177
181 if new_session:
178 if new_session:
182 if self.session_number:
179 if self.session_number:
183 self.end_session()
180 self.end_session()
184 self.input_hist_parsed[:] = [""]
181 self.input_hist_parsed[:] = [""]
185 self.input_hist_raw[:] = [""]
182 self.input_hist_raw[:] = [""]
186 self.new_session()
183 self.new_session()
187
184
188 ## -------------------------------
185 ## -------------------------------
189 ## Methods for retrieving history:
186 ## Methods for retrieving history:
190 ## -------------------------------
187 ## -------------------------------
191 def _run_sql(self, sql, params, raw=True, output=False):
188 def _run_sql(self, sql, params, raw=True, output=False):
192 """Prepares and runs an SQL query for the history database.
189 """Prepares and runs an SQL query for the history database.
193
190
194 Parameters
191 Parameters
195 ----------
192 ----------
196 sql : str
193 sql : str
197 Any filtering expressions to go after SELECT ... FROM ...
194 Any filtering expressions to go after SELECT ... FROM ...
198 params : tuple
195 params : tuple
199 Parameters passed to the SQL query (to replace "?")
196 Parameters passed to the SQL query (to replace "?")
200 raw, output : bool
197 raw, output : bool
201 See :meth:`get_range`
198 See :meth:`get_range`
202
199
203 Returns
200 Returns
204 -------
201 -------
205 Tuples as :meth:`get_range`
202 Tuples as :meth:`get_range`
206 """
203 """
207 toget = 'source_raw' if raw else 'source'
204 toget = 'source_raw' if raw else 'source'
208 sqlfrom = "history"
205 sqlfrom = "history"
209 if output:
206 if output:
210 sqlfrom = "history LEFT JOIN output_history USING (session, line)"
207 sqlfrom = "history LEFT JOIN output_history USING (session, line)"
211 toget = "history.%s, output_history.output" % toget
208 toget = "history.%s, output_history.output" % toget
212 cur = self.db.execute("SELECT session, line, %s FROM %s " %\
209 cur = self.db.execute("SELECT session, line, %s FROM %s " %\
213 (toget, sqlfrom) + sql, params)
210 (toget, sqlfrom) + sql, params)
214 if output: # Regroup into 3-tuples, and parse JSON
211 if output: # Regroup into 3-tuples, and parse JSON
215 return ((ses, lin, (inp, out)) for ses, lin, inp, out in cur)
212 return ((ses, lin, (inp, out)) for ses, lin, inp, out in cur)
216 return cur
213 return cur
217
214
218
215
219 def get_tail(self, n=10, raw=True, output=False, include_latest=False):
216 def get_tail(self, n=10, raw=True, output=False, include_latest=False):
220 """Get the last n lines from the history database.
217 """Get the last n lines from the history database.
221
218
222 Parameters
219 Parameters
223 ----------
220 ----------
224 n : int
221 n : int
225 The number of lines to get
222 The number of lines to get
226 raw, output : bool
223 raw, output : bool
227 See :meth:`get_range`
224 See :meth:`get_range`
228 include_latest : bool
225 include_latest : bool
229 If False (default), n+1 lines are fetched, and the latest one
226 If False (default), n+1 lines are fetched, and the latest one
230 is discarded. This is intended to be used where the function
227 is discarded. This is intended to be used where the function
231 is called by a user command, which it should not return.
228 is called by a user command, which it should not return.
232
229
233 Returns
230 Returns
234 -------
231 -------
235 Tuples as :meth:`get_range`
232 Tuples as :meth:`get_range`
236 """
233 """
237 self.writeout_cache()
234 self.writeout_cache()
238 if not include_latest:
235 if not include_latest:
239 n += 1
236 n += 1
240 cur = self._run_sql("ORDER BY session DESC, line DESC LIMIT ?",
237 cur = self._run_sql("ORDER BY session DESC, line DESC LIMIT ?",
241 (n,), raw=raw, output=output)
238 (n,), raw=raw, output=output)
242 if not include_latest:
239 if not include_latest:
243 return reversed(list(cur)[1:])
240 return reversed(list(cur)[1:])
244 return reversed(list(cur))
241 return reversed(list(cur))
245
242
246 def search(self, pattern="*", raw=True, search_raw=True,
243 def search(self, pattern="*", raw=True, search_raw=True,
247 output=False):
244 output=False):
248 """Search the database using unix glob-style matching (wildcards
245 """Search the database using unix glob-style matching (wildcards
249 * and ?).
246 * and ?).
250
247
251 Parameters
248 Parameters
252 ----------
249 ----------
253 pattern : str
250 pattern : str
254 The wildcarded pattern to match when searching
251 The wildcarded pattern to match when searching
255 search_raw : bool
252 search_raw : bool
256 If True, search the raw input, otherwise, the parsed input
253 If True, search the raw input, otherwise, the parsed input
257 raw, output : bool
254 raw, output : bool
258 See :meth:`get_range`
255 See :meth:`get_range`
259
256
260 Returns
257 Returns
261 -------
258 -------
262 Tuples as :meth:`get_range`
259 Tuples as :meth:`get_range`
263 """
260 """
264 tosearch = "source_raw" if search_raw else "source"
261 tosearch = "source_raw" if search_raw else "source"
265 if output:
262 if output:
266 tosearch = "history." + tosearch
263 tosearch = "history." + tosearch
267 self.writeout_cache()
264 self.writeout_cache()
268 return self._run_sql("WHERE %s GLOB ?" % tosearch, (pattern,),
265 return self._run_sql("WHERE %s GLOB ?" % tosearch, (pattern,),
269 raw=raw, output=output)
266 raw=raw, output=output)
270
267
271 def _get_range_session(self, start=1, stop=None, raw=True, output=False):
268 def _get_range_session(self, start=1, stop=None, raw=True, output=False):
272 """Get input and output history from the current session. Called by
269 """Get input and output history from the current session. Called by
273 get_range, and takes similar parameters."""
270 get_range, and takes similar parameters."""
274 input_hist = self.input_hist_raw if raw else self.input_hist_parsed
271 input_hist = self.input_hist_raw if raw else self.input_hist_parsed
275
272
276 n = len(input_hist)
273 n = len(input_hist)
277 if start < 0:
274 if start < 0:
278 start += n
275 start += n
279 if not stop:
276 if not stop:
280 stop = n
277 stop = n
281 elif stop < 0:
278 elif stop < 0:
282 stop += n
279 stop += n
283
280
284 for i in range(start, stop):
281 for i in range(start, stop):
285 if output:
282 if output:
286 line = (input_hist[i], self.output_hist_reprs.get(i))
283 line = (input_hist[i], self.output_hist_reprs.get(i))
287 else:
284 else:
288 line = input_hist[i]
285 line = input_hist[i]
289 yield (0, i, line)
286 yield (0, i, line)
290
287
291 def get_range(self, session=0, start=1, stop=None, raw=True,output=False):
288 def get_range(self, session=0, start=1, stop=None, raw=True,output=False):
292 """Retrieve input by session.
289 """Retrieve input by session.
293
290
294 Parameters
291 Parameters
295 ----------
292 ----------
296 session : int
293 session : int
297 Session number to retrieve. The current session is 0, and negative
294 Session number to retrieve. The current session is 0, and negative
298 numbers count back from current session, so -1 is previous session.
295 numbers count back from current session, so -1 is previous session.
299 start : int
296 start : int
300 First line to retrieve.
297 First line to retrieve.
301 stop : int
298 stop : int
302 End of line range (excluded from output itself). If None, retrieve
299 End of line range (excluded from output itself). If None, retrieve
303 to the end of the session.
300 to the end of the session.
304 raw : bool
301 raw : bool
305 If True, return untranslated input
302 If True, return untranslated input
306 output : bool
303 output : bool
307 If True, attempt to include output. This will be 'real' Python
304 If True, attempt to include output. This will be 'real' Python
308 objects for the current session, or text reprs from previous
305 objects for the current session, or text reprs from previous
309 sessions if db_log_output was enabled at the time. Where no output
306 sessions if db_log_output was enabled at the time. Where no output
310 is found, None is used.
307 is found, None is used.
311
308
312 Returns
309 Returns
313 -------
310 -------
314 An iterator over the desired lines. Each line is a 3-tuple, either
311 An iterator over the desired lines. Each line is a 3-tuple, either
315 (session, line, input) if output is False, or
312 (session, line, input) if output is False, or
316 (session, line, (input, output)) if output is True.
313 (session, line, (input, output)) if output is True.
317 """
314 """
318 if session == 0 or session==self.session_number: # Current session
315 if session == 0 or session==self.session_number: # Current session
319 return self._get_range_session(start, stop, raw, output)
316 return self._get_range_session(start, stop, raw, output)
320 if session < 0:
317 if session < 0:
321 session += self.session_number
318 session += self.session_number
322
319
323 if stop:
320 if stop:
324 lineclause = "line >= ? AND line < ?"
321 lineclause = "line >= ? AND line < ?"
325 params = (session, start, stop)
322 params = (session, start, stop)
326 else:
323 else:
327 lineclause = "line>=?"
324 lineclause = "line>=?"
328 params = (session, start)
325 params = (session, start)
329
326
330 return self._run_sql("WHERE session==? AND %s""" % lineclause,
327 return self._run_sql("WHERE session==? AND %s""" % lineclause,
331 params, raw=raw, output=output)
328 params, raw=raw, output=output)
332
329
333 def get_range_by_str(self, rangestr, raw=True, output=False):
330 def get_range_by_str(self, rangestr, raw=True, output=False):
334 """Get lines of history from a string of ranges, as used by magic
331 """Get lines of history from a string of ranges, as used by magic
335 commands %hist, %save, %macro, etc.
332 commands %hist, %save, %macro, etc.
336
333
337 Parameters
334 Parameters
338 ----------
335 ----------
339 rangestr : str
336 rangestr : str
340 A string specifying ranges, e.g. "5 ~2/1-4". See
337 A string specifying ranges, e.g. "5 ~2/1-4". See
341 :func:`magic_history` for full details.
338 :func:`magic_history` for full details.
342 raw, output : bool
339 raw, output : bool
343 As :meth:`get_range`
340 As :meth:`get_range`
344
341
345 Returns
342 Returns
346 -------
343 -------
347 Tuples as :meth:`get_range`
344 Tuples as :meth:`get_range`
348 """
345 """
349 for sess, s, e in extract_hist_ranges(rangestr):
346 for sess, s, e in extract_hist_ranges(rangestr):
350 for line in self.get_range(sess, s, e, raw=raw, output=output):
347 for line in self.get_range(sess, s, e, raw=raw, output=output):
351 yield line
348 yield line
352
349
353 ## ----------------------------
350 ## ----------------------------
354 ## Methods for storing history:
351 ## Methods for storing history:
355 ## ----------------------------
352 ## ----------------------------
356 def store_inputs(self, line_num, source, source_raw=None):
353 def store_inputs(self, line_num, source, source_raw=None):
357 """Store source and raw input in history and create input cache
354 """Store source and raw input in history and create input cache
358 variables _i*.
355 variables _i*.
359
356
360 Parameters
357 Parameters
361 ----------
358 ----------
362 line_num : int
359 line_num : int
363 The prompt number of this input.
360 The prompt number of this input.
364
361
365 source : str
362 source : str
366 Python input.
363 Python input.
367
364
368 source_raw : str, optional
365 source_raw : str, optional
369 If given, this is the raw input without any IPython transformations
366 If given, this is the raw input without any IPython transformations
370 applied to it. If not given, ``source`` is used.
367 applied to it. If not given, ``source`` is used.
371 """
368 """
372 if source_raw is None:
369 if source_raw is None:
373 source_raw = source
370 source_raw = source
374 source = source.rstrip('\n')
371 source = source.rstrip('\n')
375 source_raw = source_raw.rstrip('\n')
372 source_raw = source_raw.rstrip('\n')
376
373
377 # do not store exit/quit commands
374 # do not store exit/quit commands
378 if self._exit_re.match(source_raw.strip()):
375 if self._exit_re.match(source_raw.strip()):
379 return
376 return
380
377
381 self.input_hist_parsed.append(source)
378 self.input_hist_parsed.append(source)
382 self.input_hist_raw.append(source_raw)
379 self.input_hist_raw.append(source_raw)
383
380
384 with self.db_input_cache_lock:
381 with self.db_input_cache_lock:
385 self.db_input_cache.append((line_num, source, source_raw))
382 self.db_input_cache.append((line_num, source, source_raw))
386 # Trigger to flush cache and write to DB.
383 # Trigger to flush cache and write to DB.
387 if len(self.db_input_cache) >= self.db_cache_size:
384 if len(self.db_input_cache) >= self.db_cache_size:
388 self.save_flag.set()
385 self.save_flag.set()
389
386
390 # update the auto _i variables
387 # update the auto _i variables
391 self._iii = self._ii
388 self._iii = self._ii
392 self._ii = self._i
389 self._ii = self._i
393 self._i = self._i00
390 self._i = self._i00
394 self._i00 = source_raw
391 self._i00 = source_raw
395
392
396 # hackish access to user namespace to create _i1,_i2... dynamically
393 # hackish access to user namespace to create _i1,_i2... dynamically
397 new_i = '_i%s' % line_num
394 new_i = '_i%s' % line_num
398 to_main = {'_i': self._i,
395 to_main = {'_i': self._i,
399 '_ii': self._ii,
396 '_ii': self._ii,
400 '_iii': self._iii,
397 '_iii': self._iii,
401 new_i : self._i00 }
398 new_i : self._i00 }
402 self.shell.user_ns.update(to_main)
399 self.shell.user_ns.update(to_main)
403
400
404 def store_output(self, line_num):
401 def store_output(self, line_num):
405 """If database output logging is enabled, this saves all the
402 """If database output logging is enabled, this saves all the
406 outputs from the indicated prompt number to the database. It's
403 outputs from the indicated prompt number to the database. It's
407 called by run_cell after code has been executed.
404 called by run_cell after code has been executed.
408
405
409 Parameters
406 Parameters
410 ----------
407 ----------
411 line_num : int
408 line_num : int
412 The line number from which to save outputs
409 The line number from which to save outputs
413 """
410 """
414 if (not self.db_log_output) or (line_num not in self.output_hist_reprs):
411 if (not self.db_log_output) or (line_num not in self.output_hist_reprs):
415 return
412 return
416 output = self.output_hist_reprs[line_num]
413 output = self.output_hist_reprs[line_num]
417
414
418 with self.db_output_cache_lock:
415 with self.db_output_cache_lock:
419 self.db_output_cache.append((line_num, output))
416 self.db_output_cache.append((line_num, output))
420 if self.db_cache_size <= 1:
417 if self.db_cache_size <= 1:
421 self.save_flag.set()
418 self.save_flag.set()
422
419
423 def _writeout_input_cache(self, conn):
420 def _writeout_input_cache(self, conn):
424 with conn:
421 with conn:
425 for line in self.db_input_cache:
422 for line in self.db_input_cache:
426 conn.execute("INSERT INTO history VALUES (?, ?, ?, ?)",
423 conn.execute("INSERT INTO history VALUES (?, ?, ?, ?)",
427 (self.session_number,)+line)
424 (self.session_number,)+line)
428
425
429 def _writeout_output_cache(self, conn):
426 def _writeout_output_cache(self, conn):
430 with conn:
427 with conn:
431 for line in self.db_output_cache:
428 for line in self.db_output_cache:
432 conn.execute("INSERT INTO output_history VALUES (?, ?, ?)",
429 conn.execute("INSERT INTO output_history VALUES (?, ?, ?)",
433 (self.session_number,)+line)
430 (self.session_number,)+line)
434
431
435 def writeout_cache(self, conn=None):
432 def writeout_cache(self, conn=None):
436 """Write any entries in the cache to the database."""
433 """Write any entries in the cache to the database."""
437 if conn is None:
434 if conn is None:
438 conn = self.db
435 conn = self.db
439
436
440 with self.db_input_cache_lock:
437 with self.db_input_cache_lock:
441 try:
438 try:
442 self._writeout_input_cache(conn)
439 self._writeout_input_cache(conn)
443 except sqlite3.IntegrityError:
440 except sqlite3.IntegrityError:
444 self.new_session(conn)
441 self.new_session(conn)
445 print("ERROR! Session/line number was not unique in",
442 print("ERROR! Session/line number was not unique in",
446 "database. History logging moved to new session",
443 "database. History logging moved to new session",
447 self.session_number)
444 self.session_number)
448 try: # Try writing to the new session. If this fails, don't recurse
445 try: # Try writing to the new session. If this fails, don't recurse
449 self._writeout_input_cache(conn)
446 self._writeout_input_cache(conn)
450 except sqlite3.IntegrityError:
447 except sqlite3.IntegrityError:
451 pass
448 pass
452 finally:
449 finally:
453 self.db_input_cache = []
450 self.db_input_cache = []
454
451
455 with self.db_output_cache_lock:
452 with self.db_output_cache_lock:
456 try:
453 try:
457 self._writeout_output_cache(conn)
454 self._writeout_output_cache(conn)
458 except sqlite3.IntegrityError:
455 except sqlite3.IntegrityError:
459 print("!! Session/line number for output was not unique",
456 print("!! Session/line number for output was not unique",
460 "in database. Output will not be stored.")
457 "in database. Output will not be stored.")
461 finally:
458 finally:
462 self.db_output_cache = []
459 self.db_output_cache = []
463
460
464
461
465 class HistorySavingThread(threading.Thread):
462 class HistorySavingThread(threading.Thread):
466 """This thread takes care of writing history to the database, so that
463 """This thread takes care of writing history to the database, so that
467 the UI isn't held up while that happens.
464 the UI isn't held up while that happens.
468
465
469 It waits for the HistoryManager's save_flag to be set, then writes out
466 It waits for the HistoryManager's save_flag to be set, then writes out
470 the history cache. The main thread is responsible for setting the flag when
467 the history cache. The main thread is responsible for setting the flag when
471 the cache size reaches a defined threshold."""
468 the cache size reaches a defined threshold."""
472 daemon = True
469 daemon = True
473 stop_now = False
470 stop_now = False
474 def __init__(self, history_manager):
471 def __init__(self, history_manager):
475 super(HistorySavingThread, self).__init__()
472 super(HistorySavingThread, self).__init__()
476 self.history_manager = history_manager
473 self.history_manager = history_manager
477 atexit.register(self.stop)
474 atexit.register(self.stop)
478
475
479 def run(self):
476 def run(self):
480 # We need a separate db connection per thread:
477 # We need a separate db connection per thread:
481 try:
478 try:
482 self.db = sqlite3.connect(self.history_manager.hist_file)
479 self.db = sqlite3.connect(self.history_manager.hist_file)
483 while True:
480 while True:
484 self.history_manager.save_flag.wait()
481 self.history_manager.save_flag.wait()
485 if self.stop_now:
482 if self.stop_now:
486 return
483 return
487 self.history_manager.save_flag.clear()
484 self.history_manager.save_flag.clear()
488 self.history_manager.writeout_cache(self.db)
485 self.history_manager.writeout_cache(self.db)
489 except Exception as e:
486 except Exception as e:
490 print(("The history saving thread hit an unexpected error (%s)."
487 print(("The history saving thread hit an unexpected error (%s)."
491 "History will not be written to the database.") % repr(e))
488 "History will not be written to the database.") % repr(e))
492
489
493 def stop(self):
490 def stop(self):
494 """This can be called from the main thread to safely stop this thread.
491 """This can be called from the main thread to safely stop this thread.
495
492
496 Note that it does not attempt to write out remaining history before
493 Note that it does not attempt to write out remaining history before
497 exiting. That should be done by calling the HistoryManager's
494 exiting. That should be done by calling the HistoryManager's
498 end_session method."""
495 end_session method."""
499 self.stop_now = True
496 self.stop_now = True
500 self.history_manager.save_flag.set()
497 self.history_manager.save_flag.set()
501 self.join()
498 self.join()
502
499
503
500
504 # To match, e.g. ~5/8-~2/3
501 # To match, e.g. ~5/8-~2/3
505 range_re = re.compile(r"""
502 range_re = re.compile(r"""
506 ((?P<startsess>~?\d+)/)?
503 ((?P<startsess>~?\d+)/)?
507 (?P<start>\d+) # Only the start line num is compulsory
504 (?P<start>\d+) # Only the start line num is compulsory
508 ((?P<sep>[\-:])
505 ((?P<sep>[\-:])
509 ((?P<endsess>~?\d+)/)?
506 ((?P<endsess>~?\d+)/)?
510 (?P<end>\d+))?
507 (?P<end>\d+))?
511 $""", re.VERBOSE)
508 $""", re.VERBOSE)
512
509
513 def extract_hist_ranges(ranges_str):
510 def extract_hist_ranges(ranges_str):
514 """Turn a string of history ranges into 3-tuples of (session, start, stop).
511 """Turn a string of history ranges into 3-tuples of (session, start, stop).
515
512
516 Examples
513 Examples
517 --------
514 --------
518 list(extract_input_ranges("~8/5-~7/4 2"))
515 list(extract_input_ranges("~8/5-~7/4 2"))
519 [(-8, 5, None), (-7, 1, 4), (0, 2, 3)]
516 [(-8, 5, None), (-7, 1, 4), (0, 2, 3)]
520 """
517 """
521 for range_str in ranges_str.split():
518 for range_str in ranges_str.split():
522 rmatch = range_re.match(range_str)
519 rmatch = range_re.match(range_str)
523 if not rmatch:
520 if not rmatch:
524 continue
521 continue
525 start = int(rmatch.group("start"))
522 start = int(rmatch.group("start"))
526 end = rmatch.group("end")
523 end = rmatch.group("end")
527 end = int(end) if end else start+1 # If no end specified, get (a, a+1)
524 end = int(end) if end else start+1 # If no end specified, get (a, a+1)
528 if rmatch.group("sep") == "-": # 1-3 == 1:4 --> [1, 2, 3]
525 if rmatch.group("sep") == "-": # 1-3 == 1:4 --> [1, 2, 3]
529 end += 1
526 end += 1
530 startsess = rmatch.group("startsess") or "0"
527 startsess = rmatch.group("startsess") or "0"
531 endsess = rmatch.group("endsess") or startsess
528 endsess = rmatch.group("endsess") or startsess
532 startsess = int(startsess.replace("~","-"))
529 startsess = int(startsess.replace("~","-"))
533 endsess = int(endsess.replace("~","-"))
530 endsess = int(endsess.replace("~","-"))
534 assert endsess >= startsess
531 assert endsess >= startsess
535
532
536 if endsess == startsess:
533 if endsess == startsess:
537 yield (startsess, start, end)
534 yield (startsess, start, end)
538 continue
535 continue
539 # Multiple sessions in one range:
536 # Multiple sessions in one range:
540 yield (startsess, start, None)
537 yield (startsess, start, None)
541 for sess in range(startsess+1, endsess):
538 for sess in range(startsess+1, endsess):
542 yield (sess, 1, None)
539 yield (sess, 1, None)
543 yield (endsess, 1, end)
540 yield (endsess, 1, end)
544
541
545 def _format_lineno(session, line):
542 def _format_lineno(session, line):
546 """Helper function to format line numbers properly."""
543 """Helper function to format line numbers properly."""
547 if session == 0:
544 if session == 0:
548 return str(line)
545 return str(line)
549 return "%s#%s" % (session, line)
546 return "%s#%s" % (session, line)
550
547
551 @skip_doctest
548 @skip_doctest
552 def magic_history(self, parameter_s = ''):
549 def magic_history(self, parameter_s = ''):
553 """Print input history (_i<n> variables), with most recent last.
550 """Print input history (_i<n> variables), with most recent last.
554
551
555 %history -> print at most 40 inputs (some may be multi-line)\\
552 %history -> print at most 40 inputs (some may be multi-line)\\
556 %history n -> print at most n inputs\\
553 %history n -> print at most n inputs\\
557 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
554 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
558
555
559 By default, input history is printed without line numbers so it can be
556 By default, input history is printed without line numbers so it can be
560 directly pasted into an editor. Use -n to show them.
557 directly pasted into an editor. Use -n to show them.
561
558
562 Ranges of history can be indicated using the syntax:
559 Ranges of history can be indicated using the syntax:
563 4 : Line 4, current session
560 4 : Line 4, current session
564 4-6 : Lines 4-6, current session
561 4-6 : Lines 4-6, current session
565 243/1-5: Lines 1-5, session 243
562 243/1-5: Lines 1-5, session 243
566 ~2/7 : Line 7, session 2 before current
563 ~2/7 : Line 7, session 2 before current
567 ~8/1-~6/5 : From the first line of 8 sessions ago, to the fifth line
564 ~8/1-~6/5 : From the first line of 8 sessions ago, to the fifth line
568 of 6 sessions ago.
565 of 6 sessions ago.
569 Multiple ranges can be entered, separated by spaces
566 Multiple ranges can be entered, separated by spaces
570
567
571 The same syntax is used by %macro, %save, %edit, %rerun
568 The same syntax is used by %macro, %save, %edit, %rerun
572
569
573 Options:
570 Options:
574
571
575 -n: print line numbers for each input.
572 -n: print line numbers for each input.
576 This feature is only available if numbered prompts are in use.
573 This feature is only available if numbered prompts are in use.
577
574
578 -o: also print outputs for each input.
575 -o: also print outputs for each input.
579
576
580 -p: print classic '>>>' python prompts before each input. This is useful
577 -p: print classic '>>>' python prompts before each input. This is useful
581 for making documentation, and in conjunction with -o, for producing
578 for making documentation, and in conjunction with -o, for producing
582 doctest-ready output.
579 doctest-ready output.
583
580
584 -r: (default) print the 'raw' history, i.e. the actual commands you typed.
581 -r: (default) print the 'raw' history, i.e. the actual commands you typed.
585
582
586 -t: print the 'translated' history, as IPython understands it. IPython
583 -t: print the 'translated' history, as IPython understands it. IPython
587 filters your input and converts it all into valid Python source before
584 filters your input and converts it all into valid Python source before
588 executing it (things like magics or aliases are turned into function
585 executing it (things like magics or aliases are turned into function
589 calls, for example). With this option, you'll see the native history
586 calls, for example). With this option, you'll see the native history
590 instead of the user-entered version: '%cd /' will be seen as
587 instead of the user-entered version: '%cd /' will be seen as
591 'get_ipython().magic("%cd /")' instead of '%cd /'.
588 'get_ipython().magic("%cd /")' instead of '%cd /'.
592
589
593 -g: treat the arg as a pattern to grep for in (full) history.
590 -g: treat the arg as a pattern to grep for in (full) history.
594 This includes the saved history (almost all commands ever written).
591 This includes the saved history (almost all commands ever written).
595 Use '%hist -g' to show full saved history (may be very long).
592 Use '%hist -g' to show full saved history (may be very long).
596
593
597 -l: get the last n lines from all sessions. Specify n as a single arg, or
594 -l: get the last n lines from all sessions. Specify n as a single arg, or
598 the default is the last 10 lines.
595 the default is the last 10 lines.
599
596
600 -f FILENAME: instead of printing the output to the screen, redirect it to
597 -f FILENAME: instead of printing the output to the screen, redirect it to
601 the given file. The file is always overwritten, though IPython asks for
598 the given file. The file is always overwritten, though IPython asks for
602 confirmation first if it already exists.
599 confirmation first if it already exists.
603
600
604 Examples
601 Examples
605 --------
602 --------
606 ::
603 ::
607
604
608 In [6]: %hist -n 4 6
605 In [6]: %hist -n 4 6
609 4:a = 12
606 4:a = 12
610 5:print a**2
607 5:print a**2
611
608
612 """
609 """
613
610
614 if not self.shell.displayhook.do_full_cache:
611 if not self.shell.displayhook.do_full_cache:
615 print('This feature is only available if numbered prompts are in use.')
612 print('This feature is only available if numbered prompts are in use.')
616 return
613 return
617 opts,args = self.parse_options(parameter_s,'noprtglf:',mode='string')
614 opts,args = self.parse_options(parameter_s,'noprtglf:',mode='string')
618
615
619 # For brevity
616 # For brevity
620 history_manager = self.shell.history_manager
617 history_manager = self.shell.history_manager
621
618
622 def _format_lineno(session, line):
619 def _format_lineno(session, line):
623 """Helper function to format line numbers properly."""
620 """Helper function to format line numbers properly."""
624 if session in (0, history_manager.session_number):
621 if session in (0, history_manager.session_number):
625 return str(line)
622 return str(line)
626 return "%s/%s" % (session, line)
623 return "%s/%s" % (session, line)
627
624
628 # Check if output to specific file was requested.
625 # Check if output to specific file was requested.
629 try:
626 try:
630 outfname = opts['f']
627 outfname = opts['f']
631 except KeyError:
628 except KeyError:
632 outfile = io.stdout # default
629 outfile = io.stdout # default
633 # We don't want to close stdout at the end!
630 # We don't want to close stdout at the end!
634 close_at_end = False
631 close_at_end = False
635 else:
632 else:
636 if os.path.exists(outfname):
633 if os.path.exists(outfname):
637 if not io.ask_yes_no("File %r exists. Overwrite?" % outfname):
634 if not io.ask_yes_no("File %r exists. Overwrite?" % outfname):
638 print('Aborting.')
635 print('Aborting.')
639 return
636 return
640
637
641 outfile = open(outfname,'w')
638 outfile = open(outfname,'w')
642 close_at_end = True
639 close_at_end = True
643
640
644 print_nums = 'n' in opts
641 print_nums = 'n' in opts
645 get_output = 'o' in opts
642 get_output = 'o' in opts
646 pyprompts = 'p' in opts
643 pyprompts = 'p' in opts
647 # Raw history is the default
644 # Raw history is the default
648 raw = not('t' in opts)
645 raw = not('t' in opts)
649
646
650 default_length = 40
647 default_length = 40
651 pattern = None
648 pattern = None
652
649
653 if 'g' in opts: # Glob search
650 if 'g' in opts: # Glob search
654 pattern = "*" + args + "*" if args else "*"
651 pattern = "*" + args + "*" if args else "*"
655 hist = history_manager.search(pattern, raw=raw, output=get_output)
652 hist = history_manager.search(pattern, raw=raw, output=get_output)
656 elif 'l' in opts: # Get 'tail'
653 elif 'l' in opts: # Get 'tail'
657 try:
654 try:
658 n = int(args)
655 n = int(args)
659 except ValueError, IndexError:
656 except ValueError, IndexError:
660 n = 10
657 n = 10
661 hist = history_manager.get_tail(n, raw=raw, output=get_output)
658 hist = history_manager.get_tail(n, raw=raw, output=get_output)
662 else:
659 else:
663 if args: # Get history by ranges
660 if args: # Get history by ranges
664 hist = history_manager.get_range_by_str(args, raw, get_output)
661 hist = history_manager.get_range_by_str(args, raw, get_output)
665 else: # Just get history for the current session
662 else: # Just get history for the current session
666 hist = history_manager.get_range(raw=raw, output=get_output)
663 hist = history_manager.get_range(raw=raw, output=get_output)
667
664
668 # We could be displaying the entire history, so let's not try to pull it
665 # We could be displaying the entire history, so let's not try to pull it
669 # into a list in memory. Anything that needs more space will just misalign.
666 # into a list in memory. Anything that needs more space will just misalign.
670 width = 4
667 width = 4
671
668
672 for session, lineno, inline in hist:
669 for session, lineno, inline in hist:
673 # Print user history with tabs expanded to 4 spaces. The GUI clients
670 # Print user history with tabs expanded to 4 spaces. The GUI clients
674 # use hard tabs for easier usability in auto-indented code, but we want
671 # use hard tabs for easier usability in auto-indented code, but we want
675 # to produce PEP-8 compliant history for safe pasting into an editor.
672 # to produce PEP-8 compliant history for safe pasting into an editor.
676 if get_output:
673 if get_output:
677 inline, output = inline
674 inline, output = inline
678 inline = inline.expandtabs(4).rstrip()
675 inline = inline.expandtabs(4).rstrip()
679
676
680 multiline = "\n" in inline
677 multiline = "\n" in inline
681 line_sep = '\n' if multiline else ' '
678 line_sep = '\n' if multiline else ' '
682 if print_nums:
679 if print_nums:
683 print('%s:%s' % (_format_lineno(session, lineno).rjust(width),
680 print('%s:%s' % (_format_lineno(session, lineno).rjust(width),
684 line_sep), file=outfile, end='')
681 line_sep), file=outfile, end='')
685 if pyprompts:
682 if pyprompts:
686 print(">>> ", end="", file=outfile)
683 print(">>> ", end="", file=outfile)
687 if multiline:
684 if multiline:
688 inline = "\n... ".join(inline.splitlines()) + "\n..."
685 inline = "\n... ".join(inline.splitlines()) + "\n..."
689 print(inline, file=outfile)
686 print(inline, file=outfile)
690 if get_output and output:
687 if get_output and output:
691 print(output, file=outfile)
688 print(output, file=outfile)
692
689
693 if close_at_end:
690 if close_at_end:
694 outfile.close()
691 outfile.close()
695
692
696
693
697 def magic_rep(self, arg):
694 def magic_rep(self, arg):
698 r""" Repeat a command, or get command to input line for editing
695 r""" Repeat a command, or get command to input line for editing
699
696
700 - %rep (no arguments):
697 - %rep (no arguments):
701
698
702 Place a string version of last computation result (stored in the special '_'
699 Place a string version of last computation result (stored in the special '_'
703 variable) to the next input prompt. Allows you to create elaborate command
700 variable) to the next input prompt. Allows you to create elaborate command
704 lines without using copy-paste::
701 lines without using copy-paste::
705
702
706 In[1]: l = ["hei", "vaan"]
703 In[1]: l = ["hei", "vaan"]
707 In[2]: "".join(l)
704 In[2]: "".join(l)
708 Out[2]: heivaan
705 Out[2]: heivaan
709 In[3]: %rep
706 In[3]: %rep
710 In[4]: heivaan_ <== cursor blinking
707 In[4]: heivaan_ <== cursor blinking
711
708
712 %rep 45
709 %rep 45
713
710
714 Place history line 45 on the next input prompt. Use %hist to find
711 Place history line 45 on the next input prompt. Use %hist to find
715 out the number.
712 out the number.
716
713
717 %rep 1-4
714 %rep 1-4
718
715
719 Combine the specified lines into one cell, and place it on the next
716 Combine the specified lines into one cell, and place it on the next
720 input prompt. See %history for the slice syntax.
717 input prompt. See %history for the slice syntax.
721
718
722 %rep foo+bar
719 %rep foo+bar
723
720
724 If foo+bar can be evaluated in the user namespace, the result is
721 If foo+bar can be evaluated in the user namespace, the result is
725 placed at the next input prompt. Otherwise, the history is searched
722 placed at the next input prompt. Otherwise, the history is searched
726 for lines which contain that substring, and the most recent one is
723 for lines which contain that substring, and the most recent one is
727 placed at the next input prompt.
724 placed at the next input prompt.
728 """
725 """
729 if not arg: # Last output
726 if not arg: # Last output
730 self.set_next_input(str(self.shell.user_ns["_"]))
727 self.set_next_input(str(self.shell.user_ns["_"]))
731 return
728 return
732 # Get history range
729 # Get history range
733 histlines = self.history_manager.get_range_by_str(arg)
730 histlines = self.history_manager.get_range_by_str(arg)
734 cmd = "\n".join(x[2] for x in histlines)
731 cmd = "\n".join(x[2] for x in histlines)
735 if cmd:
732 if cmd:
736 self.set_next_input(cmd.rstrip())
733 self.set_next_input(cmd.rstrip())
737 return
734 return
738
735
739 try: # Variable in user namespace
736 try: # Variable in user namespace
740 cmd = str(eval(arg, self.shell.user_ns))
737 cmd = str(eval(arg, self.shell.user_ns))
741 except Exception: # Search for term in history
738 except Exception: # Search for term in history
742 histlines = self.history_manager.search("*"+arg+"*")
739 histlines = self.history_manager.search("*"+arg+"*")
743 for h in reversed([x[2] for x in histlines]):
740 for h in reversed([x[2] for x in histlines]):
744 if 'rep' in h:
741 if 'rep' in h:
745 continue
742 continue
746 self.set_next_input(h.rstrip())
743 self.set_next_input(h.rstrip())
747 return
744 return
748 else:
745 else:
749 self.set_next_input(cmd.rstrip())
746 self.set_next_input(cmd.rstrip())
750 print("Couldn't evaluate or find in history:", arg)
747 print("Couldn't evaluate or find in history:", arg)
751
748
752 def magic_rerun(self, parameter_s=''):
749 def magic_rerun(self, parameter_s=''):
753 """Re-run previous input
750 """Re-run previous input
754
751
755 By default, you can specify ranges of input history to be repeated
752 By default, you can specify ranges of input history to be repeated
756 (as with %history). With no arguments, it will repeat the last line.
753 (as with %history). With no arguments, it will repeat the last line.
757
754
758 Options:
755 Options:
759
756
760 -l <n> : Repeat the last n lines of input, not including the
757 -l <n> : Repeat the last n lines of input, not including the
761 current command.
758 current command.
762
759
763 -g foo : Repeat the most recent line which contains foo
760 -g foo : Repeat the most recent line which contains foo
764 """
761 """
765 opts, args = self.parse_options(parameter_s, 'l:g:', mode='string')
762 opts, args = self.parse_options(parameter_s, 'l:g:', mode='string')
766 if "l" in opts: # Last n lines
763 if "l" in opts: # Last n lines
767 n = int(opts['l'])
764 n = int(opts['l'])
768 hist = self.history_manager.get_tail(n)
765 hist = self.history_manager.get_tail(n)
769 elif "g" in opts: # Search
766 elif "g" in opts: # Search
770 p = "*"+opts['g']+"*"
767 p = "*"+opts['g']+"*"
771 hist = list(self.history_manager.search(p))
768 hist = list(self.history_manager.search(p))
772 for l in reversed(hist):
769 for l in reversed(hist):
773 if "rerun" not in l[2]:
770 if "rerun" not in l[2]:
774 hist = [l] # The last match which isn't a %rerun
771 hist = [l] # The last match which isn't a %rerun
775 break
772 break
776 else:
773 else:
777 hist = [] # No matches except %rerun
774 hist = [] # No matches except %rerun
778 elif args: # Specify history ranges
775 elif args: # Specify history ranges
779 hist = self.history_manager.get_range_by_str(args)
776 hist = self.history_manager.get_range_by_str(args)
780 else: # Last line
777 else: # Last line
781 hist = self.history_manager.get_tail(1)
778 hist = self.history_manager.get_tail(1)
782 hist = [x[2] for x in hist]
779 hist = [x[2] for x in hist]
783 if not hist:
780 if not hist:
784 print("No lines in history match specification")
781 print("No lines in history match specification")
785 return
782 return
786 histlines = "\n".join(hist)
783 histlines = "\n".join(hist)
787 print("=== Executing: ===")
784 print("=== Executing: ===")
788 print(histlines)
785 print(histlines)
789 print("=== Output: ===")
786 print("=== Output: ===")
790 self.run_cell("\n".join(hist), store_history=False)
787 self.run_cell("\n".join(hist), store_history=False)
791
788
792
789
793 def init_ipython(ip):
790 def init_ipython(ip):
794 ip.define_magic("rep", magic_rep)
791 ip.define_magic("rep", magic_rep)
795 ip.define_magic("recall", magic_rep)
792 ip.define_magic("recall", magic_rep)
796 ip.define_magic("rerun", magic_rerun)
793 ip.define_magic("rerun", magic_rerun)
797 ip.define_magic("hist",magic_history) # Alternative name
794 ip.define_magic("hist",magic_history) # Alternative name
798 ip.define_magic("history",magic_history)
795 ip.define_magic("history",magic_history)
799
796
800 # XXX - ipy_completers are in quarantine, need to be updated to new apis
797 # XXX - ipy_completers are in quarantine, need to be updated to new apis
801 #import ipy_completers
798 #import ipy_completers
802 #ipy_completers.quick_completer('%hist' ,'-g -t -r -n')
799 #ipy_completers.quick_completer('%hist' ,'-g -t -r -n')
@@ -1,2542 +1,2553
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
19
20 import __builtin__
20 import __builtin__
21 import __future__
21 import __future__
22 import abc
22 import abc
23 import ast
23 import ast
24 import atexit
24 import atexit
25 import codeop
25 import codeop
26 import inspect
26 import inspect
27 import os
27 import os
28 import re
28 import re
29 import sys
29 import sys
30 import tempfile
30 import tempfile
31 import types
31 import types
32 from contextlib import nested
32 from contextlib import nested
33
33
34 from IPython.config.configurable import SingletonConfigurable
34 from IPython.config.configurable import SingletonConfigurable
35 from IPython.core import debugger, oinspect
35 from IPython.core import debugger, oinspect
36 from IPython.core import history as ipcorehist
36 from IPython.core import history as ipcorehist
37 from IPython.core import page
37 from IPython.core import page
38 from IPython.core import prefilter
38 from IPython.core import prefilter
39 from IPython.core import shadowns
39 from IPython.core import shadowns
40 from IPython.core import ultratb
40 from IPython.core import ultratb
41 from IPython.core.alias import AliasManager, AliasError
41 from IPython.core.alias import AliasManager, AliasError
42 from IPython.core.autocall import ExitAutocall
42 from IPython.core.autocall import ExitAutocall
43 from IPython.core.builtin_trap import BuiltinTrap
43 from IPython.core.builtin_trap import BuiltinTrap
44 from IPython.core.compilerop import CachingCompiler
44 from IPython.core.compilerop import CachingCompiler
45 from IPython.core.display_trap import DisplayTrap
45 from IPython.core.display_trap import DisplayTrap
46 from IPython.core.displayhook import DisplayHook
46 from IPython.core.displayhook import DisplayHook
47 from IPython.core.displaypub import DisplayPublisher
47 from IPython.core.displaypub import DisplayPublisher
48 from IPython.core.error import TryNext, UsageError
48 from IPython.core.error import TryNext, UsageError
49 from IPython.core.extensions import ExtensionManager
49 from IPython.core.extensions import ExtensionManager
50 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
50 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
51 from IPython.core.formatters import DisplayFormatter
51 from IPython.core.formatters import DisplayFormatter
52 from IPython.core.history import HistoryManager
52 from IPython.core.history import HistoryManager
53 from IPython.core.inputsplitter import IPythonInputSplitter
53 from IPython.core.inputsplitter import IPythonInputSplitter
54 from IPython.core.logger import Logger
54 from IPython.core.logger import Logger
55 from IPython.core.macro import Macro
55 from IPython.core.macro import Macro
56 from IPython.core.magic import Magic
56 from IPython.core.magic import Magic
57 from IPython.core.newapplication import ProfileDir
57 from IPython.core.payload import PayloadManager
58 from IPython.core.payload import PayloadManager
58 from IPython.core.plugin import PluginManager
59 from IPython.core.plugin import PluginManager
59 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
60 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
60 from IPython.external.Itpl import ItplNS
61 from IPython.external.Itpl import ItplNS
61 from IPython.utils import PyColorize
62 from IPython.utils import PyColorize
62 from IPython.utils import io
63 from IPython.utils import io
63 from IPython.utils.doctestreload import doctest_reload
64 from IPython.utils.doctestreload import doctest_reload
64 from IPython.utils.io import ask_yes_no, rprint
65 from IPython.utils.io import ask_yes_no, rprint
65 from IPython.utils.ipstruct import Struct
66 from IPython.utils.ipstruct import Struct
66 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
67 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
67 from IPython.utils.pickleshare import PickleShareDB
68 from IPython.utils.pickleshare import PickleShareDB
68 from IPython.utils.process import system, getoutput
69 from IPython.utils.process import system, getoutput
69 from IPython.utils.strdispatch import StrDispatch
70 from IPython.utils.strdispatch import StrDispatch
70 from IPython.utils.syspathcontext import prepended_to_syspath
71 from IPython.utils.syspathcontext import prepended_to_syspath
71 from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList
72 from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList
72 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
73 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
73 List, Unicode, Instance, Type)
74 List, Unicode, Instance, Type)
74 from IPython.utils.warn import warn, error, fatal
75 from IPython.utils.warn import warn, error, fatal
75 import IPython.core.hooks
76 import IPython.core.hooks
76
77
77 #-----------------------------------------------------------------------------
78 #-----------------------------------------------------------------------------
78 # Globals
79 # Globals
79 #-----------------------------------------------------------------------------
80 #-----------------------------------------------------------------------------
80
81
81 # compiled regexps for autoindent management
82 # compiled regexps for autoindent management
82 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
83 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
83
84
84 #-----------------------------------------------------------------------------
85 #-----------------------------------------------------------------------------
85 # Utilities
86 # Utilities
86 #-----------------------------------------------------------------------------
87 #-----------------------------------------------------------------------------
87
88
88 # store the builtin raw_input globally, and use this always, in case user code
89 # store the builtin raw_input globally, and use this always, in case user code
89 # overwrites it (like wx.py.PyShell does)
90 # overwrites it (like wx.py.PyShell does)
90 raw_input_original = raw_input
91 raw_input_original = raw_input
91
92
92 def softspace(file, newvalue):
93 def softspace(file, newvalue):
93 """Copied from code.py, to remove the dependency"""
94 """Copied from code.py, to remove the dependency"""
94
95
95 oldvalue = 0
96 oldvalue = 0
96 try:
97 try:
97 oldvalue = file.softspace
98 oldvalue = file.softspace
98 except AttributeError:
99 except AttributeError:
99 pass
100 pass
100 try:
101 try:
101 file.softspace = newvalue
102 file.softspace = newvalue
102 except (AttributeError, TypeError):
103 except (AttributeError, TypeError):
103 # "attribute-less object" or "read-only attributes"
104 # "attribute-less object" or "read-only attributes"
104 pass
105 pass
105 return oldvalue
106 return oldvalue
106
107
107
108
108 def no_op(*a, **kw): pass
109 def no_op(*a, **kw): pass
109
110
110 class SpaceInInput(Exception): pass
111 class SpaceInInput(Exception): pass
111
112
112 class Bunch: pass
113 class Bunch: pass
113
114
114
115
115 def get_default_colors():
116 def get_default_colors():
116 if sys.platform=='darwin':
117 if sys.platform=='darwin':
117 return "LightBG"
118 return "LightBG"
118 elif os.name=='nt':
119 elif os.name=='nt':
119 return 'Linux'
120 return 'Linux'
120 else:
121 else:
121 return 'Linux'
122 return 'Linux'
122
123
123
124
124 class SeparateStr(Str):
125 class SeparateStr(Str):
125 """A Str subclass to validate separate_in, separate_out, etc.
126 """A Str subclass to validate separate_in, separate_out, etc.
126
127
127 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
128 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
128 """
129 """
129
130
130 def validate(self, obj, value):
131 def validate(self, obj, value):
131 if value == '0': value = ''
132 if value == '0': value = ''
132 value = value.replace('\\n','\n')
133 value = value.replace('\\n','\n')
133 return super(SeparateStr, self).validate(obj, value)
134 return super(SeparateStr, self).validate(obj, value)
134
135
135
136
136 class ReadlineNoRecord(object):
137 class ReadlineNoRecord(object):
137 """Context manager to execute some code, then reload readline history
138 """Context manager to execute some code, then reload readline history
138 so that interactive input to the code doesn't appear when pressing up."""
139 so that interactive input to the code doesn't appear when pressing up."""
139 def __init__(self, shell):
140 def __init__(self, shell):
140 self.shell = shell
141 self.shell = shell
141 self._nested_level = 0
142 self._nested_level = 0
142
143
143 def __enter__(self):
144 def __enter__(self):
144 if self._nested_level == 0:
145 if self._nested_level == 0:
145 try:
146 try:
146 self.orig_length = self.current_length()
147 self.orig_length = self.current_length()
147 self.readline_tail = self.get_readline_tail()
148 self.readline_tail = self.get_readline_tail()
148 except (AttributeError, IndexError): # Can fail with pyreadline
149 except (AttributeError, IndexError): # Can fail with pyreadline
149 self.orig_length, self.readline_tail = 999999, []
150 self.orig_length, self.readline_tail = 999999, []
150 self._nested_level += 1
151 self._nested_level += 1
151
152
152 def __exit__(self, type, value, traceback):
153 def __exit__(self, type, value, traceback):
153 self._nested_level -= 1
154 self._nested_level -= 1
154 if self._nested_level == 0:
155 if self._nested_level == 0:
155 # Try clipping the end if it's got longer
156 # Try clipping the end if it's got longer
156 try:
157 try:
157 e = self.current_length() - self.orig_length
158 e = self.current_length() - self.orig_length
158 if e > 0:
159 if e > 0:
159 for _ in range(e):
160 for _ in range(e):
160 self.shell.readline.remove_history_item(self.orig_length)
161 self.shell.readline.remove_history_item(self.orig_length)
161
162
162 # If it still doesn't match, just reload readline history.
163 # If it still doesn't match, just reload readline history.
163 if self.current_length() != self.orig_length \
164 if self.current_length() != self.orig_length \
164 or self.get_readline_tail() != self.readline_tail:
165 or self.get_readline_tail() != self.readline_tail:
165 self.shell.refill_readline_hist()
166 self.shell.refill_readline_hist()
166 except (AttributeError, IndexError):
167 except (AttributeError, IndexError):
167 pass
168 pass
168 # Returning False will cause exceptions to propagate
169 # Returning False will cause exceptions to propagate
169 return False
170 return False
170
171
171 def current_length(self):
172 def current_length(self):
172 return self.shell.readline.get_current_history_length()
173 return self.shell.readline.get_current_history_length()
173
174
174 def get_readline_tail(self, n=10):
175 def get_readline_tail(self, n=10):
175 """Get the last n items in readline history."""
176 """Get the last n items in readline history."""
176 end = self.shell.readline.get_current_history_length() + 1
177 end = self.shell.readline.get_current_history_length() + 1
177 start = max(end-n, 1)
178 start = max(end-n, 1)
178 ghi = self.shell.readline.get_history_item
179 ghi = self.shell.readline.get_history_item
179 return [ghi(x) for x in range(start, end)]
180 return [ghi(x) for x in range(start, end)]
180
181
181
182
182 _autocall_help = """
183 _autocall_help = """
183 Make IPython automatically call any callable object even if
184 Make IPython automatically call any callable object even if
184 you didn't type explicit parentheses. For example, 'str 43' becomes 'str(43)'
185 you didn't type explicit parentheses. For example, 'str 43' becomes 'str(43)'
185 automatically. The value can be '0' to disable the feature, '1' for 'smart'
186 automatically. The value can be '0' to disable the feature, '1' for 'smart'
186 autocall, where it is not applied if there are no more arguments on the line,
187 autocall, where it is not applied if there are no more arguments on the line,
187 and '2' for 'full' autocall, where all callable objects are automatically
188 and '2' for 'full' autocall, where all callable objects are automatically
188 called (even if no arguments are present). The default is '1'.
189 called (even if no arguments are present). The default is '1'.
189 """
190 """
190
191
191 #-----------------------------------------------------------------------------
192 #-----------------------------------------------------------------------------
192 # Main IPython class
193 # Main IPython class
193 #-----------------------------------------------------------------------------
194 #-----------------------------------------------------------------------------
194
195
195 class InteractiveShell(SingletonConfigurable, Magic):
196 class InteractiveShell(SingletonConfigurable, Magic):
196 """An enhanced, interactive shell for Python."""
197 """An enhanced, interactive shell for Python."""
197
198
198 _instance = None
199 _instance = None
199
200
200 autocall = Enum((0,1,2), default_value=1, config=True, help=
201 autocall = Enum((0,1,2), default_value=1, config=True, help=
201 """
202 """
202 Make IPython automatically call any callable object even if you didn't
203 Make IPython automatically call any callable object even if you didn't
203 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
204 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
204 automatically. The value can be '0' to disable the feature, '1' for
205 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
206 '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
207 arguments on the line, and '2' for 'full' autocall, where all callable
207 objects are automatically called (even if no arguments are present).
208 objects are automatically called (even if no arguments are present).
208 The default is '1'.
209 The default is '1'.
209 """
210 """
210 )
211 )
211 # TODO: remove all autoindent logic and put into frontends.
212 # TODO: remove all autoindent logic and put into frontends.
212 # We can't do this yet because even runlines uses the autoindent.
213 # We can't do this yet because even runlines uses the autoindent.
213 autoindent = CBool(True, config=True, help=
214 autoindent = CBool(True, config=True, help=
214 """
215 """
215 Autoindent IPython code entered interactively.
216 Autoindent IPython code entered interactively.
216 """
217 """
217 )
218 )
218 automagic = CBool(True, config=True, help=
219 automagic = CBool(True, config=True, help=
219 """
220 """
220 Enable magic commands to be called without the leading %.
221 Enable magic commands to be called without the leading %.
221 """
222 """
222 )
223 )
223 cache_size = Int(1000, config=True, help=
224 cache_size = Int(1000, config=True, help=
224 """
225 """
225 Set the size of the output cache. The default is 1000, you can
226 Set the size of the output cache. The default is 1000, you can
226 change it permanently in your config file. Setting it to 0 completely
227 change it permanently in your config file. Setting it to 0 completely
227 disables the caching system, and the minimum value accepted is 20 (if
228 disables the caching system, and the minimum value accepted is 20 (if
228 you provide a value less than 20, it is reset to 0 and a warning is
229 you provide a value less than 20, it is reset to 0 and a warning is
229 issued). This limit is defined because otherwise you'll spend more
230 issued). This limit is defined because otherwise you'll spend more
230 time re-flushing a too small cache than working
231 time re-flushing a too small cache than working
231 """
232 """
232 )
233 )
233 color_info = CBool(True, config=True, help=
234 color_info = CBool(True, config=True, help=
234 """
235 """
235 Use colors for displaying information about objects. Because this
236 Use colors for displaying information about objects. Because this
236 information is passed through a pager (like 'less'), and some pagers
237 information is passed through a pager (like 'less'), and some pagers
237 get confused with color codes, this capability can be turned off.
238 get confused with color codes, this capability can be turned off.
238 """
239 """
239 )
240 )
240 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
241 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
241 default_value=get_default_colors(), config=True)
242 default_value=get_default_colors(), config=True,
243 help="Set the color scheme (NoColor, Linux, and LightBG)."
244 )
242 debug = CBool(False, config=True)
245 debug = CBool(False, config=True)
243 deep_reload = CBool(False, config=True, help=
246 deep_reload = CBool(False, config=True, help=
244 """
247 """
245 Enable deep (recursive) reloading by default. IPython can use the
248 Enable deep (recursive) reloading by default. IPython can use the
246 deep_reload module which reloads changes in modules recursively (it
249 deep_reload module which reloads changes in modules recursively (it
247 replaces the reload() function, so you don't need to change anything to
250 replaces the reload() function, so you don't need to change anything to
248 use it). deep_reload() forces a full reload of modules whose code may
251 use it). deep_reload() forces a full reload of modules whose code may
249 have changed, which the default reload() function does not. When
252 have changed, which the default reload() function does not. When
250 deep_reload is off, IPython will use the normal reload(), but
253 deep_reload is off, IPython will use the normal reload(), but
251 deep_reload will still be available as dreload().
254 deep_reload will still be available as dreload().
252 """
255 """
253 )
256 )
254 display_formatter = Instance(DisplayFormatter)
257 display_formatter = Instance(DisplayFormatter)
255 displayhook_class = Type(DisplayHook)
258 displayhook_class = Type(DisplayHook)
256 display_pub_class = Type(DisplayPublisher)
259 display_pub_class = Type(DisplayPublisher)
257
260
258 exit_now = CBool(False)
261 exit_now = CBool(False)
259 exiter = Instance(ExitAutocall)
262 exiter = Instance(ExitAutocall)
260 def _exiter_default(self):
263 def _exiter_default(self):
261 return ExitAutocall(self)
264 return ExitAutocall(self)
262 # Monotonically increasing execution counter
265 # Monotonically increasing execution counter
263 execution_count = Int(1)
266 execution_count = Int(1)
264 filename = Unicode("<ipython console>")
267 filename = Unicode("<ipython console>")
265 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
268 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
266
269
267 # Input splitter, to split entire cells of input into either individual
270 # Input splitter, to split entire cells of input into either individual
268 # interactive statements or whole blocks.
271 # interactive statements or whole blocks.
269 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
272 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
270 (), {})
273 (), {})
271 logstart = CBool(False, config=True, help=
274 logstart = CBool(False, config=True, help=
272 """
275 """
273 Start logging to the default log file.
276 Start logging to the default log file.
274 """
277 """
275 )
278 )
276 logfile = Unicode('', config=True, help=
279 logfile = Unicode('', config=True, help=
277 """
280 """
278 The name of the logfile to use.
281 The name of the logfile to use.
279 """
282 """
280 )
283 )
281 logappend = Unicode('', config=True, help=
284 logappend = Unicode('', config=True, help=
282 """
285 """
283 Start logging to the given file in append mode.
286 Start logging to the given file in append mode.
284 """
287 """
285 )
288 )
286 object_info_string_level = Enum((0,1,2), default_value=0,
289 object_info_string_level = Enum((0,1,2), default_value=0,
287 config=True)
290 config=True)
288 pdb = CBool(False, config=True, help=
291 pdb = CBool(False, config=True, help=
289 """
292 """
290 Automatically call the pdb debugger after every exception.
293 Automatically call the pdb debugger after every exception.
291 """
294 """
292 )
295 )
293
296
294 profile = Unicode('', config=True)
295 prompt_in1 = Str('In [\\#]: ', config=True)
297 prompt_in1 = Str('In [\\#]: ', config=True)
296 prompt_in2 = Str(' .\\D.: ', config=True)
298 prompt_in2 = Str(' .\\D.: ', config=True)
297 prompt_out = Str('Out[\\#]: ', config=True)
299 prompt_out = Str('Out[\\#]: ', config=True)
298 prompts_pad_left = CBool(True, config=True)
300 prompts_pad_left = CBool(True, config=True)
299 quiet = CBool(False, config=True)
301 quiet = CBool(False, config=True)
300
302
301 history_length = Int(10000, config=True)
303 history_length = Int(10000, config=True)
302
304
303 # The readline stuff will eventually be moved to the terminal subclass
305 # The readline stuff will eventually be moved to the terminal subclass
304 # but for now, we can't do that as readline is welded in everywhere.
306 # but for now, we can't do that as readline is welded in everywhere.
305 readline_use = CBool(True, config=True)
307 readline_use = CBool(True, config=True)
306 readline_merge_completions = CBool(True, config=True)
308 readline_merge_completions = CBool(True, config=True)
307 readline_omit__names = Enum((0,1,2), default_value=2, config=True)
309 readline_omit__names = Enum((0,1,2), default_value=2, config=True)
308 readline_remove_delims = Str('-/~', config=True)
310 readline_remove_delims = Str('-/~', config=True)
309 # don't use \M- bindings by default, because they
311 # don't use \M- bindings by default, because they
310 # conflict with 8-bit encodings. See gh-58,gh-88
312 # conflict with 8-bit encodings. See gh-58,gh-88
311 readline_parse_and_bind = List([
313 readline_parse_and_bind = List([
312 'tab: complete',
314 'tab: complete',
313 '"\C-l": clear-screen',
315 '"\C-l": clear-screen',
314 'set show-all-if-ambiguous on',
316 'set show-all-if-ambiguous on',
315 '"\C-o": tab-insert',
317 '"\C-o": tab-insert',
316 '"\C-r": reverse-search-history',
318 '"\C-r": reverse-search-history',
317 '"\C-s": forward-search-history',
319 '"\C-s": forward-search-history',
318 '"\C-p": history-search-backward',
320 '"\C-p": history-search-backward',
319 '"\C-n": history-search-forward',
321 '"\C-n": history-search-forward',
320 '"\e[A": history-search-backward',
322 '"\e[A": history-search-backward',
321 '"\e[B": history-search-forward',
323 '"\e[B": history-search-forward',
322 '"\C-k": kill-line',
324 '"\C-k": kill-line',
323 '"\C-u": unix-line-discard',
325 '"\C-u": unix-line-discard',
324 ], allow_none=False, config=True)
326 ], allow_none=False, config=True)
325
327
326 # TODO: this part of prompt management should be moved to the frontends.
328 # TODO: this part of prompt management should be moved to the frontends.
327 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
329 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
328 separate_in = SeparateStr('\n', config=True)
330 separate_in = SeparateStr('\n', config=True)
329 separate_out = SeparateStr('', config=True)
331 separate_out = SeparateStr('', config=True)
330 separate_out2 = SeparateStr('', config=True)
332 separate_out2 = SeparateStr('', config=True)
331 wildcards_case_sensitive = CBool(True, config=True)
333 wildcards_case_sensitive = CBool(True, config=True)
332 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
334 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
333 default_value='Context', config=True)
335 default_value='Context', config=True)
334
336
335 # Subcomponents of InteractiveShell
337 # Subcomponents of InteractiveShell
336 alias_manager = Instance('IPython.core.alias.AliasManager')
338 alias_manager = Instance('IPython.core.alias.AliasManager')
337 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
339 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
338 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
340 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
339 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
341 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
340 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
342 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
341 plugin_manager = Instance('IPython.core.plugin.PluginManager')
343 plugin_manager = Instance('IPython.core.plugin.PluginManager')
342 payload_manager = Instance('IPython.core.payload.PayloadManager')
344 payload_manager = Instance('IPython.core.payload.PayloadManager')
343 history_manager = Instance('IPython.core.history.HistoryManager')
345 history_manager = Instance('IPython.core.history.HistoryManager')
344
346
347 profile_dir = Instance('IPython.core.newapplication.ProfileDir')
348 @property
349 def profile(self):
350 if self.profile_dir is not None:
351 name = os.path.basename(self.profile_dir.location)
352 return name.replace('profile_','')
353
354
345 # Private interface
355 # Private interface
346 _post_execute = Instance(dict)
356 _post_execute = Instance(dict)
347
357
348 def __init__(self, config=None, ipython_dir=None,
358 def __init__(self, config=None, ipython_dir=None, profile_dir=None,
349 user_ns=None, user_global_ns=None,
359 user_ns=None, user_global_ns=None,
350 custom_exceptions=((), None)):
360 custom_exceptions=((), None)):
351
361
352 # This is where traits with a config_key argument are updated
362 # This is where traits with a config_key argument are updated
353 # from the values on config.
363 # from the values on config.
354 super(InteractiveShell, self).__init__(config=config)
364 super(InteractiveShell, self).__init__(config=config)
355
365
356 # These are relatively independent and stateless
366 # These are relatively independent and stateless
357 self.init_ipython_dir(ipython_dir)
367 self.init_ipython_dir(ipython_dir)
368 self.init_profile_dir(profile_dir)
358 self.init_instance_attrs()
369 self.init_instance_attrs()
359 self.init_environment()
370 self.init_environment()
360
371
361 # Create namespaces (user_ns, user_global_ns, etc.)
372 # Create namespaces (user_ns, user_global_ns, etc.)
362 self.init_create_namespaces(user_ns, user_global_ns)
373 self.init_create_namespaces(user_ns, user_global_ns)
363 # This has to be done after init_create_namespaces because it uses
374 # This has to be done after init_create_namespaces because it uses
364 # something in self.user_ns, but before init_sys_modules, which
375 # something in self.user_ns, but before init_sys_modules, which
365 # is the first thing to modify sys.
376 # is the first thing to modify sys.
366 # TODO: When we override sys.stdout and sys.stderr before this class
377 # TODO: When we override sys.stdout and sys.stderr before this class
367 # is created, we are saving the overridden ones here. Not sure if this
378 # is created, we are saving the overridden ones here. Not sure if this
368 # is what we want to do.
379 # is what we want to do.
369 self.save_sys_module_state()
380 self.save_sys_module_state()
370 self.init_sys_modules()
381 self.init_sys_modules()
371
382
372 # While we're trying to have each part of the code directly access what
383 # While we're trying to have each part of the code directly access what
373 # it needs without keeping redundant references to objects, we have too
384 # it needs without keeping redundant references to objects, we have too
374 # much legacy code that expects ip.db to exist.
385 # much legacy code that expects ip.db to exist.
375 self.db = PickleShareDB(os.path.join(self.ipython_dir, 'db'))
386 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
376
387
377 self.init_history()
388 self.init_history()
378 self.init_encoding()
389 self.init_encoding()
379 self.init_prefilter()
390 self.init_prefilter()
380
391
381 Magic.__init__(self, self)
392 Magic.__init__(self, self)
382
393
383 self.init_syntax_highlighting()
394 self.init_syntax_highlighting()
384 self.init_hooks()
395 self.init_hooks()
385 self.init_pushd_popd_magic()
396 self.init_pushd_popd_magic()
386 # self.init_traceback_handlers use to be here, but we moved it below
397 # self.init_traceback_handlers use to be here, but we moved it below
387 # because it and init_io have to come after init_readline.
398 # because it and init_io have to come after init_readline.
388 self.init_user_ns()
399 self.init_user_ns()
389 self.init_logger()
400 self.init_logger()
390 self.init_alias()
401 self.init_alias()
391 self.init_builtins()
402 self.init_builtins()
392
403
393 # pre_config_initialization
404 # pre_config_initialization
394
405
395 # The next section should contain everything that was in ipmaker.
406 # The next section should contain everything that was in ipmaker.
396 self.init_logstart()
407 self.init_logstart()
397
408
398 # The following was in post_config_initialization
409 # The following was in post_config_initialization
399 self.init_inspector()
410 self.init_inspector()
400 # init_readline() must come before init_io(), because init_io uses
411 # init_readline() must come before init_io(), because init_io uses
401 # readline related things.
412 # readline related things.
402 self.init_readline()
413 self.init_readline()
403 # init_completer must come after init_readline, because it needs to
414 # init_completer must come after init_readline, because it needs to
404 # know whether readline is present or not system-wide to configure the
415 # know whether readline is present or not system-wide to configure the
405 # completers, since the completion machinery can now operate
416 # completers, since the completion machinery can now operate
406 # independently of readline (e.g. over the network)
417 # independently of readline (e.g. over the network)
407 self.init_completer()
418 self.init_completer()
408 # TODO: init_io() needs to happen before init_traceback handlers
419 # TODO: init_io() needs to happen before init_traceback handlers
409 # because the traceback handlers hardcode the stdout/stderr streams.
420 # because the traceback handlers hardcode the stdout/stderr streams.
410 # This logic in in debugger.Pdb and should eventually be changed.
421 # This logic in in debugger.Pdb and should eventually be changed.
411 self.init_io()
422 self.init_io()
412 self.init_traceback_handlers(custom_exceptions)
423 self.init_traceback_handlers(custom_exceptions)
413 self.init_prompts()
424 self.init_prompts()
414 self.init_display_formatter()
425 self.init_display_formatter()
415 self.init_display_pub()
426 self.init_display_pub()
416 self.init_displayhook()
427 self.init_displayhook()
417 self.init_reload_doctest()
428 self.init_reload_doctest()
418 self.init_magics()
429 self.init_magics()
419 self.init_pdb()
430 self.init_pdb()
420 self.init_extension_manager()
431 self.init_extension_manager()
421 self.init_plugin_manager()
432 self.init_plugin_manager()
422 self.init_payload()
433 self.init_payload()
423 self.hooks.late_startup_hook()
434 self.hooks.late_startup_hook()
424 atexit.register(self.atexit_operations)
435 atexit.register(self.atexit_operations)
425
436
426 def get_ipython(self):
437 def get_ipython(self):
427 """Return the currently running IPython instance."""
438 """Return the currently running IPython instance."""
428 return self
439 return self
429
440
430 #-------------------------------------------------------------------------
441 #-------------------------------------------------------------------------
431 # Trait changed handlers
442 # Trait changed handlers
432 #-------------------------------------------------------------------------
443 #-------------------------------------------------------------------------
433
444
434 def _ipython_dir_changed(self, name, new):
445 def _ipython_dir_changed(self, name, new):
435 if not os.path.isdir(new):
446 if not os.path.isdir(new):
436 os.makedirs(new, mode = 0777)
447 os.makedirs(new, mode = 0777)
437
448
438 def set_autoindent(self,value=None):
449 def set_autoindent(self,value=None):
439 """Set the autoindent flag, checking for readline support.
450 """Set the autoindent flag, checking for readline support.
440
451
441 If called with no arguments, it acts as a toggle."""
452 If called with no arguments, it acts as a toggle."""
442
453
443 if not self.has_readline:
454 if not self.has_readline:
444 if os.name == 'posix':
455 if os.name == 'posix':
445 warn("The auto-indent feature requires the readline library")
456 warn("The auto-indent feature requires the readline library")
446 self.autoindent = 0
457 self.autoindent = 0
447 return
458 return
448 if value is None:
459 if value is None:
449 self.autoindent = not self.autoindent
460 self.autoindent = not self.autoindent
450 else:
461 else:
451 self.autoindent = value
462 self.autoindent = value
452
463
453 #-------------------------------------------------------------------------
464 #-------------------------------------------------------------------------
454 # init_* methods called by __init__
465 # init_* methods called by __init__
455 #-------------------------------------------------------------------------
466 #-------------------------------------------------------------------------
456
467
457 def init_ipython_dir(self, ipython_dir):
468 def init_ipython_dir(self, ipython_dir):
458 if ipython_dir is not None:
469 if ipython_dir is not None:
459 self.ipython_dir = ipython_dir
470 self.ipython_dir = ipython_dir
460 self.config.Global.ipython_dir = self.ipython_dir
461 return
471 return
462
472
463 if hasattr(self.config.Global, 'ipython_dir'):
473 self.ipython_dir = get_ipython_dir()
464 self.ipython_dir = self.config.Global.ipython_dir
465 else:
466 self.ipython_dir = get_ipython_dir()
467
474
468 # All children can just read this
475 def init_profile_dir(self, profile_dir):
469 self.config.Global.ipython_dir = self.ipython_dir
476 if profile_dir is not None:
477 self.profile_dir = profile_dir
478 return
479 self.profile_dir =\
480 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
470
481
471 def init_instance_attrs(self):
482 def init_instance_attrs(self):
472 self.more = False
483 self.more = False
473
484
474 # command compiler
485 # command compiler
475 self.compile = CachingCompiler()
486 self.compile = CachingCompiler()
476
487
477 # Make an empty namespace, which extension writers can rely on both
488 # Make an empty namespace, which extension writers can rely on both
478 # existing and NEVER being used by ipython itself. This gives them a
489 # existing and NEVER being used by ipython itself. This gives them a
479 # convenient location for storing additional information and state
490 # convenient location for storing additional information and state
480 # their extensions may require, without fear of collisions with other
491 # their extensions may require, without fear of collisions with other
481 # ipython names that may develop later.
492 # ipython names that may develop later.
482 self.meta = Struct()
493 self.meta = Struct()
483
494
484 # Temporary files used for various purposes. Deleted at exit.
495 # Temporary files used for various purposes. Deleted at exit.
485 self.tempfiles = []
496 self.tempfiles = []
486
497
487 # Keep track of readline usage (later set by init_readline)
498 # Keep track of readline usage (later set by init_readline)
488 self.has_readline = False
499 self.has_readline = False
489
500
490 # keep track of where we started running (mainly for crash post-mortem)
501 # keep track of where we started running (mainly for crash post-mortem)
491 # This is not being used anywhere currently.
502 # This is not being used anywhere currently.
492 self.starting_dir = os.getcwd()
503 self.starting_dir = os.getcwd()
493
504
494 # Indentation management
505 # Indentation management
495 self.indent_current_nsp = 0
506 self.indent_current_nsp = 0
496
507
497 # Dict to track post-execution functions that have been registered
508 # Dict to track post-execution functions that have been registered
498 self._post_execute = {}
509 self._post_execute = {}
499
510
500 def init_environment(self):
511 def init_environment(self):
501 """Any changes we need to make to the user's environment."""
512 """Any changes we need to make to the user's environment."""
502 pass
513 pass
503
514
504 def init_encoding(self):
515 def init_encoding(self):
505 # Get system encoding at startup time. Certain terminals (like Emacs
516 # Get system encoding at startup time. Certain terminals (like Emacs
506 # under Win32 have it set to None, and we need to have a known valid
517 # under Win32 have it set to None, and we need to have a known valid
507 # encoding to use in the raw_input() method
518 # encoding to use in the raw_input() method
508 try:
519 try:
509 self.stdin_encoding = sys.stdin.encoding or 'ascii'
520 self.stdin_encoding = sys.stdin.encoding or 'ascii'
510 except AttributeError:
521 except AttributeError:
511 self.stdin_encoding = 'ascii'
522 self.stdin_encoding = 'ascii'
512
523
513 def init_syntax_highlighting(self):
524 def init_syntax_highlighting(self):
514 # Python source parser/formatter for syntax highlighting
525 # Python source parser/formatter for syntax highlighting
515 pyformat = PyColorize.Parser().format
526 pyformat = PyColorize.Parser().format
516 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
527 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
517
528
518 def init_pushd_popd_magic(self):
529 def init_pushd_popd_magic(self):
519 # for pushd/popd management
530 # for pushd/popd management
520 try:
531 try:
521 self.home_dir = get_home_dir()
532 self.home_dir = get_home_dir()
522 except HomeDirError, msg:
533 except HomeDirError, msg:
523 fatal(msg)
534 fatal(msg)
524
535
525 self.dir_stack = []
536 self.dir_stack = []
526
537
527 def init_logger(self):
538 def init_logger(self):
528 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
539 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
529 logmode='rotate')
540 logmode='rotate')
530
541
531 def init_logstart(self):
542 def init_logstart(self):
532 """Initialize logging in case it was requested at the command line.
543 """Initialize logging in case it was requested at the command line.
533 """
544 """
534 if self.logappend:
545 if self.logappend:
535 self.magic_logstart(self.logappend + ' append')
546 self.magic_logstart(self.logappend + ' append')
536 elif self.logfile:
547 elif self.logfile:
537 self.magic_logstart(self.logfile)
548 self.magic_logstart(self.logfile)
538 elif self.logstart:
549 elif self.logstart:
539 self.magic_logstart()
550 self.magic_logstart()
540
551
541 def init_builtins(self):
552 def init_builtins(self):
542 self.builtin_trap = BuiltinTrap(shell=self)
553 self.builtin_trap = BuiltinTrap(shell=self)
543
554
544 def init_inspector(self):
555 def init_inspector(self):
545 # Object inspector
556 # Object inspector
546 self.inspector = oinspect.Inspector(oinspect.InspectColors,
557 self.inspector = oinspect.Inspector(oinspect.InspectColors,
547 PyColorize.ANSICodeColors,
558 PyColorize.ANSICodeColors,
548 'NoColor',
559 'NoColor',
549 self.object_info_string_level)
560 self.object_info_string_level)
550
561
551 def init_io(self):
562 def init_io(self):
552 # This will just use sys.stdout and sys.stderr. If you want to
563 # This will just use sys.stdout and sys.stderr. If you want to
553 # override sys.stdout and sys.stderr themselves, you need to do that
564 # override sys.stdout and sys.stderr themselves, you need to do that
554 # *before* instantiating this class, because io holds onto
565 # *before* instantiating this class, because io holds onto
555 # references to the underlying streams.
566 # references to the underlying streams.
556 if sys.platform == 'win32' and self.has_readline:
567 if sys.platform == 'win32' and self.has_readline:
557 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
568 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
558 else:
569 else:
559 io.stdout = io.IOStream(sys.stdout)
570 io.stdout = io.IOStream(sys.stdout)
560 io.stderr = io.IOStream(sys.stderr)
571 io.stderr = io.IOStream(sys.stderr)
561
572
562 def init_prompts(self):
573 def init_prompts(self):
563 # TODO: This is a pass for now because the prompts are managed inside
574 # TODO: This is a pass for now because the prompts are managed inside
564 # the DisplayHook. Once there is a separate prompt manager, this
575 # the DisplayHook. Once there is a separate prompt manager, this
565 # will initialize that object and all prompt related information.
576 # will initialize that object and all prompt related information.
566 pass
577 pass
567
578
568 def init_display_formatter(self):
579 def init_display_formatter(self):
569 self.display_formatter = DisplayFormatter(config=self.config)
580 self.display_formatter = DisplayFormatter(config=self.config)
570
581
571 def init_display_pub(self):
582 def init_display_pub(self):
572 self.display_pub = self.display_pub_class(config=self.config)
583 self.display_pub = self.display_pub_class(config=self.config)
573
584
574 def init_displayhook(self):
585 def init_displayhook(self):
575 # Initialize displayhook, set in/out prompts and printing system
586 # Initialize displayhook, set in/out prompts and printing system
576 self.displayhook = self.displayhook_class(
587 self.displayhook = self.displayhook_class(
577 config=self.config,
588 config=self.config,
578 shell=self,
589 shell=self,
579 cache_size=self.cache_size,
590 cache_size=self.cache_size,
580 input_sep = self.separate_in,
591 input_sep = self.separate_in,
581 output_sep = self.separate_out,
592 output_sep = self.separate_out,
582 output_sep2 = self.separate_out2,
593 output_sep2 = self.separate_out2,
583 ps1 = self.prompt_in1,
594 ps1 = self.prompt_in1,
584 ps2 = self.prompt_in2,
595 ps2 = self.prompt_in2,
585 ps_out = self.prompt_out,
596 ps_out = self.prompt_out,
586 pad_left = self.prompts_pad_left
597 pad_left = self.prompts_pad_left
587 )
598 )
588 # This is a context manager that installs/revmoes the displayhook at
599 # This is a context manager that installs/revmoes the displayhook at
589 # the appropriate time.
600 # the appropriate time.
590 self.display_trap = DisplayTrap(hook=self.displayhook)
601 self.display_trap = DisplayTrap(hook=self.displayhook)
591
602
592 def init_reload_doctest(self):
603 def init_reload_doctest(self):
593 # Do a proper resetting of doctest, including the necessary displayhook
604 # Do a proper resetting of doctest, including the necessary displayhook
594 # monkeypatching
605 # monkeypatching
595 try:
606 try:
596 doctest_reload()
607 doctest_reload()
597 except ImportError:
608 except ImportError:
598 warn("doctest module does not exist.")
609 warn("doctest module does not exist.")
599
610
600 #-------------------------------------------------------------------------
611 #-------------------------------------------------------------------------
601 # Things related to injections into the sys module
612 # Things related to injections into the sys module
602 #-------------------------------------------------------------------------
613 #-------------------------------------------------------------------------
603
614
604 def save_sys_module_state(self):
615 def save_sys_module_state(self):
605 """Save the state of hooks in the sys module.
616 """Save the state of hooks in the sys module.
606
617
607 This has to be called after self.user_ns is created.
618 This has to be called after self.user_ns is created.
608 """
619 """
609 self._orig_sys_module_state = {}
620 self._orig_sys_module_state = {}
610 self._orig_sys_module_state['stdin'] = sys.stdin
621 self._orig_sys_module_state['stdin'] = sys.stdin
611 self._orig_sys_module_state['stdout'] = sys.stdout
622 self._orig_sys_module_state['stdout'] = sys.stdout
612 self._orig_sys_module_state['stderr'] = sys.stderr
623 self._orig_sys_module_state['stderr'] = sys.stderr
613 self._orig_sys_module_state['excepthook'] = sys.excepthook
624 self._orig_sys_module_state['excepthook'] = sys.excepthook
614 try:
625 try:
615 self._orig_sys_modules_main_name = self.user_ns['__name__']
626 self._orig_sys_modules_main_name = self.user_ns['__name__']
616 except KeyError:
627 except KeyError:
617 pass
628 pass
618
629
619 def restore_sys_module_state(self):
630 def restore_sys_module_state(self):
620 """Restore the state of the sys module."""
631 """Restore the state of the sys module."""
621 try:
632 try:
622 for k, v in self._orig_sys_module_state.iteritems():
633 for k, v in self._orig_sys_module_state.iteritems():
623 setattr(sys, k, v)
634 setattr(sys, k, v)
624 except AttributeError:
635 except AttributeError:
625 pass
636 pass
626 # Reset what what done in self.init_sys_modules
637 # Reset what what done in self.init_sys_modules
627 try:
638 try:
628 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
639 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
629 except (AttributeError, KeyError):
640 except (AttributeError, KeyError):
630 pass
641 pass
631
642
632 #-------------------------------------------------------------------------
643 #-------------------------------------------------------------------------
633 # Things related to hooks
644 # Things related to hooks
634 #-------------------------------------------------------------------------
645 #-------------------------------------------------------------------------
635
646
636 def init_hooks(self):
647 def init_hooks(self):
637 # hooks holds pointers used for user-side customizations
648 # hooks holds pointers used for user-side customizations
638 self.hooks = Struct()
649 self.hooks = Struct()
639
650
640 self.strdispatchers = {}
651 self.strdispatchers = {}
641
652
642 # Set all default hooks, defined in the IPython.hooks module.
653 # Set all default hooks, defined in the IPython.hooks module.
643 hooks = IPython.core.hooks
654 hooks = IPython.core.hooks
644 for hook_name in hooks.__all__:
655 for hook_name in hooks.__all__:
645 # default hooks have priority 100, i.e. low; user hooks should have
656 # default hooks have priority 100, i.e. low; user hooks should have
646 # 0-100 priority
657 # 0-100 priority
647 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
658 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
648
659
649 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
660 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
650 """set_hook(name,hook) -> sets an internal IPython hook.
661 """set_hook(name,hook) -> sets an internal IPython hook.
651
662
652 IPython exposes some of its internal API as user-modifiable hooks. By
663 IPython exposes some of its internal API as user-modifiable hooks. By
653 adding your function to one of these hooks, you can modify IPython's
664 adding your function to one of these hooks, you can modify IPython's
654 behavior to call at runtime your own routines."""
665 behavior to call at runtime your own routines."""
655
666
656 # At some point in the future, this should validate the hook before it
667 # At some point in the future, this should validate the hook before it
657 # accepts it. Probably at least check that the hook takes the number
668 # accepts it. Probably at least check that the hook takes the number
658 # of args it's supposed to.
669 # of args it's supposed to.
659
670
660 f = types.MethodType(hook,self)
671 f = types.MethodType(hook,self)
661
672
662 # check if the hook is for strdispatcher first
673 # check if the hook is for strdispatcher first
663 if str_key is not None:
674 if str_key is not None:
664 sdp = self.strdispatchers.get(name, StrDispatch())
675 sdp = self.strdispatchers.get(name, StrDispatch())
665 sdp.add_s(str_key, f, priority )
676 sdp.add_s(str_key, f, priority )
666 self.strdispatchers[name] = sdp
677 self.strdispatchers[name] = sdp
667 return
678 return
668 if re_key is not None:
679 if re_key is not None:
669 sdp = self.strdispatchers.get(name, StrDispatch())
680 sdp = self.strdispatchers.get(name, StrDispatch())
670 sdp.add_re(re.compile(re_key), f, priority )
681 sdp.add_re(re.compile(re_key), f, priority )
671 self.strdispatchers[name] = sdp
682 self.strdispatchers[name] = sdp
672 return
683 return
673
684
674 dp = getattr(self.hooks, name, None)
685 dp = getattr(self.hooks, name, None)
675 if name not in IPython.core.hooks.__all__:
686 if name not in IPython.core.hooks.__all__:
676 print "Warning! Hook '%s' is not one of %s" % \
687 print "Warning! Hook '%s' is not one of %s" % \
677 (name, IPython.core.hooks.__all__ )
688 (name, IPython.core.hooks.__all__ )
678 if not dp:
689 if not dp:
679 dp = IPython.core.hooks.CommandChainDispatcher()
690 dp = IPython.core.hooks.CommandChainDispatcher()
680
691
681 try:
692 try:
682 dp.add(f,priority)
693 dp.add(f,priority)
683 except AttributeError:
694 except AttributeError:
684 # it was not commandchain, plain old func - replace
695 # it was not commandchain, plain old func - replace
685 dp = f
696 dp = f
686
697
687 setattr(self.hooks,name, dp)
698 setattr(self.hooks,name, dp)
688
699
689 def register_post_execute(self, func):
700 def register_post_execute(self, func):
690 """Register a function for calling after code execution.
701 """Register a function for calling after code execution.
691 """
702 """
692 if not callable(func):
703 if not callable(func):
693 raise ValueError('argument %s must be callable' % func)
704 raise ValueError('argument %s must be callable' % func)
694 self._post_execute[func] = True
705 self._post_execute[func] = True
695
706
696 #-------------------------------------------------------------------------
707 #-------------------------------------------------------------------------
697 # Things related to the "main" module
708 # Things related to the "main" module
698 #-------------------------------------------------------------------------
709 #-------------------------------------------------------------------------
699
710
700 def new_main_mod(self,ns=None):
711 def new_main_mod(self,ns=None):
701 """Return a new 'main' module object for user code execution.
712 """Return a new 'main' module object for user code execution.
702 """
713 """
703 main_mod = self._user_main_module
714 main_mod = self._user_main_module
704 init_fakemod_dict(main_mod,ns)
715 init_fakemod_dict(main_mod,ns)
705 return main_mod
716 return main_mod
706
717
707 def cache_main_mod(self,ns,fname):
718 def cache_main_mod(self,ns,fname):
708 """Cache a main module's namespace.
719 """Cache a main module's namespace.
709
720
710 When scripts are executed via %run, we must keep a reference to the
721 When scripts are executed via %run, we must keep a reference to the
711 namespace of their __main__ module (a FakeModule instance) around so
722 namespace of their __main__ module (a FakeModule instance) around so
712 that Python doesn't clear it, rendering objects defined therein
723 that Python doesn't clear it, rendering objects defined therein
713 useless.
724 useless.
714
725
715 This method keeps said reference in a private dict, keyed by the
726 This method keeps said reference in a private dict, keyed by the
716 absolute path of the module object (which corresponds to the script
727 absolute path of the module object (which corresponds to the script
717 path). This way, for multiple executions of the same script we only
728 path). This way, for multiple executions of the same script we only
718 keep one copy of the namespace (the last one), thus preventing memory
729 keep one copy of the namespace (the last one), thus preventing memory
719 leaks from old references while allowing the objects from the last
730 leaks from old references while allowing the objects from the last
720 execution to be accessible.
731 execution to be accessible.
721
732
722 Note: we can not allow the actual FakeModule instances to be deleted,
733 Note: we can not allow the actual FakeModule instances to be deleted,
723 because of how Python tears down modules (it hard-sets all their
734 because of how Python tears down modules (it hard-sets all their
724 references to None without regard for reference counts). This method
735 references to None without regard for reference counts). This method
725 must therefore make a *copy* of the given namespace, to allow the
736 must therefore make a *copy* of the given namespace, to allow the
726 original module's __dict__ to be cleared and reused.
737 original module's __dict__ to be cleared and reused.
727
738
728
739
729 Parameters
740 Parameters
730 ----------
741 ----------
731 ns : a namespace (a dict, typically)
742 ns : a namespace (a dict, typically)
732
743
733 fname : str
744 fname : str
734 Filename associated with the namespace.
745 Filename associated with the namespace.
735
746
736 Examples
747 Examples
737 --------
748 --------
738
749
739 In [10]: import IPython
750 In [10]: import IPython
740
751
741 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
752 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
742
753
743 In [12]: IPython.__file__ in _ip._main_ns_cache
754 In [12]: IPython.__file__ in _ip._main_ns_cache
744 Out[12]: True
755 Out[12]: True
745 """
756 """
746 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
757 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
747
758
748 def clear_main_mod_cache(self):
759 def clear_main_mod_cache(self):
749 """Clear the cache of main modules.
760 """Clear the cache of main modules.
750
761
751 Mainly for use by utilities like %reset.
762 Mainly for use by utilities like %reset.
752
763
753 Examples
764 Examples
754 --------
765 --------
755
766
756 In [15]: import IPython
767 In [15]: import IPython
757
768
758 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
769 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
759
770
760 In [17]: len(_ip._main_ns_cache) > 0
771 In [17]: len(_ip._main_ns_cache) > 0
761 Out[17]: True
772 Out[17]: True
762
773
763 In [18]: _ip.clear_main_mod_cache()
774 In [18]: _ip.clear_main_mod_cache()
764
775
765 In [19]: len(_ip._main_ns_cache) == 0
776 In [19]: len(_ip._main_ns_cache) == 0
766 Out[19]: True
777 Out[19]: True
767 """
778 """
768 self._main_ns_cache.clear()
779 self._main_ns_cache.clear()
769
780
770 #-------------------------------------------------------------------------
781 #-------------------------------------------------------------------------
771 # Things related to debugging
782 # Things related to debugging
772 #-------------------------------------------------------------------------
783 #-------------------------------------------------------------------------
773
784
774 def init_pdb(self):
785 def init_pdb(self):
775 # Set calling of pdb on exceptions
786 # Set calling of pdb on exceptions
776 # self.call_pdb is a property
787 # self.call_pdb is a property
777 self.call_pdb = self.pdb
788 self.call_pdb = self.pdb
778
789
779 def _get_call_pdb(self):
790 def _get_call_pdb(self):
780 return self._call_pdb
791 return self._call_pdb
781
792
782 def _set_call_pdb(self,val):
793 def _set_call_pdb(self,val):
783
794
784 if val not in (0,1,False,True):
795 if val not in (0,1,False,True):
785 raise ValueError,'new call_pdb value must be boolean'
796 raise ValueError,'new call_pdb value must be boolean'
786
797
787 # store value in instance
798 # store value in instance
788 self._call_pdb = val
799 self._call_pdb = val
789
800
790 # notify the actual exception handlers
801 # notify the actual exception handlers
791 self.InteractiveTB.call_pdb = val
802 self.InteractiveTB.call_pdb = val
792
803
793 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
804 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
794 'Control auto-activation of pdb at exceptions')
805 'Control auto-activation of pdb at exceptions')
795
806
796 def debugger(self,force=False):
807 def debugger(self,force=False):
797 """Call the pydb/pdb debugger.
808 """Call the pydb/pdb debugger.
798
809
799 Keywords:
810 Keywords:
800
811
801 - force(False): by default, this routine checks the instance call_pdb
812 - force(False): by default, this routine checks the instance call_pdb
802 flag and does not actually invoke the debugger if the flag is false.
813 flag and does not actually invoke the debugger if the flag is false.
803 The 'force' option forces the debugger to activate even if the flag
814 The 'force' option forces the debugger to activate even if the flag
804 is false.
815 is false.
805 """
816 """
806
817
807 if not (force or self.call_pdb):
818 if not (force or self.call_pdb):
808 return
819 return
809
820
810 if not hasattr(sys,'last_traceback'):
821 if not hasattr(sys,'last_traceback'):
811 error('No traceback has been produced, nothing to debug.')
822 error('No traceback has been produced, nothing to debug.')
812 return
823 return
813
824
814 # use pydb if available
825 # use pydb if available
815 if debugger.has_pydb:
826 if debugger.has_pydb:
816 from pydb import pm
827 from pydb import pm
817 else:
828 else:
818 # fallback to our internal debugger
829 # fallback to our internal debugger
819 pm = lambda : self.InteractiveTB.debugger(force=True)
830 pm = lambda : self.InteractiveTB.debugger(force=True)
820
831
821 with self.readline_no_record:
832 with self.readline_no_record:
822 pm()
833 pm()
823
834
824 #-------------------------------------------------------------------------
835 #-------------------------------------------------------------------------
825 # Things related to IPython's various namespaces
836 # Things related to IPython's various namespaces
826 #-------------------------------------------------------------------------
837 #-------------------------------------------------------------------------
827
838
828 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
839 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
829 # Create the namespace where the user will operate. user_ns is
840 # Create the namespace where the user will operate. user_ns is
830 # normally the only one used, and it is passed to the exec calls as
841 # normally the only one used, and it is passed to the exec calls as
831 # the locals argument. But we do carry a user_global_ns namespace
842 # the locals argument. But we do carry a user_global_ns namespace
832 # given as the exec 'globals' argument, This is useful in embedding
843 # given as the exec 'globals' argument, This is useful in embedding
833 # situations where the ipython shell opens in a context where the
844 # situations where the ipython shell opens in a context where the
834 # distinction between locals and globals is meaningful. For
845 # distinction between locals and globals is meaningful. For
835 # non-embedded contexts, it is just the same object as the user_ns dict.
846 # non-embedded contexts, it is just the same object as the user_ns dict.
836
847
837 # FIXME. For some strange reason, __builtins__ is showing up at user
848 # FIXME. For some strange reason, __builtins__ is showing up at user
838 # level as a dict instead of a module. This is a manual fix, but I
849 # level as a dict instead of a module. This is a manual fix, but I
839 # should really track down where the problem is coming from. Alex
850 # should really track down where the problem is coming from. Alex
840 # Schmolck reported this problem first.
851 # Schmolck reported this problem first.
841
852
842 # A useful post by Alex Martelli on this topic:
853 # A useful post by Alex Martelli on this topic:
843 # Re: inconsistent value from __builtins__
854 # Re: inconsistent value from __builtins__
844 # Von: Alex Martelli <aleaxit@yahoo.com>
855 # Von: Alex Martelli <aleaxit@yahoo.com>
845 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
856 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
846 # Gruppen: comp.lang.python
857 # Gruppen: comp.lang.python
847
858
848 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
859 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
849 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
860 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
850 # > <type 'dict'>
861 # > <type 'dict'>
851 # > >>> print type(__builtins__)
862 # > >>> print type(__builtins__)
852 # > <type 'module'>
863 # > <type 'module'>
853 # > Is this difference in return value intentional?
864 # > Is this difference in return value intentional?
854
865
855 # Well, it's documented that '__builtins__' can be either a dictionary
866 # Well, it's documented that '__builtins__' can be either a dictionary
856 # or a module, and it's been that way for a long time. Whether it's
867 # or a module, and it's been that way for a long time. Whether it's
857 # intentional (or sensible), I don't know. In any case, the idea is
868 # intentional (or sensible), I don't know. In any case, the idea is
858 # that if you need to access the built-in namespace directly, you
869 # that if you need to access the built-in namespace directly, you
859 # should start with "import __builtin__" (note, no 's') which will
870 # should start with "import __builtin__" (note, no 's') which will
860 # definitely give you a module. Yeah, it's somewhat confusing:-(.
871 # definitely give you a module. Yeah, it's somewhat confusing:-(.
861
872
862 # These routines return properly built dicts as needed by the rest of
873 # These routines return properly built dicts as needed by the rest of
863 # the code, and can also be used by extension writers to generate
874 # the code, and can also be used by extension writers to generate
864 # properly initialized namespaces.
875 # properly initialized namespaces.
865 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
876 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
866 user_global_ns)
877 user_global_ns)
867
878
868 # Assign namespaces
879 # Assign namespaces
869 # This is the namespace where all normal user variables live
880 # This is the namespace where all normal user variables live
870 self.user_ns = user_ns
881 self.user_ns = user_ns
871 self.user_global_ns = user_global_ns
882 self.user_global_ns = user_global_ns
872
883
873 # An auxiliary namespace that checks what parts of the user_ns were
884 # An auxiliary namespace that checks what parts of the user_ns were
874 # loaded at startup, so we can list later only variables defined in
885 # loaded at startup, so we can list later only variables defined in
875 # actual interactive use. Since it is always a subset of user_ns, it
886 # actual interactive use. Since it is always a subset of user_ns, it
876 # doesn't need to be separately tracked in the ns_table.
887 # doesn't need to be separately tracked in the ns_table.
877 self.user_ns_hidden = {}
888 self.user_ns_hidden = {}
878
889
879 # A namespace to keep track of internal data structures to prevent
890 # A namespace to keep track of internal data structures to prevent
880 # them from cluttering user-visible stuff. Will be updated later
891 # them from cluttering user-visible stuff. Will be updated later
881 self.internal_ns = {}
892 self.internal_ns = {}
882
893
883 # Now that FakeModule produces a real module, we've run into a nasty
894 # Now that FakeModule produces a real module, we've run into a nasty
884 # problem: after script execution (via %run), the module where the user
895 # problem: after script execution (via %run), the module where the user
885 # code ran is deleted. Now that this object is a true module (needed
896 # code ran is deleted. Now that this object is a true module (needed
886 # so docetst and other tools work correctly), the Python module
897 # so docetst and other tools work correctly), the Python module
887 # teardown mechanism runs over it, and sets to None every variable
898 # teardown mechanism runs over it, and sets to None every variable
888 # present in that module. Top-level references to objects from the
899 # present in that module. Top-level references to objects from the
889 # script survive, because the user_ns is updated with them. However,
900 # script survive, because the user_ns is updated with them. However,
890 # calling functions defined in the script that use other things from
901 # calling functions defined in the script that use other things from
891 # the script will fail, because the function's closure had references
902 # the script will fail, because the function's closure had references
892 # to the original objects, which are now all None. So we must protect
903 # to the original objects, which are now all None. So we must protect
893 # these modules from deletion by keeping a cache.
904 # these modules from deletion by keeping a cache.
894 #
905 #
895 # To avoid keeping stale modules around (we only need the one from the
906 # To avoid keeping stale modules around (we only need the one from the
896 # last run), we use a dict keyed with the full path to the script, so
907 # last run), we use a dict keyed with the full path to the script, so
897 # only the last version of the module is held in the cache. Note,
908 # only the last version of the module is held in the cache. Note,
898 # however, that we must cache the module *namespace contents* (their
909 # however, that we must cache the module *namespace contents* (their
899 # __dict__). Because if we try to cache the actual modules, old ones
910 # __dict__). Because if we try to cache the actual modules, old ones
900 # (uncached) could be destroyed while still holding references (such as
911 # (uncached) could be destroyed while still holding references (such as
901 # those held by GUI objects that tend to be long-lived)>
912 # those held by GUI objects that tend to be long-lived)>
902 #
913 #
903 # The %reset command will flush this cache. See the cache_main_mod()
914 # The %reset command will flush this cache. See the cache_main_mod()
904 # and clear_main_mod_cache() methods for details on use.
915 # and clear_main_mod_cache() methods for details on use.
905
916
906 # This is the cache used for 'main' namespaces
917 # This is the cache used for 'main' namespaces
907 self._main_ns_cache = {}
918 self._main_ns_cache = {}
908 # And this is the single instance of FakeModule whose __dict__ we keep
919 # And this is the single instance of FakeModule whose __dict__ we keep
909 # copying and clearing for reuse on each %run
920 # copying and clearing for reuse on each %run
910 self._user_main_module = FakeModule()
921 self._user_main_module = FakeModule()
911
922
912 # A table holding all the namespaces IPython deals with, so that
923 # A table holding all the namespaces IPython deals with, so that
913 # introspection facilities can search easily.
924 # introspection facilities can search easily.
914 self.ns_table = {'user':user_ns,
925 self.ns_table = {'user':user_ns,
915 'user_global':user_global_ns,
926 'user_global':user_global_ns,
916 'internal':self.internal_ns,
927 'internal':self.internal_ns,
917 'builtin':__builtin__.__dict__
928 'builtin':__builtin__.__dict__
918 }
929 }
919
930
920 # Similarly, track all namespaces where references can be held and that
931 # Similarly, track all namespaces where references can be held and that
921 # we can safely clear (so it can NOT include builtin). This one can be
932 # we can safely clear (so it can NOT include builtin). This one can be
922 # a simple list. Note that the main execution namespaces, user_ns and
933 # a simple list. Note that the main execution namespaces, user_ns and
923 # user_global_ns, can NOT be listed here, as clearing them blindly
934 # user_global_ns, can NOT be listed here, as clearing them blindly
924 # causes errors in object __del__ methods. Instead, the reset() method
935 # causes errors in object __del__ methods. Instead, the reset() method
925 # clears them manually and carefully.
936 # clears them manually and carefully.
926 self.ns_refs_table = [ self.user_ns_hidden,
937 self.ns_refs_table = [ self.user_ns_hidden,
927 self.internal_ns, self._main_ns_cache ]
938 self.internal_ns, self._main_ns_cache ]
928
939
929 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
940 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
930 """Return a valid local and global user interactive namespaces.
941 """Return a valid local and global user interactive namespaces.
931
942
932 This builds a dict with the minimal information needed to operate as a
943 This builds a dict with the minimal information needed to operate as a
933 valid IPython user namespace, which you can pass to the various
944 valid IPython user namespace, which you can pass to the various
934 embedding classes in ipython. The default implementation returns the
945 embedding classes in ipython. The default implementation returns the
935 same dict for both the locals and the globals to allow functions to
946 same dict for both the locals and the globals to allow functions to
936 refer to variables in the namespace. Customized implementations can
947 refer to variables in the namespace. Customized implementations can
937 return different dicts. The locals dictionary can actually be anything
948 return different dicts. The locals dictionary can actually be anything
938 following the basic mapping protocol of a dict, but the globals dict
949 following the basic mapping protocol of a dict, but the globals dict
939 must be a true dict, not even a subclass. It is recommended that any
950 must be a true dict, not even a subclass. It is recommended that any
940 custom object for the locals namespace synchronize with the globals
951 custom object for the locals namespace synchronize with the globals
941 dict somehow.
952 dict somehow.
942
953
943 Raises TypeError if the provided globals namespace is not a true dict.
954 Raises TypeError if the provided globals namespace is not a true dict.
944
955
945 Parameters
956 Parameters
946 ----------
957 ----------
947 user_ns : dict-like, optional
958 user_ns : dict-like, optional
948 The current user namespace. The items in this namespace should
959 The current user namespace. The items in this namespace should
949 be included in the output. If None, an appropriate blank
960 be included in the output. If None, an appropriate blank
950 namespace should be created.
961 namespace should be created.
951 user_global_ns : dict, optional
962 user_global_ns : dict, optional
952 The current user global namespace. The items in this namespace
963 The current user global namespace. The items in this namespace
953 should be included in the output. If None, an appropriate
964 should be included in the output. If None, an appropriate
954 blank namespace should be created.
965 blank namespace should be created.
955
966
956 Returns
967 Returns
957 -------
968 -------
958 A pair of dictionary-like object to be used as the local namespace
969 A pair of dictionary-like object to be used as the local namespace
959 of the interpreter and a dict to be used as the global namespace.
970 of the interpreter and a dict to be used as the global namespace.
960 """
971 """
961
972
962
973
963 # We must ensure that __builtin__ (without the final 's') is always
974 # We must ensure that __builtin__ (without the final 's') is always
964 # available and pointing to the __builtin__ *module*. For more details:
975 # available and pointing to the __builtin__ *module*. For more details:
965 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
976 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
966
977
967 if user_ns is None:
978 if user_ns is None:
968 # Set __name__ to __main__ to better match the behavior of the
979 # Set __name__ to __main__ to better match the behavior of the
969 # normal interpreter.
980 # normal interpreter.
970 user_ns = {'__name__' :'__main__',
981 user_ns = {'__name__' :'__main__',
971 '__builtin__' : __builtin__,
982 '__builtin__' : __builtin__,
972 '__builtins__' : __builtin__,
983 '__builtins__' : __builtin__,
973 }
984 }
974 else:
985 else:
975 user_ns.setdefault('__name__','__main__')
986 user_ns.setdefault('__name__','__main__')
976 user_ns.setdefault('__builtin__',__builtin__)
987 user_ns.setdefault('__builtin__',__builtin__)
977 user_ns.setdefault('__builtins__',__builtin__)
988 user_ns.setdefault('__builtins__',__builtin__)
978
989
979 if user_global_ns is None:
990 if user_global_ns is None:
980 user_global_ns = user_ns
991 user_global_ns = user_ns
981 if type(user_global_ns) is not dict:
992 if type(user_global_ns) is not dict:
982 raise TypeError("user_global_ns must be a true dict; got %r"
993 raise TypeError("user_global_ns must be a true dict; got %r"
983 % type(user_global_ns))
994 % type(user_global_ns))
984
995
985 return user_ns, user_global_ns
996 return user_ns, user_global_ns
986
997
987 def init_sys_modules(self):
998 def init_sys_modules(self):
988 # We need to insert into sys.modules something that looks like a
999 # We need to insert into sys.modules something that looks like a
989 # module but which accesses the IPython namespace, for shelve and
1000 # module but which accesses the IPython namespace, for shelve and
990 # pickle to work interactively. Normally they rely on getting
1001 # pickle to work interactively. Normally they rely on getting
991 # everything out of __main__, but for embedding purposes each IPython
1002 # everything out of __main__, but for embedding purposes each IPython
992 # instance has its own private namespace, so we can't go shoving
1003 # instance has its own private namespace, so we can't go shoving
993 # everything into __main__.
1004 # everything into __main__.
994
1005
995 # note, however, that we should only do this for non-embedded
1006 # note, however, that we should only do this for non-embedded
996 # ipythons, which really mimic the __main__.__dict__ with their own
1007 # ipythons, which really mimic the __main__.__dict__ with their own
997 # namespace. Embedded instances, on the other hand, should not do
1008 # namespace. Embedded instances, on the other hand, should not do
998 # this because they need to manage the user local/global namespaces
1009 # this because they need to manage the user local/global namespaces
999 # only, but they live within a 'normal' __main__ (meaning, they
1010 # only, but they live within a 'normal' __main__ (meaning, they
1000 # shouldn't overtake the execution environment of the script they're
1011 # shouldn't overtake the execution environment of the script they're
1001 # embedded in).
1012 # embedded in).
1002
1013
1003 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1014 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1004
1015
1005 try:
1016 try:
1006 main_name = self.user_ns['__name__']
1017 main_name = self.user_ns['__name__']
1007 except KeyError:
1018 except KeyError:
1008 raise KeyError('user_ns dictionary MUST have a "__name__" key')
1019 raise KeyError('user_ns dictionary MUST have a "__name__" key')
1009 else:
1020 else:
1010 sys.modules[main_name] = FakeModule(self.user_ns)
1021 sys.modules[main_name] = FakeModule(self.user_ns)
1011
1022
1012 def init_user_ns(self):
1023 def init_user_ns(self):
1013 """Initialize all user-visible namespaces to their minimum defaults.
1024 """Initialize all user-visible namespaces to their minimum defaults.
1014
1025
1015 Certain history lists are also initialized here, as they effectively
1026 Certain history lists are also initialized here, as they effectively
1016 act as user namespaces.
1027 act as user namespaces.
1017
1028
1018 Notes
1029 Notes
1019 -----
1030 -----
1020 All data structures here are only filled in, they are NOT reset by this
1031 All data structures here are only filled in, they are NOT reset by this
1021 method. If they were not empty before, data will simply be added to
1032 method. If they were not empty before, data will simply be added to
1022 therm.
1033 therm.
1023 """
1034 """
1024 # This function works in two parts: first we put a few things in
1035 # This function works in two parts: first we put a few things in
1025 # user_ns, and we sync that contents into user_ns_hidden so that these
1036 # user_ns, and we sync that contents into user_ns_hidden so that these
1026 # initial variables aren't shown by %who. After the sync, we add the
1037 # initial variables aren't shown by %who. After the sync, we add the
1027 # rest of what we *do* want the user to see with %who even on a new
1038 # rest of what we *do* want the user to see with %who even on a new
1028 # session (probably nothing, so theye really only see their own stuff)
1039 # session (probably nothing, so theye really only see their own stuff)
1029
1040
1030 # The user dict must *always* have a __builtin__ reference to the
1041 # The user dict must *always* have a __builtin__ reference to the
1031 # Python standard __builtin__ namespace, which must be imported.
1042 # Python standard __builtin__ namespace, which must be imported.
1032 # This is so that certain operations in prompt evaluation can be
1043 # This is so that certain operations in prompt evaluation can be
1033 # reliably executed with builtins. Note that we can NOT use
1044 # reliably executed with builtins. Note that we can NOT use
1034 # __builtins__ (note the 's'), because that can either be a dict or a
1045 # __builtins__ (note the 's'), because that can either be a dict or a
1035 # module, and can even mutate at runtime, depending on the context
1046 # module, and can even mutate at runtime, depending on the context
1036 # (Python makes no guarantees on it). In contrast, __builtin__ is
1047 # (Python makes no guarantees on it). In contrast, __builtin__ is
1037 # always a module object, though it must be explicitly imported.
1048 # always a module object, though it must be explicitly imported.
1038
1049
1039 # For more details:
1050 # For more details:
1040 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1051 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1041 ns = dict(__builtin__ = __builtin__)
1052 ns = dict(__builtin__ = __builtin__)
1042
1053
1043 # Put 'help' in the user namespace
1054 # Put 'help' in the user namespace
1044 try:
1055 try:
1045 from site import _Helper
1056 from site import _Helper
1046 ns['help'] = _Helper()
1057 ns['help'] = _Helper()
1047 except ImportError:
1058 except ImportError:
1048 warn('help() not available - check site.py')
1059 warn('help() not available - check site.py')
1049
1060
1050 # make global variables for user access to the histories
1061 # make global variables for user access to the histories
1051 ns['_ih'] = self.history_manager.input_hist_parsed
1062 ns['_ih'] = self.history_manager.input_hist_parsed
1052 ns['_oh'] = self.history_manager.output_hist
1063 ns['_oh'] = self.history_manager.output_hist
1053 ns['_dh'] = self.history_manager.dir_hist
1064 ns['_dh'] = self.history_manager.dir_hist
1054
1065
1055 ns['_sh'] = shadowns
1066 ns['_sh'] = shadowns
1056
1067
1057 # user aliases to input and output histories. These shouldn't show up
1068 # user aliases to input and output histories. These shouldn't show up
1058 # in %who, as they can have very large reprs.
1069 # in %who, as they can have very large reprs.
1059 ns['In'] = self.history_manager.input_hist_parsed
1070 ns['In'] = self.history_manager.input_hist_parsed
1060 ns['Out'] = self.history_manager.output_hist
1071 ns['Out'] = self.history_manager.output_hist
1061
1072
1062 # Store myself as the public api!!!
1073 # Store myself as the public api!!!
1063 ns['get_ipython'] = self.get_ipython
1074 ns['get_ipython'] = self.get_ipython
1064
1075
1065 ns['exit'] = self.exiter
1076 ns['exit'] = self.exiter
1066 ns['quit'] = self.exiter
1077 ns['quit'] = self.exiter
1067
1078
1068 # Sync what we've added so far to user_ns_hidden so these aren't seen
1079 # Sync what we've added so far to user_ns_hidden so these aren't seen
1069 # by %who
1080 # by %who
1070 self.user_ns_hidden.update(ns)
1081 self.user_ns_hidden.update(ns)
1071
1082
1072 # Anything put into ns now would show up in %who. Think twice before
1083 # Anything put into ns now would show up in %who. Think twice before
1073 # putting anything here, as we really want %who to show the user their
1084 # putting anything here, as we really want %who to show the user their
1074 # stuff, not our variables.
1085 # stuff, not our variables.
1075
1086
1076 # Finally, update the real user's namespace
1087 # Finally, update the real user's namespace
1077 self.user_ns.update(ns)
1088 self.user_ns.update(ns)
1078
1089
1079 def reset(self, new_session=True):
1090 def reset(self, new_session=True):
1080 """Clear all internal namespaces, and attempt to release references to
1091 """Clear all internal namespaces, and attempt to release references to
1081 user objects.
1092 user objects.
1082
1093
1083 If new_session is True, a new history session will be opened.
1094 If new_session is True, a new history session will be opened.
1084 """
1095 """
1085 # Clear histories
1096 # Clear histories
1086 self.history_manager.reset(new_session)
1097 self.history_manager.reset(new_session)
1087 # Reset counter used to index all histories
1098 # Reset counter used to index all histories
1088 if new_session:
1099 if new_session:
1089 self.execution_count = 1
1100 self.execution_count = 1
1090
1101
1091 # Flush cached output items
1102 # Flush cached output items
1092 if self.displayhook.do_full_cache:
1103 if self.displayhook.do_full_cache:
1093 self.displayhook.flush()
1104 self.displayhook.flush()
1094
1105
1095 # Restore the user namespaces to minimal usability
1106 # Restore the user namespaces to minimal usability
1096 for ns in self.ns_refs_table:
1107 for ns in self.ns_refs_table:
1097 ns.clear()
1108 ns.clear()
1098
1109
1099 # The main execution namespaces must be cleared very carefully,
1110 # The main execution namespaces must be cleared very carefully,
1100 # skipping the deletion of the builtin-related keys, because doing so
1111 # skipping the deletion of the builtin-related keys, because doing so
1101 # would cause errors in many object's __del__ methods.
1112 # would cause errors in many object's __del__ methods.
1102 for ns in [self.user_ns, self.user_global_ns]:
1113 for ns in [self.user_ns, self.user_global_ns]:
1103 drop_keys = set(ns.keys())
1114 drop_keys = set(ns.keys())
1104 drop_keys.discard('__builtin__')
1115 drop_keys.discard('__builtin__')
1105 drop_keys.discard('__builtins__')
1116 drop_keys.discard('__builtins__')
1106 for k in drop_keys:
1117 for k in drop_keys:
1107 del ns[k]
1118 del ns[k]
1108
1119
1109 # Restore the user namespaces to minimal usability
1120 # Restore the user namespaces to minimal usability
1110 self.init_user_ns()
1121 self.init_user_ns()
1111
1122
1112 # Restore the default and user aliases
1123 # Restore the default and user aliases
1113 self.alias_manager.clear_aliases()
1124 self.alias_manager.clear_aliases()
1114 self.alias_manager.init_aliases()
1125 self.alias_manager.init_aliases()
1115
1126
1116 # Flush the private list of module references kept for script
1127 # Flush the private list of module references kept for script
1117 # execution protection
1128 # execution protection
1118 self.clear_main_mod_cache()
1129 self.clear_main_mod_cache()
1119
1130
1120 # Clear out the namespace from the last %run
1131 # Clear out the namespace from the last %run
1121 self.new_main_mod()
1132 self.new_main_mod()
1122
1133
1123 def del_var(self, varname, by_name=False):
1134 def del_var(self, varname, by_name=False):
1124 """Delete a variable from the various namespaces, so that, as
1135 """Delete a variable from the various namespaces, so that, as
1125 far as possible, we're not keeping any hidden references to it.
1136 far as possible, we're not keeping any hidden references to it.
1126
1137
1127 Parameters
1138 Parameters
1128 ----------
1139 ----------
1129 varname : str
1140 varname : str
1130 The name of the variable to delete.
1141 The name of the variable to delete.
1131 by_name : bool
1142 by_name : bool
1132 If True, delete variables with the given name in each
1143 If True, delete variables with the given name in each
1133 namespace. If False (default), find the variable in the user
1144 namespace. If False (default), find the variable in the user
1134 namespace, and delete references to it.
1145 namespace, and delete references to it.
1135 """
1146 """
1136 if varname in ('__builtin__', '__builtins__'):
1147 if varname in ('__builtin__', '__builtins__'):
1137 raise ValueError("Refusing to delete %s" % varname)
1148 raise ValueError("Refusing to delete %s" % varname)
1138 ns_refs = self.ns_refs_table + [self.user_ns,
1149 ns_refs = self.ns_refs_table + [self.user_ns,
1139 self.user_global_ns, self._user_main_module.__dict__] +\
1150 self.user_global_ns, self._user_main_module.__dict__] +\
1140 self._main_ns_cache.values()
1151 self._main_ns_cache.values()
1141
1152
1142 if by_name: # Delete by name
1153 if by_name: # Delete by name
1143 for ns in ns_refs:
1154 for ns in ns_refs:
1144 try:
1155 try:
1145 del ns[varname]
1156 del ns[varname]
1146 except KeyError:
1157 except KeyError:
1147 pass
1158 pass
1148 else: # Delete by object
1159 else: # Delete by object
1149 try:
1160 try:
1150 obj = self.user_ns[varname]
1161 obj = self.user_ns[varname]
1151 except KeyError:
1162 except KeyError:
1152 raise NameError("name '%s' is not defined" % varname)
1163 raise NameError("name '%s' is not defined" % varname)
1153 # Also check in output history
1164 # Also check in output history
1154 ns_refs.append(self.history_manager.output_hist)
1165 ns_refs.append(self.history_manager.output_hist)
1155 for ns in ns_refs:
1166 for ns in ns_refs:
1156 to_delete = [n for n, o in ns.iteritems() if o is obj]
1167 to_delete = [n for n, o in ns.iteritems() if o is obj]
1157 for name in to_delete:
1168 for name in to_delete:
1158 del ns[name]
1169 del ns[name]
1159
1170
1160 # displayhook keeps extra references, but not in a dictionary
1171 # displayhook keeps extra references, but not in a dictionary
1161 for name in ('_', '__', '___'):
1172 for name in ('_', '__', '___'):
1162 if getattr(self.displayhook, name) is obj:
1173 if getattr(self.displayhook, name) is obj:
1163 setattr(self.displayhook, name, None)
1174 setattr(self.displayhook, name, None)
1164
1175
1165 def reset_selective(self, regex=None):
1176 def reset_selective(self, regex=None):
1166 """Clear selective variables from internal namespaces based on a
1177 """Clear selective variables from internal namespaces based on a
1167 specified regular expression.
1178 specified regular expression.
1168
1179
1169 Parameters
1180 Parameters
1170 ----------
1181 ----------
1171 regex : string or compiled pattern, optional
1182 regex : string or compiled pattern, optional
1172 A regular expression pattern that will be used in searching
1183 A regular expression pattern that will be used in searching
1173 variable names in the users namespaces.
1184 variable names in the users namespaces.
1174 """
1185 """
1175 if regex is not None:
1186 if regex is not None:
1176 try:
1187 try:
1177 m = re.compile(regex)
1188 m = re.compile(regex)
1178 except TypeError:
1189 except TypeError:
1179 raise TypeError('regex must be a string or compiled pattern')
1190 raise TypeError('regex must be a string or compiled pattern')
1180 # Search for keys in each namespace that match the given regex
1191 # Search for keys in each namespace that match the given regex
1181 # If a match is found, delete the key/value pair.
1192 # If a match is found, delete the key/value pair.
1182 for ns in self.ns_refs_table:
1193 for ns in self.ns_refs_table:
1183 for var in ns:
1194 for var in ns:
1184 if m.search(var):
1195 if m.search(var):
1185 del ns[var]
1196 del ns[var]
1186
1197
1187 def push(self, variables, interactive=True):
1198 def push(self, variables, interactive=True):
1188 """Inject a group of variables into the IPython user namespace.
1199 """Inject a group of variables into the IPython user namespace.
1189
1200
1190 Parameters
1201 Parameters
1191 ----------
1202 ----------
1192 variables : dict, str or list/tuple of str
1203 variables : dict, str or list/tuple of str
1193 The variables to inject into the user's namespace. If a dict, a
1204 The variables to inject into the user's namespace. If a dict, a
1194 simple update is done. If a str, the string is assumed to have
1205 simple update is done. If a str, the string is assumed to have
1195 variable names separated by spaces. A list/tuple of str can also
1206 variable names separated by spaces. A list/tuple of str can also
1196 be used to give the variable names. If just the variable names are
1207 be used to give the variable names. If just the variable names are
1197 give (list/tuple/str) then the variable values looked up in the
1208 give (list/tuple/str) then the variable values looked up in the
1198 callers frame.
1209 callers frame.
1199 interactive : bool
1210 interactive : bool
1200 If True (default), the variables will be listed with the ``who``
1211 If True (default), the variables will be listed with the ``who``
1201 magic.
1212 magic.
1202 """
1213 """
1203 vdict = None
1214 vdict = None
1204
1215
1205 # We need a dict of name/value pairs to do namespace updates.
1216 # We need a dict of name/value pairs to do namespace updates.
1206 if isinstance(variables, dict):
1217 if isinstance(variables, dict):
1207 vdict = variables
1218 vdict = variables
1208 elif isinstance(variables, (basestring, list, tuple)):
1219 elif isinstance(variables, (basestring, list, tuple)):
1209 if isinstance(variables, basestring):
1220 if isinstance(variables, basestring):
1210 vlist = variables.split()
1221 vlist = variables.split()
1211 else:
1222 else:
1212 vlist = variables
1223 vlist = variables
1213 vdict = {}
1224 vdict = {}
1214 cf = sys._getframe(1)
1225 cf = sys._getframe(1)
1215 for name in vlist:
1226 for name in vlist:
1216 try:
1227 try:
1217 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1228 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1218 except:
1229 except:
1219 print ('Could not get variable %s from %s' %
1230 print ('Could not get variable %s from %s' %
1220 (name,cf.f_code.co_name))
1231 (name,cf.f_code.co_name))
1221 else:
1232 else:
1222 raise ValueError('variables must be a dict/str/list/tuple')
1233 raise ValueError('variables must be a dict/str/list/tuple')
1223
1234
1224 # Propagate variables to user namespace
1235 # Propagate variables to user namespace
1225 self.user_ns.update(vdict)
1236 self.user_ns.update(vdict)
1226
1237
1227 # And configure interactive visibility
1238 # And configure interactive visibility
1228 config_ns = self.user_ns_hidden
1239 config_ns = self.user_ns_hidden
1229 if interactive:
1240 if interactive:
1230 for name, val in vdict.iteritems():
1241 for name, val in vdict.iteritems():
1231 config_ns.pop(name, None)
1242 config_ns.pop(name, None)
1232 else:
1243 else:
1233 for name,val in vdict.iteritems():
1244 for name,val in vdict.iteritems():
1234 config_ns[name] = val
1245 config_ns[name] = val
1235
1246
1236 #-------------------------------------------------------------------------
1247 #-------------------------------------------------------------------------
1237 # Things related to object introspection
1248 # Things related to object introspection
1238 #-------------------------------------------------------------------------
1249 #-------------------------------------------------------------------------
1239
1250
1240 def _ofind(self, oname, namespaces=None):
1251 def _ofind(self, oname, namespaces=None):
1241 """Find an object in the available namespaces.
1252 """Find an object in the available namespaces.
1242
1253
1243 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1254 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1244
1255
1245 Has special code to detect magic functions.
1256 Has special code to detect magic functions.
1246 """
1257 """
1247 #oname = oname.strip()
1258 #oname = oname.strip()
1248 #print '1- oname: <%r>' % oname # dbg
1259 #print '1- oname: <%r>' % oname # dbg
1249 try:
1260 try:
1250 oname = oname.strip().encode('ascii')
1261 oname = oname.strip().encode('ascii')
1251 #print '2- oname: <%r>' % oname # dbg
1262 #print '2- oname: <%r>' % oname # dbg
1252 except UnicodeEncodeError:
1263 except UnicodeEncodeError:
1253 print 'Python identifiers can only contain ascii characters.'
1264 print 'Python identifiers can only contain ascii characters.'
1254 return dict(found=False)
1265 return dict(found=False)
1255
1266
1256 alias_ns = None
1267 alias_ns = None
1257 if namespaces is None:
1268 if namespaces is None:
1258 # Namespaces to search in:
1269 # Namespaces to search in:
1259 # Put them in a list. The order is important so that we
1270 # Put them in a list. The order is important so that we
1260 # find things in the same order that Python finds them.
1271 # find things in the same order that Python finds them.
1261 namespaces = [ ('Interactive', self.user_ns),
1272 namespaces = [ ('Interactive', self.user_ns),
1262 ('IPython internal', self.internal_ns),
1273 ('IPython internal', self.internal_ns),
1263 ('Python builtin', __builtin__.__dict__),
1274 ('Python builtin', __builtin__.__dict__),
1264 ('Alias', self.alias_manager.alias_table),
1275 ('Alias', self.alias_manager.alias_table),
1265 ]
1276 ]
1266 alias_ns = self.alias_manager.alias_table
1277 alias_ns = self.alias_manager.alias_table
1267
1278
1268 # initialize results to 'null'
1279 # initialize results to 'null'
1269 found = False; obj = None; ospace = None; ds = None;
1280 found = False; obj = None; ospace = None; ds = None;
1270 ismagic = False; isalias = False; parent = None
1281 ismagic = False; isalias = False; parent = None
1271
1282
1272 # We need to special-case 'print', which as of python2.6 registers as a
1283 # We need to special-case 'print', which as of python2.6 registers as a
1273 # function but should only be treated as one if print_function was
1284 # function but should only be treated as one if print_function was
1274 # loaded with a future import. In this case, just bail.
1285 # loaded with a future import. In this case, just bail.
1275 if (oname == 'print' and not (self.compile.compiler_flags &
1286 if (oname == 'print' and not (self.compile.compiler_flags &
1276 __future__.CO_FUTURE_PRINT_FUNCTION)):
1287 __future__.CO_FUTURE_PRINT_FUNCTION)):
1277 return {'found':found, 'obj':obj, 'namespace':ospace,
1288 return {'found':found, 'obj':obj, 'namespace':ospace,
1278 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1289 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1279
1290
1280 # Look for the given name by splitting it in parts. If the head is
1291 # Look for the given name by splitting it in parts. If the head is
1281 # found, then we look for all the remaining parts as members, and only
1292 # found, then we look for all the remaining parts as members, and only
1282 # declare success if we can find them all.
1293 # declare success if we can find them all.
1283 oname_parts = oname.split('.')
1294 oname_parts = oname.split('.')
1284 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1295 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1285 for nsname,ns in namespaces:
1296 for nsname,ns in namespaces:
1286 try:
1297 try:
1287 obj = ns[oname_head]
1298 obj = ns[oname_head]
1288 except KeyError:
1299 except KeyError:
1289 continue
1300 continue
1290 else:
1301 else:
1291 #print 'oname_rest:', oname_rest # dbg
1302 #print 'oname_rest:', oname_rest # dbg
1292 for part in oname_rest:
1303 for part in oname_rest:
1293 try:
1304 try:
1294 parent = obj
1305 parent = obj
1295 obj = getattr(obj,part)
1306 obj = getattr(obj,part)
1296 except:
1307 except:
1297 # Blanket except b/c some badly implemented objects
1308 # Blanket except b/c some badly implemented objects
1298 # allow __getattr__ to raise exceptions other than
1309 # allow __getattr__ to raise exceptions other than
1299 # AttributeError, which then crashes IPython.
1310 # AttributeError, which then crashes IPython.
1300 break
1311 break
1301 else:
1312 else:
1302 # If we finish the for loop (no break), we got all members
1313 # If we finish the for loop (no break), we got all members
1303 found = True
1314 found = True
1304 ospace = nsname
1315 ospace = nsname
1305 if ns == alias_ns:
1316 if ns == alias_ns:
1306 isalias = True
1317 isalias = True
1307 break # namespace loop
1318 break # namespace loop
1308
1319
1309 # Try to see if it's magic
1320 # Try to see if it's magic
1310 if not found:
1321 if not found:
1311 if oname.startswith(ESC_MAGIC):
1322 if oname.startswith(ESC_MAGIC):
1312 oname = oname[1:]
1323 oname = oname[1:]
1313 obj = getattr(self,'magic_'+oname,None)
1324 obj = getattr(self,'magic_'+oname,None)
1314 if obj is not None:
1325 if obj is not None:
1315 found = True
1326 found = True
1316 ospace = 'IPython internal'
1327 ospace = 'IPython internal'
1317 ismagic = True
1328 ismagic = True
1318
1329
1319 # Last try: special-case some literals like '', [], {}, etc:
1330 # Last try: special-case some literals like '', [], {}, etc:
1320 if not found and oname_head in ["''",'""','[]','{}','()']:
1331 if not found and oname_head in ["''",'""','[]','{}','()']:
1321 obj = eval(oname_head)
1332 obj = eval(oname_head)
1322 found = True
1333 found = True
1323 ospace = 'Interactive'
1334 ospace = 'Interactive'
1324
1335
1325 return {'found':found, 'obj':obj, 'namespace':ospace,
1336 return {'found':found, 'obj':obj, 'namespace':ospace,
1326 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1337 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1327
1338
1328 def _ofind_property(self, oname, info):
1339 def _ofind_property(self, oname, info):
1329 """Second part of object finding, to look for property details."""
1340 """Second part of object finding, to look for property details."""
1330 if info.found:
1341 if info.found:
1331 # Get the docstring of the class property if it exists.
1342 # Get the docstring of the class property if it exists.
1332 path = oname.split('.')
1343 path = oname.split('.')
1333 root = '.'.join(path[:-1])
1344 root = '.'.join(path[:-1])
1334 if info.parent is not None:
1345 if info.parent is not None:
1335 try:
1346 try:
1336 target = getattr(info.parent, '__class__')
1347 target = getattr(info.parent, '__class__')
1337 # The object belongs to a class instance.
1348 # The object belongs to a class instance.
1338 try:
1349 try:
1339 target = getattr(target, path[-1])
1350 target = getattr(target, path[-1])
1340 # The class defines the object.
1351 # The class defines the object.
1341 if isinstance(target, property):
1352 if isinstance(target, property):
1342 oname = root + '.__class__.' + path[-1]
1353 oname = root + '.__class__.' + path[-1]
1343 info = Struct(self._ofind(oname))
1354 info = Struct(self._ofind(oname))
1344 except AttributeError: pass
1355 except AttributeError: pass
1345 except AttributeError: pass
1356 except AttributeError: pass
1346
1357
1347 # We return either the new info or the unmodified input if the object
1358 # We return either the new info or the unmodified input if the object
1348 # hadn't been found
1359 # hadn't been found
1349 return info
1360 return info
1350
1361
1351 def _object_find(self, oname, namespaces=None):
1362 def _object_find(self, oname, namespaces=None):
1352 """Find an object and return a struct with info about it."""
1363 """Find an object and return a struct with info about it."""
1353 inf = Struct(self._ofind(oname, namespaces))
1364 inf = Struct(self._ofind(oname, namespaces))
1354 return Struct(self._ofind_property(oname, inf))
1365 return Struct(self._ofind_property(oname, inf))
1355
1366
1356 def _inspect(self, meth, oname, namespaces=None, **kw):
1367 def _inspect(self, meth, oname, namespaces=None, **kw):
1357 """Generic interface to the inspector system.
1368 """Generic interface to the inspector system.
1358
1369
1359 This function is meant to be called by pdef, pdoc & friends."""
1370 This function is meant to be called by pdef, pdoc & friends."""
1360 info = self._object_find(oname)
1371 info = self._object_find(oname)
1361 if info.found:
1372 if info.found:
1362 pmethod = getattr(self.inspector, meth)
1373 pmethod = getattr(self.inspector, meth)
1363 formatter = format_screen if info.ismagic else None
1374 formatter = format_screen if info.ismagic else None
1364 if meth == 'pdoc':
1375 if meth == 'pdoc':
1365 pmethod(info.obj, oname, formatter)
1376 pmethod(info.obj, oname, formatter)
1366 elif meth == 'pinfo':
1377 elif meth == 'pinfo':
1367 pmethod(info.obj, oname, formatter, info, **kw)
1378 pmethod(info.obj, oname, formatter, info, **kw)
1368 else:
1379 else:
1369 pmethod(info.obj, oname)
1380 pmethod(info.obj, oname)
1370 else:
1381 else:
1371 print 'Object `%s` not found.' % oname
1382 print 'Object `%s` not found.' % oname
1372 return 'not found' # so callers can take other action
1383 return 'not found' # so callers can take other action
1373
1384
1374 def object_inspect(self, oname):
1385 def object_inspect(self, oname):
1375 with self.builtin_trap:
1386 with self.builtin_trap:
1376 info = self._object_find(oname)
1387 info = self._object_find(oname)
1377 if info.found:
1388 if info.found:
1378 return self.inspector.info(info.obj, oname, info=info)
1389 return self.inspector.info(info.obj, oname, info=info)
1379 else:
1390 else:
1380 return oinspect.object_info(name=oname, found=False)
1391 return oinspect.object_info(name=oname, found=False)
1381
1392
1382 #-------------------------------------------------------------------------
1393 #-------------------------------------------------------------------------
1383 # Things related to history management
1394 # Things related to history management
1384 #-------------------------------------------------------------------------
1395 #-------------------------------------------------------------------------
1385
1396
1386 def init_history(self):
1397 def init_history(self):
1387 """Sets up the command history, and starts regular autosaves."""
1398 """Sets up the command history, and starts regular autosaves."""
1388 self.history_manager = HistoryManager(shell=self, config=self.config)
1399 self.history_manager = HistoryManager(shell=self, config=self.config)
1389
1400
1390 #-------------------------------------------------------------------------
1401 #-------------------------------------------------------------------------
1391 # Things related to exception handling and tracebacks (not debugging)
1402 # Things related to exception handling and tracebacks (not debugging)
1392 #-------------------------------------------------------------------------
1403 #-------------------------------------------------------------------------
1393
1404
1394 def init_traceback_handlers(self, custom_exceptions):
1405 def init_traceback_handlers(self, custom_exceptions):
1395 # Syntax error handler.
1406 # Syntax error handler.
1396 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1407 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1397
1408
1398 # The interactive one is initialized with an offset, meaning we always
1409 # The interactive one is initialized with an offset, meaning we always
1399 # want to remove the topmost item in the traceback, which is our own
1410 # want to remove the topmost item in the traceback, which is our own
1400 # internal code. Valid modes: ['Plain','Context','Verbose']
1411 # internal code. Valid modes: ['Plain','Context','Verbose']
1401 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1412 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1402 color_scheme='NoColor',
1413 color_scheme='NoColor',
1403 tb_offset = 1,
1414 tb_offset = 1,
1404 check_cache=self.compile.check_cache)
1415 check_cache=self.compile.check_cache)
1405
1416
1406 # The instance will store a pointer to the system-wide exception hook,
1417 # The instance will store a pointer to the system-wide exception hook,
1407 # so that runtime code (such as magics) can access it. This is because
1418 # so that runtime code (such as magics) can access it. This is because
1408 # during the read-eval loop, it may get temporarily overwritten.
1419 # during the read-eval loop, it may get temporarily overwritten.
1409 self.sys_excepthook = sys.excepthook
1420 self.sys_excepthook = sys.excepthook
1410
1421
1411 # and add any custom exception handlers the user may have specified
1422 # and add any custom exception handlers the user may have specified
1412 self.set_custom_exc(*custom_exceptions)
1423 self.set_custom_exc(*custom_exceptions)
1413
1424
1414 # Set the exception mode
1425 # Set the exception mode
1415 self.InteractiveTB.set_mode(mode=self.xmode)
1426 self.InteractiveTB.set_mode(mode=self.xmode)
1416
1427
1417 def set_custom_exc(self, exc_tuple, handler):
1428 def set_custom_exc(self, exc_tuple, handler):
1418 """set_custom_exc(exc_tuple,handler)
1429 """set_custom_exc(exc_tuple,handler)
1419
1430
1420 Set a custom exception handler, which will be called if any of the
1431 Set a custom exception handler, which will be called if any of the
1421 exceptions in exc_tuple occur in the mainloop (specifically, in the
1432 exceptions in exc_tuple occur in the mainloop (specifically, in the
1422 run_code() method.
1433 run_code() method.
1423
1434
1424 Inputs:
1435 Inputs:
1425
1436
1426 - exc_tuple: a *tuple* of valid exceptions to call the defined
1437 - exc_tuple: a *tuple* of valid exceptions to call the defined
1427 handler for. It is very important that you use a tuple, and NOT A
1438 handler for. It is very important that you use a tuple, and NOT A
1428 LIST here, because of the way Python's except statement works. If
1439 LIST here, because of the way Python's except statement works. If
1429 you only want to trap a single exception, use a singleton tuple:
1440 you only want to trap a single exception, use a singleton tuple:
1430
1441
1431 exc_tuple == (MyCustomException,)
1442 exc_tuple == (MyCustomException,)
1432
1443
1433 - handler: this must be defined as a function with the following
1444 - handler: this must be defined as a function with the following
1434 basic interface::
1445 basic interface::
1435
1446
1436 def my_handler(self, etype, value, tb, tb_offset=None)
1447 def my_handler(self, etype, value, tb, tb_offset=None)
1437 ...
1448 ...
1438 # The return value must be
1449 # The return value must be
1439 return structured_traceback
1450 return structured_traceback
1440
1451
1441 This will be made into an instance method (via types.MethodType)
1452 This will be made into an instance method (via types.MethodType)
1442 of IPython itself, and it will be called if any of the exceptions
1453 of IPython itself, and it will be called if any of the exceptions
1443 listed in the exc_tuple are caught. If the handler is None, an
1454 listed in the exc_tuple are caught. If the handler is None, an
1444 internal basic one is used, which just prints basic info.
1455 internal basic one is used, which just prints basic info.
1445
1456
1446 WARNING: by putting in your own exception handler into IPython's main
1457 WARNING: by putting in your own exception handler into IPython's main
1447 execution loop, you run a very good chance of nasty crashes. This
1458 execution loop, you run a very good chance of nasty crashes. This
1448 facility should only be used if you really know what you are doing."""
1459 facility should only be used if you really know what you are doing."""
1449
1460
1450 assert type(exc_tuple)==type(()) , \
1461 assert type(exc_tuple)==type(()) , \
1451 "The custom exceptions must be given AS A TUPLE."
1462 "The custom exceptions must be given AS A TUPLE."
1452
1463
1453 def dummy_handler(self,etype,value,tb):
1464 def dummy_handler(self,etype,value,tb):
1454 print '*** Simple custom exception handler ***'
1465 print '*** Simple custom exception handler ***'
1455 print 'Exception type :',etype
1466 print 'Exception type :',etype
1456 print 'Exception value:',value
1467 print 'Exception value:',value
1457 print 'Traceback :',tb
1468 print 'Traceback :',tb
1458 #print 'Source code :','\n'.join(self.buffer)
1469 #print 'Source code :','\n'.join(self.buffer)
1459
1470
1460 if handler is None: handler = dummy_handler
1471 if handler is None: handler = dummy_handler
1461
1472
1462 self.CustomTB = types.MethodType(handler,self)
1473 self.CustomTB = types.MethodType(handler,self)
1463 self.custom_exceptions = exc_tuple
1474 self.custom_exceptions = exc_tuple
1464
1475
1465 def excepthook(self, etype, value, tb):
1476 def excepthook(self, etype, value, tb):
1466 """One more defense for GUI apps that call sys.excepthook.
1477 """One more defense for GUI apps that call sys.excepthook.
1467
1478
1468 GUI frameworks like wxPython trap exceptions and call
1479 GUI frameworks like wxPython trap exceptions and call
1469 sys.excepthook themselves. I guess this is a feature that
1480 sys.excepthook themselves. I guess this is a feature that
1470 enables them to keep running after exceptions that would
1481 enables them to keep running after exceptions that would
1471 otherwise kill their mainloop. This is a bother for IPython
1482 otherwise kill their mainloop. This is a bother for IPython
1472 which excepts to catch all of the program exceptions with a try:
1483 which excepts to catch all of the program exceptions with a try:
1473 except: statement.
1484 except: statement.
1474
1485
1475 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1486 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1476 any app directly invokes sys.excepthook, it will look to the user like
1487 any app directly invokes sys.excepthook, it will look to the user like
1477 IPython crashed. In order to work around this, we can disable the
1488 IPython crashed. In order to work around this, we can disable the
1478 CrashHandler and replace it with this excepthook instead, which prints a
1489 CrashHandler and replace it with this excepthook instead, which prints a
1479 regular traceback using our InteractiveTB. In this fashion, apps which
1490 regular traceback using our InteractiveTB. In this fashion, apps which
1480 call sys.excepthook will generate a regular-looking exception from
1491 call sys.excepthook will generate a regular-looking exception from
1481 IPython, and the CrashHandler will only be triggered by real IPython
1492 IPython, and the CrashHandler will only be triggered by real IPython
1482 crashes.
1493 crashes.
1483
1494
1484 This hook should be used sparingly, only in places which are not likely
1495 This hook should be used sparingly, only in places which are not likely
1485 to be true IPython errors.
1496 to be true IPython errors.
1486 """
1497 """
1487 self.showtraceback((etype,value,tb),tb_offset=0)
1498 self.showtraceback((etype,value,tb),tb_offset=0)
1488
1499
1489 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1500 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1490 exception_only=False):
1501 exception_only=False):
1491 """Display the exception that just occurred.
1502 """Display the exception that just occurred.
1492
1503
1493 If nothing is known about the exception, this is the method which
1504 If nothing is known about the exception, this is the method which
1494 should be used throughout the code for presenting user tracebacks,
1505 should be used throughout the code for presenting user tracebacks,
1495 rather than directly invoking the InteractiveTB object.
1506 rather than directly invoking the InteractiveTB object.
1496
1507
1497 A specific showsyntaxerror() also exists, but this method can take
1508 A specific showsyntaxerror() also exists, but this method can take
1498 care of calling it if needed, so unless you are explicitly catching a
1509 care of calling it if needed, so unless you are explicitly catching a
1499 SyntaxError exception, don't try to analyze the stack manually and
1510 SyntaxError exception, don't try to analyze the stack manually and
1500 simply call this method."""
1511 simply call this method."""
1501
1512
1502 try:
1513 try:
1503 if exc_tuple is None:
1514 if exc_tuple is None:
1504 etype, value, tb = sys.exc_info()
1515 etype, value, tb = sys.exc_info()
1505 else:
1516 else:
1506 etype, value, tb = exc_tuple
1517 etype, value, tb = exc_tuple
1507
1518
1508 if etype is None:
1519 if etype is None:
1509 if hasattr(sys, 'last_type'):
1520 if hasattr(sys, 'last_type'):
1510 etype, value, tb = sys.last_type, sys.last_value, \
1521 etype, value, tb = sys.last_type, sys.last_value, \
1511 sys.last_traceback
1522 sys.last_traceback
1512 else:
1523 else:
1513 self.write_err('No traceback available to show.\n')
1524 self.write_err('No traceback available to show.\n')
1514 return
1525 return
1515
1526
1516 if etype is SyntaxError:
1527 if etype is SyntaxError:
1517 # Though this won't be called by syntax errors in the input
1528 # Though this won't be called by syntax errors in the input
1518 # line, there may be SyntaxError cases whith imported code.
1529 # line, there may be SyntaxError cases whith imported code.
1519 self.showsyntaxerror(filename)
1530 self.showsyntaxerror(filename)
1520 elif etype is UsageError:
1531 elif etype is UsageError:
1521 print "UsageError:", value
1532 print "UsageError:", value
1522 else:
1533 else:
1523 # WARNING: these variables are somewhat deprecated and not
1534 # WARNING: these variables are somewhat deprecated and not
1524 # necessarily safe to use in a threaded environment, but tools
1535 # necessarily safe to use in a threaded environment, but tools
1525 # like pdb depend on their existence, so let's set them. If we
1536 # like pdb depend on their existence, so let's set them. If we
1526 # find problems in the field, we'll need to revisit their use.
1537 # find problems in the field, we'll need to revisit their use.
1527 sys.last_type = etype
1538 sys.last_type = etype
1528 sys.last_value = value
1539 sys.last_value = value
1529 sys.last_traceback = tb
1540 sys.last_traceback = tb
1530 if etype in self.custom_exceptions:
1541 if etype in self.custom_exceptions:
1531 # FIXME: Old custom traceback objects may just return a
1542 # FIXME: Old custom traceback objects may just return a
1532 # string, in that case we just put it into a list
1543 # string, in that case we just put it into a list
1533 stb = self.CustomTB(etype, value, tb, tb_offset)
1544 stb = self.CustomTB(etype, value, tb, tb_offset)
1534 if isinstance(ctb, basestring):
1545 if isinstance(ctb, basestring):
1535 stb = [stb]
1546 stb = [stb]
1536 else:
1547 else:
1537 if exception_only:
1548 if exception_only:
1538 stb = ['An exception has occurred, use %tb to see '
1549 stb = ['An exception has occurred, use %tb to see '
1539 'the full traceback.\n']
1550 'the full traceback.\n']
1540 stb.extend(self.InteractiveTB.get_exception_only(etype,
1551 stb.extend(self.InteractiveTB.get_exception_only(etype,
1541 value))
1552 value))
1542 else:
1553 else:
1543 stb = self.InteractiveTB.structured_traceback(etype,
1554 stb = self.InteractiveTB.structured_traceback(etype,
1544 value, tb, tb_offset=tb_offset)
1555 value, tb, tb_offset=tb_offset)
1545
1556
1546 if self.call_pdb:
1557 if self.call_pdb:
1547 # drop into debugger
1558 # drop into debugger
1548 self.debugger(force=True)
1559 self.debugger(force=True)
1549
1560
1550 # Actually show the traceback
1561 # Actually show the traceback
1551 self._showtraceback(etype, value, stb)
1562 self._showtraceback(etype, value, stb)
1552
1563
1553 except KeyboardInterrupt:
1564 except KeyboardInterrupt:
1554 self.write_err("\nKeyboardInterrupt\n")
1565 self.write_err("\nKeyboardInterrupt\n")
1555
1566
1556 def _showtraceback(self, etype, evalue, stb):
1567 def _showtraceback(self, etype, evalue, stb):
1557 """Actually show a traceback.
1568 """Actually show a traceback.
1558
1569
1559 Subclasses may override this method to put the traceback on a different
1570 Subclasses may override this method to put the traceback on a different
1560 place, like a side channel.
1571 place, like a side channel.
1561 """
1572 """
1562 print >> io.stdout, self.InteractiveTB.stb2text(stb)
1573 print >> io.stdout, self.InteractiveTB.stb2text(stb)
1563
1574
1564 def showsyntaxerror(self, filename=None):
1575 def showsyntaxerror(self, filename=None):
1565 """Display the syntax error that just occurred.
1576 """Display the syntax error that just occurred.
1566
1577
1567 This doesn't display a stack trace because there isn't one.
1578 This doesn't display a stack trace because there isn't one.
1568
1579
1569 If a filename is given, it is stuffed in the exception instead
1580 If a filename is given, it is stuffed in the exception instead
1570 of what was there before (because Python's parser always uses
1581 of what was there before (because Python's parser always uses
1571 "<string>" when reading from a string).
1582 "<string>" when reading from a string).
1572 """
1583 """
1573 etype, value, last_traceback = sys.exc_info()
1584 etype, value, last_traceback = sys.exc_info()
1574
1585
1575 # See note about these variables in showtraceback() above
1586 # See note about these variables in showtraceback() above
1576 sys.last_type = etype
1587 sys.last_type = etype
1577 sys.last_value = value
1588 sys.last_value = value
1578 sys.last_traceback = last_traceback
1589 sys.last_traceback = last_traceback
1579
1590
1580 if filename and etype is SyntaxError:
1591 if filename and etype is SyntaxError:
1581 # Work hard to stuff the correct filename in the exception
1592 # Work hard to stuff the correct filename in the exception
1582 try:
1593 try:
1583 msg, (dummy_filename, lineno, offset, line) = value
1594 msg, (dummy_filename, lineno, offset, line) = value
1584 except:
1595 except:
1585 # Not the format we expect; leave it alone
1596 # Not the format we expect; leave it alone
1586 pass
1597 pass
1587 else:
1598 else:
1588 # Stuff in the right filename
1599 # Stuff in the right filename
1589 try:
1600 try:
1590 # Assume SyntaxError is a class exception
1601 # Assume SyntaxError is a class exception
1591 value = SyntaxError(msg, (filename, lineno, offset, line))
1602 value = SyntaxError(msg, (filename, lineno, offset, line))
1592 except:
1603 except:
1593 # If that failed, assume SyntaxError is a string
1604 # If that failed, assume SyntaxError is a string
1594 value = msg, (filename, lineno, offset, line)
1605 value = msg, (filename, lineno, offset, line)
1595 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1606 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1596 self._showtraceback(etype, value, stb)
1607 self._showtraceback(etype, value, stb)
1597
1608
1598 #-------------------------------------------------------------------------
1609 #-------------------------------------------------------------------------
1599 # Things related to readline
1610 # Things related to readline
1600 #-------------------------------------------------------------------------
1611 #-------------------------------------------------------------------------
1601
1612
1602 def init_readline(self):
1613 def init_readline(self):
1603 """Command history completion/saving/reloading."""
1614 """Command history completion/saving/reloading."""
1604
1615
1605 if self.readline_use:
1616 if self.readline_use:
1606 import IPython.utils.rlineimpl as readline
1617 import IPython.utils.rlineimpl as readline
1607
1618
1608 self.rl_next_input = None
1619 self.rl_next_input = None
1609 self.rl_do_indent = False
1620 self.rl_do_indent = False
1610
1621
1611 if not self.readline_use or not readline.have_readline:
1622 if not self.readline_use or not readline.have_readline:
1612 self.has_readline = False
1623 self.has_readline = False
1613 self.readline = None
1624 self.readline = None
1614 # Set a number of methods that depend on readline to be no-op
1625 # Set a number of methods that depend on readline to be no-op
1615 self.set_readline_completer = no_op
1626 self.set_readline_completer = no_op
1616 self.set_custom_completer = no_op
1627 self.set_custom_completer = no_op
1617 self.set_completer_frame = no_op
1628 self.set_completer_frame = no_op
1618 warn('Readline services not available or not loaded.')
1629 warn('Readline services not available or not loaded.')
1619 else:
1630 else:
1620 self.has_readline = True
1631 self.has_readline = True
1621 self.readline = readline
1632 self.readline = readline
1622 sys.modules['readline'] = readline
1633 sys.modules['readline'] = readline
1623
1634
1624 # Platform-specific configuration
1635 # Platform-specific configuration
1625 if os.name == 'nt':
1636 if os.name == 'nt':
1626 # FIXME - check with Frederick to see if we can harmonize
1637 # FIXME - check with Frederick to see if we can harmonize
1627 # naming conventions with pyreadline to avoid this
1638 # naming conventions with pyreadline to avoid this
1628 # platform-dependent check
1639 # platform-dependent check
1629 self.readline_startup_hook = readline.set_pre_input_hook
1640 self.readline_startup_hook = readline.set_pre_input_hook
1630 else:
1641 else:
1631 self.readline_startup_hook = readline.set_startup_hook
1642 self.readline_startup_hook = readline.set_startup_hook
1632
1643
1633 # Load user's initrc file (readline config)
1644 # Load user's initrc file (readline config)
1634 # Or if libedit is used, load editrc.
1645 # Or if libedit is used, load editrc.
1635 inputrc_name = os.environ.get('INPUTRC')
1646 inputrc_name = os.environ.get('INPUTRC')
1636 if inputrc_name is None:
1647 if inputrc_name is None:
1637 home_dir = get_home_dir()
1648 home_dir = get_home_dir()
1638 if home_dir is not None:
1649 if home_dir is not None:
1639 inputrc_name = '.inputrc'
1650 inputrc_name = '.inputrc'
1640 if readline.uses_libedit:
1651 if readline.uses_libedit:
1641 inputrc_name = '.editrc'
1652 inputrc_name = '.editrc'
1642 inputrc_name = os.path.join(home_dir, inputrc_name)
1653 inputrc_name = os.path.join(home_dir, inputrc_name)
1643 if os.path.isfile(inputrc_name):
1654 if os.path.isfile(inputrc_name):
1644 try:
1655 try:
1645 readline.read_init_file(inputrc_name)
1656 readline.read_init_file(inputrc_name)
1646 except:
1657 except:
1647 warn('Problems reading readline initialization file <%s>'
1658 warn('Problems reading readline initialization file <%s>'
1648 % inputrc_name)
1659 % inputrc_name)
1649
1660
1650 # Configure readline according to user's prefs
1661 # Configure readline according to user's prefs
1651 # This is only done if GNU readline is being used. If libedit
1662 # This is only done if GNU readline is being used. If libedit
1652 # is being used (as on Leopard) the readline config is
1663 # is being used (as on Leopard) the readline config is
1653 # not run as the syntax for libedit is different.
1664 # not run as the syntax for libedit is different.
1654 if not readline.uses_libedit:
1665 if not readline.uses_libedit:
1655 for rlcommand in self.readline_parse_and_bind:
1666 for rlcommand in self.readline_parse_and_bind:
1656 #print "loading rl:",rlcommand # dbg
1667 #print "loading rl:",rlcommand # dbg
1657 readline.parse_and_bind(rlcommand)
1668 readline.parse_and_bind(rlcommand)
1658
1669
1659 # Remove some chars from the delimiters list. If we encounter
1670 # Remove some chars from the delimiters list. If we encounter
1660 # unicode chars, discard them.
1671 # unicode chars, discard them.
1661 delims = readline.get_completer_delims().encode("ascii", "ignore")
1672 delims = readline.get_completer_delims().encode("ascii", "ignore")
1662 delims = delims.translate(None, self.readline_remove_delims)
1673 delims = delims.translate(None, self.readline_remove_delims)
1663 delims = delims.replace(ESC_MAGIC, '')
1674 delims = delims.replace(ESC_MAGIC, '')
1664 readline.set_completer_delims(delims)
1675 readline.set_completer_delims(delims)
1665 # otherwise we end up with a monster history after a while:
1676 # otherwise we end up with a monster history after a while:
1666 readline.set_history_length(self.history_length)
1677 readline.set_history_length(self.history_length)
1667
1678
1668 self.refill_readline_hist()
1679 self.refill_readline_hist()
1669 self.readline_no_record = ReadlineNoRecord(self)
1680 self.readline_no_record = ReadlineNoRecord(self)
1670
1681
1671 # Configure auto-indent for all platforms
1682 # Configure auto-indent for all platforms
1672 self.set_autoindent(self.autoindent)
1683 self.set_autoindent(self.autoindent)
1673
1684
1674 def refill_readline_hist(self):
1685 def refill_readline_hist(self):
1675 # Load the last 1000 lines from history
1686 # Load the last 1000 lines from history
1676 self.readline.clear_history()
1687 self.readline.clear_history()
1677 stdin_encoding = sys.stdin.encoding or "utf-8"
1688 stdin_encoding = sys.stdin.encoding or "utf-8"
1678 for _, _, cell in self.history_manager.get_tail(1000,
1689 for _, _, cell in self.history_manager.get_tail(1000,
1679 include_latest=True):
1690 include_latest=True):
1680 if cell.strip(): # Ignore blank lines
1691 if cell.strip(): # Ignore blank lines
1681 for line in cell.splitlines():
1692 for line in cell.splitlines():
1682 self.readline.add_history(line.encode(stdin_encoding, 'replace'))
1693 self.readline.add_history(line.encode(stdin_encoding, 'replace'))
1683
1694
1684 def set_next_input(self, s):
1695 def set_next_input(self, s):
1685 """ Sets the 'default' input string for the next command line.
1696 """ Sets the 'default' input string for the next command line.
1686
1697
1687 Requires readline.
1698 Requires readline.
1688
1699
1689 Example:
1700 Example:
1690
1701
1691 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1702 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1692 [D:\ipython]|2> Hello Word_ # cursor is here
1703 [D:\ipython]|2> Hello Word_ # cursor is here
1693 """
1704 """
1694
1705
1695 self.rl_next_input = s
1706 self.rl_next_input = s
1696
1707
1697 # Maybe move this to the terminal subclass?
1708 # Maybe move this to the terminal subclass?
1698 def pre_readline(self):
1709 def pre_readline(self):
1699 """readline hook to be used at the start of each line.
1710 """readline hook to be used at the start of each line.
1700
1711
1701 Currently it handles auto-indent only."""
1712 Currently it handles auto-indent only."""
1702
1713
1703 if self.rl_do_indent:
1714 if self.rl_do_indent:
1704 self.readline.insert_text(self._indent_current_str())
1715 self.readline.insert_text(self._indent_current_str())
1705 if self.rl_next_input is not None:
1716 if self.rl_next_input is not None:
1706 self.readline.insert_text(self.rl_next_input)
1717 self.readline.insert_text(self.rl_next_input)
1707 self.rl_next_input = None
1718 self.rl_next_input = None
1708
1719
1709 def _indent_current_str(self):
1720 def _indent_current_str(self):
1710 """return the current level of indentation as a string"""
1721 """return the current level of indentation as a string"""
1711 return self.input_splitter.indent_spaces * ' '
1722 return self.input_splitter.indent_spaces * ' '
1712
1723
1713 #-------------------------------------------------------------------------
1724 #-------------------------------------------------------------------------
1714 # Things related to text completion
1725 # Things related to text completion
1715 #-------------------------------------------------------------------------
1726 #-------------------------------------------------------------------------
1716
1727
1717 def init_completer(self):
1728 def init_completer(self):
1718 """Initialize the completion machinery.
1729 """Initialize the completion machinery.
1719
1730
1720 This creates completion machinery that can be used by client code,
1731 This creates completion machinery that can be used by client code,
1721 either interactively in-process (typically triggered by the readline
1732 either interactively in-process (typically triggered by the readline
1722 library), programatically (such as in test suites) or out-of-prcess
1733 library), programatically (such as in test suites) or out-of-prcess
1723 (typically over the network by remote frontends).
1734 (typically over the network by remote frontends).
1724 """
1735 """
1725 from IPython.core.completer import IPCompleter
1736 from IPython.core.completer import IPCompleter
1726 from IPython.core.completerlib import (module_completer,
1737 from IPython.core.completerlib import (module_completer,
1727 magic_run_completer, cd_completer)
1738 magic_run_completer, cd_completer)
1728
1739
1729 self.Completer = IPCompleter(self,
1740 self.Completer = IPCompleter(self,
1730 self.user_ns,
1741 self.user_ns,
1731 self.user_global_ns,
1742 self.user_global_ns,
1732 self.readline_omit__names,
1743 self.readline_omit__names,
1733 self.alias_manager.alias_table,
1744 self.alias_manager.alias_table,
1734 self.has_readline)
1745 self.has_readline)
1735
1746
1736 # Add custom completers to the basic ones built into IPCompleter
1747 # Add custom completers to the basic ones built into IPCompleter
1737 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1748 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1738 self.strdispatchers['complete_command'] = sdisp
1749 self.strdispatchers['complete_command'] = sdisp
1739 self.Completer.custom_completers = sdisp
1750 self.Completer.custom_completers = sdisp
1740
1751
1741 self.set_hook('complete_command', module_completer, str_key = 'import')
1752 self.set_hook('complete_command', module_completer, str_key = 'import')
1742 self.set_hook('complete_command', module_completer, str_key = 'from')
1753 self.set_hook('complete_command', module_completer, str_key = 'from')
1743 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1754 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1744 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1755 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1745
1756
1746 # Only configure readline if we truly are using readline. IPython can
1757 # Only configure readline if we truly are using readline. IPython can
1747 # do tab-completion over the network, in GUIs, etc, where readline
1758 # do tab-completion over the network, in GUIs, etc, where readline
1748 # itself may be absent
1759 # itself may be absent
1749 if self.has_readline:
1760 if self.has_readline:
1750 self.set_readline_completer()
1761 self.set_readline_completer()
1751
1762
1752 def complete(self, text, line=None, cursor_pos=None):
1763 def complete(self, text, line=None, cursor_pos=None):
1753 """Return the completed text and a list of completions.
1764 """Return the completed text and a list of completions.
1754
1765
1755 Parameters
1766 Parameters
1756 ----------
1767 ----------
1757
1768
1758 text : string
1769 text : string
1759 A string of text to be completed on. It can be given as empty and
1770 A string of text to be completed on. It can be given as empty and
1760 instead a line/position pair are given. In this case, the
1771 instead a line/position pair are given. In this case, the
1761 completer itself will split the line like readline does.
1772 completer itself will split the line like readline does.
1762
1773
1763 line : string, optional
1774 line : string, optional
1764 The complete line that text is part of.
1775 The complete line that text is part of.
1765
1776
1766 cursor_pos : int, optional
1777 cursor_pos : int, optional
1767 The position of the cursor on the input line.
1778 The position of the cursor on the input line.
1768
1779
1769 Returns
1780 Returns
1770 -------
1781 -------
1771 text : string
1782 text : string
1772 The actual text that was completed.
1783 The actual text that was completed.
1773
1784
1774 matches : list
1785 matches : list
1775 A sorted list with all possible completions.
1786 A sorted list with all possible completions.
1776
1787
1777 The optional arguments allow the completion to take more context into
1788 The optional arguments allow the completion to take more context into
1778 account, and are part of the low-level completion API.
1789 account, and are part of the low-level completion API.
1779
1790
1780 This is a wrapper around the completion mechanism, similar to what
1791 This is a wrapper around the completion mechanism, similar to what
1781 readline does at the command line when the TAB key is hit. By
1792 readline does at the command line when the TAB key is hit. By
1782 exposing it as a method, it can be used by other non-readline
1793 exposing it as a method, it can be used by other non-readline
1783 environments (such as GUIs) for text completion.
1794 environments (such as GUIs) for text completion.
1784
1795
1785 Simple usage example:
1796 Simple usage example:
1786
1797
1787 In [1]: x = 'hello'
1798 In [1]: x = 'hello'
1788
1799
1789 In [2]: _ip.complete('x.l')
1800 In [2]: _ip.complete('x.l')
1790 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1801 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1791 """
1802 """
1792
1803
1793 # Inject names into __builtin__ so we can complete on the added names.
1804 # Inject names into __builtin__ so we can complete on the added names.
1794 with self.builtin_trap:
1805 with self.builtin_trap:
1795 return self.Completer.complete(text, line, cursor_pos)
1806 return self.Completer.complete(text, line, cursor_pos)
1796
1807
1797 def set_custom_completer(self, completer, pos=0):
1808 def set_custom_completer(self, completer, pos=0):
1798 """Adds a new custom completer function.
1809 """Adds a new custom completer function.
1799
1810
1800 The position argument (defaults to 0) is the index in the completers
1811 The position argument (defaults to 0) is the index in the completers
1801 list where you want the completer to be inserted."""
1812 list where you want the completer to be inserted."""
1802
1813
1803 newcomp = types.MethodType(completer,self.Completer)
1814 newcomp = types.MethodType(completer,self.Completer)
1804 self.Completer.matchers.insert(pos,newcomp)
1815 self.Completer.matchers.insert(pos,newcomp)
1805
1816
1806 def set_readline_completer(self):
1817 def set_readline_completer(self):
1807 """Reset readline's completer to be our own."""
1818 """Reset readline's completer to be our own."""
1808 self.readline.set_completer(self.Completer.rlcomplete)
1819 self.readline.set_completer(self.Completer.rlcomplete)
1809
1820
1810 def set_completer_frame(self, frame=None):
1821 def set_completer_frame(self, frame=None):
1811 """Set the frame of the completer."""
1822 """Set the frame of the completer."""
1812 if frame:
1823 if frame:
1813 self.Completer.namespace = frame.f_locals
1824 self.Completer.namespace = frame.f_locals
1814 self.Completer.global_namespace = frame.f_globals
1825 self.Completer.global_namespace = frame.f_globals
1815 else:
1826 else:
1816 self.Completer.namespace = self.user_ns
1827 self.Completer.namespace = self.user_ns
1817 self.Completer.global_namespace = self.user_global_ns
1828 self.Completer.global_namespace = self.user_global_ns
1818
1829
1819 #-------------------------------------------------------------------------
1830 #-------------------------------------------------------------------------
1820 # Things related to magics
1831 # Things related to magics
1821 #-------------------------------------------------------------------------
1832 #-------------------------------------------------------------------------
1822
1833
1823 def init_magics(self):
1834 def init_magics(self):
1824 # FIXME: Move the color initialization to the DisplayHook, which
1835 # FIXME: Move the color initialization to the DisplayHook, which
1825 # should be split into a prompt manager and displayhook. We probably
1836 # should be split into a prompt manager and displayhook. We probably
1826 # even need a centralize colors management object.
1837 # even need a centralize colors management object.
1827 self.magic_colors(self.colors)
1838 self.magic_colors(self.colors)
1828 # History was moved to a separate module
1839 # History was moved to a separate module
1829 from . import history
1840 from . import history
1830 history.init_ipython(self)
1841 history.init_ipython(self)
1831
1842
1832 def magic(self,arg_s):
1843 def magic(self,arg_s):
1833 """Call a magic function by name.
1844 """Call a magic function by name.
1834
1845
1835 Input: a string containing the name of the magic function to call and
1846 Input: a string containing the name of the magic function to call and
1836 any additional arguments to be passed to the magic.
1847 any additional arguments to be passed to the magic.
1837
1848
1838 magic('name -opt foo bar') is equivalent to typing at the ipython
1849 magic('name -opt foo bar') is equivalent to typing at the ipython
1839 prompt:
1850 prompt:
1840
1851
1841 In[1]: %name -opt foo bar
1852 In[1]: %name -opt foo bar
1842
1853
1843 To call a magic without arguments, simply use magic('name').
1854 To call a magic without arguments, simply use magic('name').
1844
1855
1845 This provides a proper Python function to call IPython's magics in any
1856 This provides a proper Python function to call IPython's magics in any
1846 valid Python code you can type at the interpreter, including loops and
1857 valid Python code you can type at the interpreter, including loops and
1847 compound statements.
1858 compound statements.
1848 """
1859 """
1849 args = arg_s.split(' ',1)
1860 args = arg_s.split(' ',1)
1850 magic_name = args[0]
1861 magic_name = args[0]
1851 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1862 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1852
1863
1853 try:
1864 try:
1854 magic_args = args[1]
1865 magic_args = args[1]
1855 except IndexError:
1866 except IndexError:
1856 magic_args = ''
1867 magic_args = ''
1857 fn = getattr(self,'magic_'+magic_name,None)
1868 fn = getattr(self,'magic_'+magic_name,None)
1858 if fn is None:
1869 if fn is None:
1859 error("Magic function `%s` not found." % magic_name)
1870 error("Magic function `%s` not found." % magic_name)
1860 else:
1871 else:
1861 magic_args = self.var_expand(magic_args,1)
1872 magic_args = self.var_expand(magic_args,1)
1862 # Grab local namespace if we need it:
1873 # Grab local namespace if we need it:
1863 if getattr(fn, "needs_local_scope", False):
1874 if getattr(fn, "needs_local_scope", False):
1864 self._magic_locals = sys._getframe(1).f_locals
1875 self._magic_locals = sys._getframe(1).f_locals
1865 with self.builtin_trap:
1876 with self.builtin_trap:
1866 result = fn(magic_args)
1877 result = fn(magic_args)
1867 # Ensure we're not keeping object references around:
1878 # Ensure we're not keeping object references around:
1868 self._magic_locals = {}
1879 self._magic_locals = {}
1869 return result
1880 return result
1870
1881
1871 def define_magic(self, magicname, func):
1882 def define_magic(self, magicname, func):
1872 """Expose own function as magic function for ipython
1883 """Expose own function as magic function for ipython
1873
1884
1874 def foo_impl(self,parameter_s=''):
1885 def foo_impl(self,parameter_s=''):
1875 'My very own magic!. (Use docstrings, IPython reads them).'
1886 'My very own magic!. (Use docstrings, IPython reads them).'
1876 print 'Magic function. Passed parameter is between < >:'
1887 print 'Magic function. Passed parameter is between < >:'
1877 print '<%s>' % parameter_s
1888 print '<%s>' % parameter_s
1878 print 'The self object is:',self
1889 print 'The self object is:',self
1879
1890
1880 self.define_magic('foo',foo_impl)
1891 self.define_magic('foo',foo_impl)
1881 """
1892 """
1882
1893
1883 import new
1894 import new
1884 im = types.MethodType(func,self)
1895 im = types.MethodType(func,self)
1885 old = getattr(self, "magic_" + magicname, None)
1896 old = getattr(self, "magic_" + magicname, None)
1886 setattr(self, "magic_" + magicname, im)
1897 setattr(self, "magic_" + magicname, im)
1887 return old
1898 return old
1888
1899
1889 #-------------------------------------------------------------------------
1900 #-------------------------------------------------------------------------
1890 # Things related to macros
1901 # Things related to macros
1891 #-------------------------------------------------------------------------
1902 #-------------------------------------------------------------------------
1892
1903
1893 def define_macro(self, name, themacro):
1904 def define_macro(self, name, themacro):
1894 """Define a new macro
1905 """Define a new macro
1895
1906
1896 Parameters
1907 Parameters
1897 ----------
1908 ----------
1898 name : str
1909 name : str
1899 The name of the macro.
1910 The name of the macro.
1900 themacro : str or Macro
1911 themacro : str or Macro
1901 The action to do upon invoking the macro. If a string, a new
1912 The action to do upon invoking the macro. If a string, a new
1902 Macro object is created by passing the string to it.
1913 Macro object is created by passing the string to it.
1903 """
1914 """
1904
1915
1905 from IPython.core import macro
1916 from IPython.core import macro
1906
1917
1907 if isinstance(themacro, basestring):
1918 if isinstance(themacro, basestring):
1908 themacro = macro.Macro(themacro)
1919 themacro = macro.Macro(themacro)
1909 if not isinstance(themacro, macro.Macro):
1920 if not isinstance(themacro, macro.Macro):
1910 raise ValueError('A macro must be a string or a Macro instance.')
1921 raise ValueError('A macro must be a string or a Macro instance.')
1911 self.user_ns[name] = themacro
1922 self.user_ns[name] = themacro
1912
1923
1913 #-------------------------------------------------------------------------
1924 #-------------------------------------------------------------------------
1914 # Things related to the running of system commands
1925 # Things related to the running of system commands
1915 #-------------------------------------------------------------------------
1926 #-------------------------------------------------------------------------
1916
1927
1917 def system_piped(self, cmd):
1928 def system_piped(self, cmd):
1918 """Call the given cmd in a subprocess, piping stdout/err
1929 """Call the given cmd in a subprocess, piping stdout/err
1919
1930
1920 Parameters
1931 Parameters
1921 ----------
1932 ----------
1922 cmd : str
1933 cmd : str
1923 Command to execute (can not end in '&', as background processes are
1934 Command to execute (can not end in '&', as background processes are
1924 not supported. Should not be a command that expects input
1935 not supported. Should not be a command that expects input
1925 other than simple text.
1936 other than simple text.
1926 """
1937 """
1927 if cmd.rstrip().endswith('&'):
1938 if cmd.rstrip().endswith('&'):
1928 # this is *far* from a rigorous test
1939 # this is *far* from a rigorous test
1929 # We do not support backgrounding processes because we either use
1940 # We do not support backgrounding processes because we either use
1930 # pexpect or pipes to read from. Users can always just call
1941 # pexpect or pipes to read from. Users can always just call
1931 # os.system() or use ip.system=ip.system_raw
1942 # os.system() or use ip.system=ip.system_raw
1932 # if they really want a background process.
1943 # if they really want a background process.
1933 raise OSError("Background processes not supported.")
1944 raise OSError("Background processes not supported.")
1934
1945
1935 # we explicitly do NOT return the subprocess status code, because
1946 # we explicitly do NOT return the subprocess status code, because
1936 # a non-None value would trigger :func:`sys.displayhook` calls.
1947 # a non-None value would trigger :func:`sys.displayhook` calls.
1937 # Instead, we store the exit_code in user_ns.
1948 # Instead, we store the exit_code in user_ns.
1938 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=2))
1949 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=2))
1939
1950
1940 def system_raw(self, cmd):
1951 def system_raw(self, cmd):
1941 """Call the given cmd in a subprocess using os.system
1952 """Call the given cmd in a subprocess using os.system
1942
1953
1943 Parameters
1954 Parameters
1944 ----------
1955 ----------
1945 cmd : str
1956 cmd : str
1946 Command to execute.
1957 Command to execute.
1947 """
1958 """
1948 # We explicitly do NOT return the subprocess status code, because
1959 # We explicitly do NOT return the subprocess status code, because
1949 # a non-None value would trigger :func:`sys.displayhook` calls.
1960 # a non-None value would trigger :func:`sys.displayhook` calls.
1950 # Instead, we store the exit_code in user_ns.
1961 # Instead, we store the exit_code in user_ns.
1951 self.user_ns['_exit_code'] = os.system(self.var_expand(cmd, depth=2))
1962 self.user_ns['_exit_code'] = os.system(self.var_expand(cmd, depth=2))
1952
1963
1953 # use piped system by default, because it is better behaved
1964 # use piped system by default, because it is better behaved
1954 system = system_piped
1965 system = system_piped
1955
1966
1956 def getoutput(self, cmd, split=True):
1967 def getoutput(self, cmd, split=True):
1957 """Get output (possibly including stderr) from a subprocess.
1968 """Get output (possibly including stderr) from a subprocess.
1958
1969
1959 Parameters
1970 Parameters
1960 ----------
1971 ----------
1961 cmd : str
1972 cmd : str
1962 Command to execute (can not end in '&', as background processes are
1973 Command to execute (can not end in '&', as background processes are
1963 not supported.
1974 not supported.
1964 split : bool, optional
1975 split : bool, optional
1965
1976
1966 If True, split the output into an IPython SList. Otherwise, an
1977 If True, split the output into an IPython SList. Otherwise, an
1967 IPython LSString is returned. These are objects similar to normal
1978 IPython LSString is returned. These are objects similar to normal
1968 lists and strings, with a few convenience attributes for easier
1979 lists and strings, with a few convenience attributes for easier
1969 manipulation of line-based output. You can use '?' on them for
1980 manipulation of line-based output. You can use '?' on them for
1970 details.
1981 details.
1971 """
1982 """
1972 if cmd.rstrip().endswith('&'):
1983 if cmd.rstrip().endswith('&'):
1973 # this is *far* from a rigorous test
1984 # this is *far* from a rigorous test
1974 raise OSError("Background processes not supported.")
1985 raise OSError("Background processes not supported.")
1975 out = getoutput(self.var_expand(cmd, depth=2))
1986 out = getoutput(self.var_expand(cmd, depth=2))
1976 if split:
1987 if split:
1977 out = SList(out.splitlines())
1988 out = SList(out.splitlines())
1978 else:
1989 else:
1979 out = LSString(out)
1990 out = LSString(out)
1980 return out
1991 return out
1981
1992
1982 #-------------------------------------------------------------------------
1993 #-------------------------------------------------------------------------
1983 # Things related to aliases
1994 # Things related to aliases
1984 #-------------------------------------------------------------------------
1995 #-------------------------------------------------------------------------
1985
1996
1986 def init_alias(self):
1997 def init_alias(self):
1987 self.alias_manager = AliasManager(shell=self, config=self.config)
1998 self.alias_manager = AliasManager(shell=self, config=self.config)
1988 self.ns_table['alias'] = self.alias_manager.alias_table,
1999 self.ns_table['alias'] = self.alias_manager.alias_table,
1989
2000
1990 #-------------------------------------------------------------------------
2001 #-------------------------------------------------------------------------
1991 # Things related to extensions and plugins
2002 # Things related to extensions and plugins
1992 #-------------------------------------------------------------------------
2003 #-------------------------------------------------------------------------
1993
2004
1994 def init_extension_manager(self):
2005 def init_extension_manager(self):
1995 self.extension_manager = ExtensionManager(shell=self, config=self.config)
2006 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1996
2007
1997 def init_plugin_manager(self):
2008 def init_plugin_manager(self):
1998 self.plugin_manager = PluginManager(config=self.config)
2009 self.plugin_manager = PluginManager(config=self.config)
1999
2010
2000 #-------------------------------------------------------------------------
2011 #-------------------------------------------------------------------------
2001 # Things related to payloads
2012 # Things related to payloads
2002 #-------------------------------------------------------------------------
2013 #-------------------------------------------------------------------------
2003
2014
2004 def init_payload(self):
2015 def init_payload(self):
2005 self.payload_manager = PayloadManager(config=self.config)
2016 self.payload_manager = PayloadManager(config=self.config)
2006
2017
2007 #-------------------------------------------------------------------------
2018 #-------------------------------------------------------------------------
2008 # Things related to the prefilter
2019 # Things related to the prefilter
2009 #-------------------------------------------------------------------------
2020 #-------------------------------------------------------------------------
2010
2021
2011 def init_prefilter(self):
2022 def init_prefilter(self):
2012 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
2023 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
2013 # Ultimately this will be refactored in the new interpreter code, but
2024 # Ultimately this will be refactored in the new interpreter code, but
2014 # for now, we should expose the main prefilter method (there's legacy
2025 # for now, we should expose the main prefilter method (there's legacy
2015 # code out there that may rely on this).
2026 # code out there that may rely on this).
2016 self.prefilter = self.prefilter_manager.prefilter_lines
2027 self.prefilter = self.prefilter_manager.prefilter_lines
2017
2028
2018 def auto_rewrite_input(self, cmd):
2029 def auto_rewrite_input(self, cmd):
2019 """Print to the screen the rewritten form of the user's command.
2030 """Print to the screen the rewritten form of the user's command.
2020
2031
2021 This shows visual feedback by rewriting input lines that cause
2032 This shows visual feedback by rewriting input lines that cause
2022 automatic calling to kick in, like::
2033 automatic calling to kick in, like::
2023
2034
2024 /f x
2035 /f x
2025
2036
2026 into::
2037 into::
2027
2038
2028 ------> f(x)
2039 ------> f(x)
2029
2040
2030 after the user's input prompt. This helps the user understand that the
2041 after the user's input prompt. This helps the user understand that the
2031 input line was transformed automatically by IPython.
2042 input line was transformed automatically by IPython.
2032 """
2043 """
2033 rw = self.displayhook.prompt1.auto_rewrite() + cmd
2044 rw = self.displayhook.prompt1.auto_rewrite() + cmd
2034
2045
2035 try:
2046 try:
2036 # plain ascii works better w/ pyreadline, on some machines, so
2047 # plain ascii works better w/ pyreadline, on some machines, so
2037 # we use it and only print uncolored rewrite if we have unicode
2048 # we use it and only print uncolored rewrite if we have unicode
2038 rw = str(rw)
2049 rw = str(rw)
2039 print >> io.stdout, rw
2050 print >> io.stdout, rw
2040 except UnicodeEncodeError:
2051 except UnicodeEncodeError:
2041 print "------> " + cmd
2052 print "------> " + cmd
2042
2053
2043 #-------------------------------------------------------------------------
2054 #-------------------------------------------------------------------------
2044 # Things related to extracting values/expressions from kernel and user_ns
2055 # Things related to extracting values/expressions from kernel and user_ns
2045 #-------------------------------------------------------------------------
2056 #-------------------------------------------------------------------------
2046
2057
2047 def _simple_error(self):
2058 def _simple_error(self):
2048 etype, value = sys.exc_info()[:2]
2059 etype, value = sys.exc_info()[:2]
2049 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
2060 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
2050
2061
2051 def user_variables(self, names):
2062 def user_variables(self, names):
2052 """Get a list of variable names from the user's namespace.
2063 """Get a list of variable names from the user's namespace.
2053
2064
2054 Parameters
2065 Parameters
2055 ----------
2066 ----------
2056 names : list of strings
2067 names : list of strings
2057 A list of names of variables to be read from the user namespace.
2068 A list of names of variables to be read from the user namespace.
2058
2069
2059 Returns
2070 Returns
2060 -------
2071 -------
2061 A dict, keyed by the input names and with the repr() of each value.
2072 A dict, keyed by the input names and with the repr() of each value.
2062 """
2073 """
2063 out = {}
2074 out = {}
2064 user_ns = self.user_ns
2075 user_ns = self.user_ns
2065 for varname in names:
2076 for varname in names:
2066 try:
2077 try:
2067 value = repr(user_ns[varname])
2078 value = repr(user_ns[varname])
2068 except:
2079 except:
2069 value = self._simple_error()
2080 value = self._simple_error()
2070 out[varname] = value
2081 out[varname] = value
2071 return out
2082 return out
2072
2083
2073 def user_expressions(self, expressions):
2084 def user_expressions(self, expressions):
2074 """Evaluate a dict of expressions in the user's namespace.
2085 """Evaluate a dict of expressions in the user's namespace.
2075
2086
2076 Parameters
2087 Parameters
2077 ----------
2088 ----------
2078 expressions : dict
2089 expressions : dict
2079 A dict with string keys and string values. The expression values
2090 A dict with string keys and string values. The expression values
2080 should be valid Python expressions, each of which will be evaluated
2091 should be valid Python expressions, each of which will be evaluated
2081 in the user namespace.
2092 in the user namespace.
2082
2093
2083 Returns
2094 Returns
2084 -------
2095 -------
2085 A dict, keyed like the input expressions dict, with the repr() of each
2096 A dict, keyed like the input expressions dict, with the repr() of each
2086 value.
2097 value.
2087 """
2098 """
2088 out = {}
2099 out = {}
2089 user_ns = self.user_ns
2100 user_ns = self.user_ns
2090 global_ns = self.user_global_ns
2101 global_ns = self.user_global_ns
2091 for key, expr in expressions.iteritems():
2102 for key, expr in expressions.iteritems():
2092 try:
2103 try:
2093 value = repr(eval(expr, global_ns, user_ns))
2104 value = repr(eval(expr, global_ns, user_ns))
2094 except:
2105 except:
2095 value = self._simple_error()
2106 value = self._simple_error()
2096 out[key] = value
2107 out[key] = value
2097 return out
2108 return out
2098
2109
2099 #-------------------------------------------------------------------------
2110 #-------------------------------------------------------------------------
2100 # Things related to the running of code
2111 # Things related to the running of code
2101 #-------------------------------------------------------------------------
2112 #-------------------------------------------------------------------------
2102
2113
2103 def ex(self, cmd):
2114 def ex(self, cmd):
2104 """Execute a normal python statement in user namespace."""
2115 """Execute a normal python statement in user namespace."""
2105 with self.builtin_trap:
2116 with self.builtin_trap:
2106 exec cmd in self.user_global_ns, self.user_ns
2117 exec cmd in self.user_global_ns, self.user_ns
2107
2118
2108 def ev(self, expr):
2119 def ev(self, expr):
2109 """Evaluate python expression expr in user namespace.
2120 """Evaluate python expression expr in user namespace.
2110
2121
2111 Returns the result of evaluation
2122 Returns the result of evaluation
2112 """
2123 """
2113 with self.builtin_trap:
2124 with self.builtin_trap:
2114 return eval(expr, self.user_global_ns, self.user_ns)
2125 return eval(expr, self.user_global_ns, self.user_ns)
2115
2126
2116 def safe_execfile(self, fname, *where, **kw):
2127 def safe_execfile(self, fname, *where, **kw):
2117 """A safe version of the builtin execfile().
2128 """A safe version of the builtin execfile().
2118
2129
2119 This version will never throw an exception, but instead print
2130 This version will never throw an exception, but instead print
2120 helpful error messages to the screen. This only works on pure
2131 helpful error messages to the screen. This only works on pure
2121 Python files with the .py extension.
2132 Python files with the .py extension.
2122
2133
2123 Parameters
2134 Parameters
2124 ----------
2135 ----------
2125 fname : string
2136 fname : string
2126 The name of the file to be executed.
2137 The name of the file to be executed.
2127 where : tuple
2138 where : tuple
2128 One or two namespaces, passed to execfile() as (globals,locals).
2139 One or two namespaces, passed to execfile() as (globals,locals).
2129 If only one is given, it is passed as both.
2140 If only one is given, it is passed as both.
2130 exit_ignore : bool (False)
2141 exit_ignore : bool (False)
2131 If True, then silence SystemExit for non-zero status (it is always
2142 If True, then silence SystemExit for non-zero status (it is always
2132 silenced for zero status, as it is so common).
2143 silenced for zero status, as it is so common).
2133 """
2144 """
2134 kw.setdefault('exit_ignore', False)
2145 kw.setdefault('exit_ignore', False)
2135
2146
2136 fname = os.path.abspath(os.path.expanduser(fname))
2147 fname = os.path.abspath(os.path.expanduser(fname))
2137 # Make sure we have a .py file
2148 # Make sure we have a .py file
2138 if not fname.endswith('.py'):
2149 if not fname.endswith('.py'):
2139 warn('File must end with .py to be run using execfile: <%s>' % fname)
2150 warn('File must end with .py to be run using execfile: <%s>' % fname)
2140
2151
2141 # Make sure we can open the file
2152 # Make sure we can open the file
2142 try:
2153 try:
2143 with open(fname) as thefile:
2154 with open(fname) as thefile:
2144 pass
2155 pass
2145 except:
2156 except:
2146 warn('Could not open file <%s> for safe execution.' % fname)
2157 warn('Could not open file <%s> for safe execution.' % fname)
2147 return
2158 return
2148
2159
2149 # Find things also in current directory. This is needed to mimic the
2160 # Find things also in current directory. This is needed to mimic the
2150 # behavior of running a script from the system command line, where
2161 # behavior of running a script from the system command line, where
2151 # Python inserts the script's directory into sys.path
2162 # Python inserts the script's directory into sys.path
2152 dname = os.path.dirname(fname)
2163 dname = os.path.dirname(fname)
2153
2164
2154 if isinstance(fname, unicode):
2165 if isinstance(fname, unicode):
2155 # execfile uses default encoding instead of filesystem encoding
2166 # execfile uses default encoding instead of filesystem encoding
2156 # so unicode filenames will fail
2167 # so unicode filenames will fail
2157 fname = fname.encode(sys.getfilesystemencoding() or sys.getdefaultencoding())
2168 fname = fname.encode(sys.getfilesystemencoding() or sys.getdefaultencoding())
2158
2169
2159 with prepended_to_syspath(dname):
2170 with prepended_to_syspath(dname):
2160 try:
2171 try:
2161 execfile(fname,*where)
2172 execfile(fname,*where)
2162 except SystemExit, status:
2173 except SystemExit, status:
2163 # If the call was made with 0 or None exit status (sys.exit(0)
2174 # If the call was made with 0 or None exit status (sys.exit(0)
2164 # or sys.exit() ), don't bother showing a traceback, as both of
2175 # or sys.exit() ), don't bother showing a traceback, as both of
2165 # these are considered normal by the OS:
2176 # these are considered normal by the OS:
2166 # > python -c'import sys;sys.exit(0)'; echo $?
2177 # > python -c'import sys;sys.exit(0)'; echo $?
2167 # 0
2178 # 0
2168 # > python -c'import sys;sys.exit()'; echo $?
2179 # > python -c'import sys;sys.exit()'; echo $?
2169 # 0
2180 # 0
2170 # For other exit status, we show the exception unless
2181 # For other exit status, we show the exception unless
2171 # explicitly silenced, but only in short form.
2182 # explicitly silenced, but only in short form.
2172 if status.code not in (0, None) and not kw['exit_ignore']:
2183 if status.code not in (0, None) and not kw['exit_ignore']:
2173 self.showtraceback(exception_only=True)
2184 self.showtraceback(exception_only=True)
2174 except:
2185 except:
2175 self.showtraceback()
2186 self.showtraceback()
2176
2187
2177 def safe_execfile_ipy(self, fname):
2188 def safe_execfile_ipy(self, fname):
2178 """Like safe_execfile, but for .ipy files with IPython syntax.
2189 """Like safe_execfile, but for .ipy files with IPython syntax.
2179
2190
2180 Parameters
2191 Parameters
2181 ----------
2192 ----------
2182 fname : str
2193 fname : str
2183 The name of the file to execute. The filename must have a
2194 The name of the file to execute. The filename must have a
2184 .ipy extension.
2195 .ipy extension.
2185 """
2196 """
2186 fname = os.path.abspath(os.path.expanduser(fname))
2197 fname = os.path.abspath(os.path.expanduser(fname))
2187
2198
2188 # Make sure we have a .py file
2199 # Make sure we have a .py file
2189 if not fname.endswith('.ipy'):
2200 if not fname.endswith('.ipy'):
2190 warn('File must end with .py to be run using execfile: <%s>' % fname)
2201 warn('File must end with .py to be run using execfile: <%s>' % fname)
2191
2202
2192 # Make sure we can open the file
2203 # Make sure we can open the file
2193 try:
2204 try:
2194 with open(fname) as thefile:
2205 with open(fname) as thefile:
2195 pass
2206 pass
2196 except:
2207 except:
2197 warn('Could not open file <%s> for safe execution.' % fname)
2208 warn('Could not open file <%s> for safe execution.' % fname)
2198 return
2209 return
2199
2210
2200 # Find things also in current directory. This is needed to mimic the
2211 # Find things also in current directory. This is needed to mimic the
2201 # behavior of running a script from the system command line, where
2212 # behavior of running a script from the system command line, where
2202 # Python inserts the script's directory into sys.path
2213 # Python inserts the script's directory into sys.path
2203 dname = os.path.dirname(fname)
2214 dname = os.path.dirname(fname)
2204
2215
2205 with prepended_to_syspath(dname):
2216 with prepended_to_syspath(dname):
2206 try:
2217 try:
2207 with open(fname) as thefile:
2218 with open(fname) as thefile:
2208 # self.run_cell currently captures all exceptions
2219 # self.run_cell currently captures all exceptions
2209 # raised in user code. It would be nice if there were
2220 # raised in user code. It would be nice if there were
2210 # versions of runlines, execfile that did raise, so
2221 # versions of runlines, execfile that did raise, so
2211 # we could catch the errors.
2222 # we could catch the errors.
2212 self.run_cell(thefile.read(), store_history=False)
2223 self.run_cell(thefile.read(), store_history=False)
2213 except:
2224 except:
2214 self.showtraceback()
2225 self.showtraceback()
2215 warn('Unknown failure executing file: <%s>' % fname)
2226 warn('Unknown failure executing file: <%s>' % fname)
2216
2227
2217 def run_cell(self, raw_cell, store_history=True):
2228 def run_cell(self, raw_cell, store_history=True):
2218 """Run a complete IPython cell.
2229 """Run a complete IPython cell.
2219
2230
2220 Parameters
2231 Parameters
2221 ----------
2232 ----------
2222 raw_cell : str
2233 raw_cell : str
2223 The code (including IPython code such as %magic functions) to run.
2234 The code (including IPython code such as %magic functions) to run.
2224 store_history : bool
2235 store_history : bool
2225 If True, the raw and translated cell will be stored in IPython's
2236 If True, the raw and translated cell will be stored in IPython's
2226 history. For user code calling back into IPython's machinery, this
2237 history. For user code calling back into IPython's machinery, this
2227 should be set to False.
2238 should be set to False.
2228 """
2239 """
2229 if (not raw_cell) or raw_cell.isspace():
2240 if (not raw_cell) or raw_cell.isspace():
2230 return
2241 return
2231
2242
2232 for line in raw_cell.splitlines():
2243 for line in raw_cell.splitlines():
2233 self.input_splitter.push(line)
2244 self.input_splitter.push(line)
2234 cell = self.input_splitter.source_reset()
2245 cell = self.input_splitter.source_reset()
2235
2246
2236 with self.builtin_trap:
2247 with self.builtin_trap:
2237 prefilter_failed = False
2248 prefilter_failed = False
2238 if len(cell.splitlines()) == 1:
2249 if len(cell.splitlines()) == 1:
2239 try:
2250 try:
2240 # use prefilter_lines to handle trailing newlines
2251 # use prefilter_lines to handle trailing newlines
2241 # restore trailing newline for ast.parse
2252 # restore trailing newline for ast.parse
2242 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2253 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2243 except AliasError as e:
2254 except AliasError as e:
2244 error(e)
2255 error(e)
2245 prefilter_failed=True
2256 prefilter_failed=True
2246 except Exception:
2257 except Exception:
2247 # don't allow prefilter errors to crash IPython
2258 # don't allow prefilter errors to crash IPython
2248 self.showtraceback()
2259 self.showtraceback()
2249 prefilter_failed = True
2260 prefilter_failed = True
2250
2261
2251 # Store raw and processed history
2262 # Store raw and processed history
2252 if store_history:
2263 if store_history:
2253 self.history_manager.store_inputs(self.execution_count,
2264 self.history_manager.store_inputs(self.execution_count,
2254 cell, raw_cell)
2265 cell, raw_cell)
2255
2266
2256 self.logger.log(cell, raw_cell)
2267 self.logger.log(cell, raw_cell)
2257
2268
2258 if not prefilter_failed:
2269 if not prefilter_failed:
2259 # don't run if prefilter failed
2270 # don't run if prefilter failed
2260 cell_name = self.compile.cache(cell, self.execution_count)
2271 cell_name = self.compile.cache(cell, self.execution_count)
2261
2272
2262 with self.display_trap:
2273 with self.display_trap:
2263 try:
2274 try:
2264 code_ast = ast.parse(cell, filename=cell_name)
2275 code_ast = ast.parse(cell, filename=cell_name)
2265 except (OverflowError, SyntaxError, ValueError, TypeError,
2276 except (OverflowError, SyntaxError, ValueError, TypeError,
2266 MemoryError):
2277 MemoryError):
2267 self.showsyntaxerror()
2278 self.showsyntaxerror()
2268 self.execution_count += 1
2279 self.execution_count += 1
2269 return None
2280 return None
2270
2281
2271 self.run_ast_nodes(code_ast.body, cell_name,
2282 self.run_ast_nodes(code_ast.body, cell_name,
2272 interactivity="last_expr")
2283 interactivity="last_expr")
2273
2284
2274 # Execute any registered post-execution functions.
2285 # Execute any registered post-execution functions.
2275 for func, status in self._post_execute.iteritems():
2286 for func, status in self._post_execute.iteritems():
2276 if not status:
2287 if not status:
2277 continue
2288 continue
2278 try:
2289 try:
2279 func()
2290 func()
2280 except:
2291 except:
2281 self.showtraceback()
2292 self.showtraceback()
2282 # Deactivate failing function
2293 # Deactivate failing function
2283 self._post_execute[func] = False
2294 self._post_execute[func] = False
2284
2295
2285 if store_history:
2296 if store_history:
2286 # Write output to the database. Does nothing unless
2297 # Write output to the database. Does nothing unless
2287 # history output logging is enabled.
2298 # history output logging is enabled.
2288 self.history_manager.store_output(self.execution_count)
2299 self.history_manager.store_output(self.execution_count)
2289 # Each cell is a *single* input, regardless of how many lines it has
2300 # Each cell is a *single* input, regardless of how many lines it has
2290 self.execution_count += 1
2301 self.execution_count += 1
2291
2302
2292 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'):
2303 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'):
2293 """Run a sequence of AST nodes. The execution mode depends on the
2304 """Run a sequence of AST nodes. The execution mode depends on the
2294 interactivity parameter.
2305 interactivity parameter.
2295
2306
2296 Parameters
2307 Parameters
2297 ----------
2308 ----------
2298 nodelist : list
2309 nodelist : list
2299 A sequence of AST nodes to run.
2310 A sequence of AST nodes to run.
2300 cell_name : str
2311 cell_name : str
2301 Will be passed to the compiler as the filename of the cell. Typically
2312 Will be passed to the compiler as the filename of the cell. Typically
2302 the value returned by ip.compile.cache(cell).
2313 the value returned by ip.compile.cache(cell).
2303 interactivity : str
2314 interactivity : str
2304 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2315 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2305 run interactively (displaying output from expressions). 'last_expr'
2316 run interactively (displaying output from expressions). 'last_expr'
2306 will run the last node interactively only if it is an expression (i.e.
2317 will run the last node interactively only if it is an expression (i.e.
2307 expressions in loops or other blocks are not displayed. Other values
2318 expressions in loops or other blocks are not displayed. Other values
2308 for this parameter will raise a ValueError.
2319 for this parameter will raise a ValueError.
2309 """
2320 """
2310 if not nodelist:
2321 if not nodelist:
2311 return
2322 return
2312
2323
2313 if interactivity == 'last_expr':
2324 if interactivity == 'last_expr':
2314 if isinstance(nodelist[-1], ast.Expr):
2325 if isinstance(nodelist[-1], ast.Expr):
2315 interactivity = "last"
2326 interactivity = "last"
2316 else:
2327 else:
2317 interactivity = "none"
2328 interactivity = "none"
2318
2329
2319 if interactivity == 'none':
2330 if interactivity == 'none':
2320 to_run_exec, to_run_interactive = nodelist, []
2331 to_run_exec, to_run_interactive = nodelist, []
2321 elif interactivity == 'last':
2332 elif interactivity == 'last':
2322 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2333 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2323 elif interactivity == 'all':
2334 elif interactivity == 'all':
2324 to_run_exec, to_run_interactive = [], nodelist
2335 to_run_exec, to_run_interactive = [], nodelist
2325 else:
2336 else:
2326 raise ValueError("Interactivity was %r" % interactivity)
2337 raise ValueError("Interactivity was %r" % interactivity)
2327
2338
2328 exec_count = self.execution_count
2339 exec_count = self.execution_count
2329
2340
2330 for i, node in enumerate(to_run_exec):
2341 for i, node in enumerate(to_run_exec):
2331 mod = ast.Module([node])
2342 mod = ast.Module([node])
2332 code = self.compile(mod, cell_name, "exec")
2343 code = self.compile(mod, cell_name, "exec")
2333 if self.run_code(code):
2344 if self.run_code(code):
2334 return True
2345 return True
2335
2346
2336 for i, node in enumerate(to_run_interactive):
2347 for i, node in enumerate(to_run_interactive):
2337 mod = ast.Interactive([node])
2348 mod = ast.Interactive([node])
2338 code = self.compile(mod, cell_name, "single")
2349 code = self.compile(mod, cell_name, "single")
2339 if self.run_code(code):
2350 if self.run_code(code):
2340 return True
2351 return True
2341
2352
2342 return False
2353 return False
2343
2354
2344 def run_code(self, code_obj):
2355 def run_code(self, code_obj):
2345 """Execute a code object.
2356 """Execute a code object.
2346
2357
2347 When an exception occurs, self.showtraceback() is called to display a
2358 When an exception occurs, self.showtraceback() is called to display a
2348 traceback.
2359 traceback.
2349
2360
2350 Parameters
2361 Parameters
2351 ----------
2362 ----------
2352 code_obj : code object
2363 code_obj : code object
2353 A compiled code object, to be executed
2364 A compiled code object, to be executed
2354 post_execute : bool [default: True]
2365 post_execute : bool [default: True]
2355 whether to call post_execute hooks after this particular execution.
2366 whether to call post_execute hooks after this particular execution.
2356
2367
2357 Returns
2368 Returns
2358 -------
2369 -------
2359 False : successful execution.
2370 False : successful execution.
2360 True : an error occurred.
2371 True : an error occurred.
2361 """
2372 """
2362
2373
2363 # Set our own excepthook in case the user code tries to call it
2374 # Set our own excepthook in case the user code tries to call it
2364 # directly, so that the IPython crash handler doesn't get triggered
2375 # directly, so that the IPython crash handler doesn't get triggered
2365 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2376 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2366
2377
2367 # we save the original sys.excepthook in the instance, in case config
2378 # we save the original sys.excepthook in the instance, in case config
2368 # code (such as magics) needs access to it.
2379 # code (such as magics) needs access to it.
2369 self.sys_excepthook = old_excepthook
2380 self.sys_excepthook = old_excepthook
2370 outflag = 1 # happens in more places, so it's easier as default
2381 outflag = 1 # happens in more places, so it's easier as default
2371 try:
2382 try:
2372 try:
2383 try:
2373 self.hooks.pre_run_code_hook()
2384 self.hooks.pre_run_code_hook()
2374 #rprint('Running code', repr(code_obj)) # dbg
2385 #rprint('Running code', repr(code_obj)) # dbg
2375 exec code_obj in self.user_global_ns, self.user_ns
2386 exec code_obj in self.user_global_ns, self.user_ns
2376 finally:
2387 finally:
2377 # Reset our crash handler in place
2388 # Reset our crash handler in place
2378 sys.excepthook = old_excepthook
2389 sys.excepthook = old_excepthook
2379 except SystemExit:
2390 except SystemExit:
2380 self.showtraceback(exception_only=True)
2391 self.showtraceback(exception_only=True)
2381 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2392 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2382 except self.custom_exceptions:
2393 except self.custom_exceptions:
2383 etype,value,tb = sys.exc_info()
2394 etype,value,tb = sys.exc_info()
2384 self.CustomTB(etype,value,tb)
2395 self.CustomTB(etype,value,tb)
2385 except:
2396 except:
2386 self.showtraceback()
2397 self.showtraceback()
2387 else:
2398 else:
2388 outflag = 0
2399 outflag = 0
2389 if softspace(sys.stdout, 0):
2400 if softspace(sys.stdout, 0):
2390 print
2401 print
2391
2402
2392 return outflag
2403 return outflag
2393
2404
2394 # For backwards compatibility
2405 # For backwards compatibility
2395 runcode = run_code
2406 runcode = run_code
2396
2407
2397 #-------------------------------------------------------------------------
2408 #-------------------------------------------------------------------------
2398 # Things related to GUI support and pylab
2409 # Things related to GUI support and pylab
2399 #-------------------------------------------------------------------------
2410 #-------------------------------------------------------------------------
2400
2411
2401 def enable_pylab(self, gui=None):
2412 def enable_pylab(self, gui=None):
2402 raise NotImplementedError('Implement enable_pylab in a subclass')
2413 raise NotImplementedError('Implement enable_pylab in a subclass')
2403
2414
2404 #-------------------------------------------------------------------------
2415 #-------------------------------------------------------------------------
2405 # Utilities
2416 # Utilities
2406 #-------------------------------------------------------------------------
2417 #-------------------------------------------------------------------------
2407
2418
2408 def var_expand(self,cmd,depth=0):
2419 def var_expand(self,cmd,depth=0):
2409 """Expand python variables in a string.
2420 """Expand python variables in a string.
2410
2421
2411 The depth argument indicates how many frames above the caller should
2422 The depth argument indicates how many frames above the caller should
2412 be walked to look for the local namespace where to expand variables.
2423 be walked to look for the local namespace where to expand variables.
2413
2424
2414 The global namespace for expansion is always the user's interactive
2425 The global namespace for expansion is always the user's interactive
2415 namespace.
2426 namespace.
2416 """
2427 """
2417 res = ItplNS(cmd, self.user_ns, # globals
2428 res = ItplNS(cmd, self.user_ns, # globals
2418 # Skip our own frame in searching for locals:
2429 # Skip our own frame in searching for locals:
2419 sys._getframe(depth+1).f_locals # locals
2430 sys._getframe(depth+1).f_locals # locals
2420 )
2431 )
2421 return str(res).decode(res.codec)
2432 return str(res).decode(res.codec)
2422
2433
2423 def mktempfile(self, data=None, prefix='ipython_edit_'):
2434 def mktempfile(self, data=None, prefix='ipython_edit_'):
2424 """Make a new tempfile and return its filename.
2435 """Make a new tempfile and return its filename.
2425
2436
2426 This makes a call to tempfile.mktemp, but it registers the created
2437 This makes a call to tempfile.mktemp, but it registers the created
2427 filename internally so ipython cleans it up at exit time.
2438 filename internally so ipython cleans it up at exit time.
2428
2439
2429 Optional inputs:
2440 Optional inputs:
2430
2441
2431 - data(None): if data is given, it gets written out to the temp file
2442 - data(None): if data is given, it gets written out to the temp file
2432 immediately, and the file is closed again."""
2443 immediately, and the file is closed again."""
2433
2444
2434 filename = tempfile.mktemp('.py', prefix)
2445 filename = tempfile.mktemp('.py', prefix)
2435 self.tempfiles.append(filename)
2446 self.tempfiles.append(filename)
2436
2447
2437 if data:
2448 if data:
2438 tmp_file = open(filename,'w')
2449 tmp_file = open(filename,'w')
2439 tmp_file.write(data)
2450 tmp_file.write(data)
2440 tmp_file.close()
2451 tmp_file.close()
2441 return filename
2452 return filename
2442
2453
2443 # TODO: This should be removed when Term is refactored.
2454 # TODO: This should be removed when Term is refactored.
2444 def write(self,data):
2455 def write(self,data):
2445 """Write a string to the default output"""
2456 """Write a string to the default output"""
2446 io.stdout.write(data)
2457 io.stdout.write(data)
2447
2458
2448 # TODO: This should be removed when Term is refactored.
2459 # TODO: This should be removed when Term is refactored.
2449 def write_err(self,data):
2460 def write_err(self,data):
2450 """Write a string to the default error output"""
2461 """Write a string to the default error output"""
2451 io.stderr.write(data)
2462 io.stderr.write(data)
2452
2463
2453 def ask_yes_no(self,prompt,default=True):
2464 def ask_yes_no(self,prompt,default=True):
2454 if self.quiet:
2465 if self.quiet:
2455 return True
2466 return True
2456 return ask_yes_no(prompt,default)
2467 return ask_yes_no(prompt,default)
2457
2468
2458 def show_usage(self):
2469 def show_usage(self):
2459 """Show a usage message"""
2470 """Show a usage message"""
2460 page.page(IPython.core.usage.interactive_usage)
2471 page.page(IPython.core.usage.interactive_usage)
2461
2472
2462 def find_user_code(self, target, raw=True):
2473 def find_user_code(self, target, raw=True):
2463 """Get a code string from history, file, or a string or macro.
2474 """Get a code string from history, file, or a string or macro.
2464
2475
2465 This is mainly used by magic functions.
2476 This is mainly used by magic functions.
2466
2477
2467 Parameters
2478 Parameters
2468 ----------
2479 ----------
2469 target : str
2480 target : str
2470 A string specifying code to retrieve. This will be tried respectively
2481 A string specifying code to retrieve. This will be tried respectively
2471 as: ranges of input history (see %history for syntax), a filename, or
2482 as: ranges of input history (see %history for syntax), a filename, or
2472 an expression evaluating to a string or Macro in the user namespace.
2483 an expression evaluating to a string or Macro in the user namespace.
2473 raw : bool
2484 raw : bool
2474 If true (default), retrieve raw history. Has no effect on the other
2485 If true (default), retrieve raw history. Has no effect on the other
2475 retrieval mechanisms.
2486 retrieval mechanisms.
2476
2487
2477 Returns
2488 Returns
2478 -------
2489 -------
2479 A string of code.
2490 A string of code.
2480
2491
2481 ValueError is raised if nothing is found, and TypeError if it evaluates
2492 ValueError is raised if nothing is found, and TypeError if it evaluates
2482 to an object of another type. In each case, .args[0] is a printable
2493 to an object of another type. In each case, .args[0] is a printable
2483 message.
2494 message.
2484 """
2495 """
2485 code = self.extract_input_lines(target, raw=raw) # Grab history
2496 code = self.extract_input_lines(target, raw=raw) # Grab history
2486 if code:
2497 if code:
2487 return code
2498 return code
2488 if os.path.isfile(target): # Read file
2499 if os.path.isfile(target): # Read file
2489 return open(target, "r").read()
2500 return open(target, "r").read()
2490
2501
2491 try: # User namespace
2502 try: # User namespace
2492 codeobj = eval(target, self.user_ns)
2503 codeobj = eval(target, self.user_ns)
2493 except Exception:
2504 except Exception:
2494 raise ValueError(("'%s' was not found in history, as a file, nor in"
2505 raise ValueError(("'%s' was not found in history, as a file, nor in"
2495 " the user namespace.") % target)
2506 " the user namespace.") % target)
2496 if isinstance(codeobj, basestring):
2507 if isinstance(codeobj, basestring):
2497 return codeobj
2508 return codeobj
2498 elif isinstance(codeobj, Macro):
2509 elif isinstance(codeobj, Macro):
2499 return codeobj.value
2510 return codeobj.value
2500
2511
2501 raise TypeError("%s is neither a string nor a macro." % target,
2512 raise TypeError("%s is neither a string nor a macro." % target,
2502 codeobj)
2513 codeobj)
2503
2514
2504 #-------------------------------------------------------------------------
2515 #-------------------------------------------------------------------------
2505 # Things related to IPython exiting
2516 # Things related to IPython exiting
2506 #-------------------------------------------------------------------------
2517 #-------------------------------------------------------------------------
2507 def atexit_operations(self):
2518 def atexit_operations(self):
2508 """This will be executed at the time of exit.
2519 """This will be executed at the time of exit.
2509
2520
2510 Cleanup operations and saving of persistent data that is done
2521 Cleanup operations and saving of persistent data that is done
2511 unconditionally by IPython should be performed here.
2522 unconditionally by IPython should be performed here.
2512
2523
2513 For things that may depend on startup flags or platform specifics (such
2524 For things that may depend on startup flags or platform specifics (such
2514 as having readline or not), register a separate atexit function in the
2525 as having readline or not), register a separate atexit function in the
2515 code that has the appropriate information, rather than trying to
2526 code that has the appropriate information, rather than trying to
2516 clutter
2527 clutter
2517 """
2528 """
2518 # Cleanup all tempfiles left around
2529 # Cleanup all tempfiles left around
2519 for tfile in self.tempfiles:
2530 for tfile in self.tempfiles:
2520 try:
2531 try:
2521 os.unlink(tfile)
2532 os.unlink(tfile)
2522 except OSError:
2533 except OSError:
2523 pass
2534 pass
2524
2535
2525 # Close the history session (this stores the end time and line count)
2536 # Close the history session (this stores the end time and line count)
2526 self.history_manager.end_session()
2537 self.history_manager.end_session()
2527
2538
2528 # Clear all user namespaces to release all references cleanly.
2539 # Clear all user namespaces to release all references cleanly.
2529 self.reset(new_session=False)
2540 self.reset(new_session=False)
2530
2541
2531 # Run user hooks
2542 # Run user hooks
2532 self.hooks.shutdown_hook()
2543 self.hooks.shutdown_hook()
2533
2544
2534 def cleanup(self):
2545 def cleanup(self):
2535 self.restore_sys_module_state()
2546 self.restore_sys_module_state()
2536
2547
2537
2548
2538 class InteractiveShellABC(object):
2549 class InteractiveShellABC(object):
2539 """An abstract base class for InteractiveShell."""
2550 """An abstract base class for InteractiveShell."""
2540 __metaclass__ = abc.ABCMeta
2551 __metaclass__ = abc.ABCMeta
2541
2552
2542 InteractiveShellABC.register(InteractiveShell)
2553 InteractiveShellABC.register(InteractiveShell)
@@ -1,3518 +1,3504
1 # encoding: utf-8
1 # encoding: utf-8
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3 """
3 """
4
4
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
7 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2008-2009 The IPython Development Team
8 # Copyright (C) 2008-2009 The IPython Development Team
9
9
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 import __builtin__
18 import __builtin__
19 import __future__
19 import __future__
20 import bdb
20 import bdb
21 import inspect
21 import inspect
22 import os
22 import os
23 import sys
23 import sys
24 import shutil
24 import shutil
25 import re
25 import re
26 import time
26 import time
27 import textwrap
27 import textwrap
28 from cStringIO import StringIO
28 from cStringIO import StringIO
29 from getopt import getopt,GetoptError
29 from getopt import getopt,GetoptError
30 from pprint import pformat
30 from pprint import pformat
31 from xmlrpclib import ServerProxy
31 from xmlrpclib import ServerProxy
32
32
33 # cProfile was added in Python2.5
33 # cProfile was added in Python2.5
34 try:
34 try:
35 import cProfile as profile
35 import cProfile as profile
36 import pstats
36 import pstats
37 except ImportError:
37 except ImportError:
38 # profile isn't bundled by default in Debian for license reasons
38 # profile isn't bundled by default in Debian for license reasons
39 try:
39 try:
40 import profile,pstats
40 import profile,pstats
41 except ImportError:
41 except ImportError:
42 profile = pstats = None
42 profile = pstats = None
43
43
44 import IPython
44 import IPython
45 from IPython.core import debugger, oinspect
45 from IPython.core import debugger, oinspect
46 from IPython.core.error import TryNext
46 from IPython.core.error import TryNext
47 from IPython.core.error import UsageError
47 from IPython.core.error import UsageError
48 from IPython.core.fakemodule import FakeModule
48 from IPython.core.fakemodule import FakeModule
49 from IPython.core.newapplication import ProfileDir
49 from IPython.core.macro import Macro
50 from IPython.core.macro import Macro
50 from IPython.core import page
51 from IPython.core import page
51 from IPython.core.prefilter import ESC_MAGIC
52 from IPython.core.prefilter import ESC_MAGIC
52 from IPython.lib.pylabtools import mpl_runner
53 from IPython.lib.pylabtools import mpl_runner
53 from IPython.external.Itpl import itpl, printpl
54 from IPython.external.Itpl import itpl, printpl
54 from IPython.testing.skipdoctest import skip_doctest
55 from IPython.testing.skipdoctest import skip_doctest
55 from IPython.utils.io import file_read, nlprint
56 from IPython.utils.io import file_read, nlprint
56 from IPython.utils.path import get_py_filename
57 from IPython.utils.path import get_py_filename
57 from IPython.utils.process import arg_split, abbrev_cwd
58 from IPython.utils.process import arg_split, abbrev_cwd
58 from IPython.utils.terminal import set_term_title
59 from IPython.utils.terminal import set_term_title
59 from IPython.utils.text import LSString, SList, format_screen
60 from IPython.utils.text import LSString, SList, format_screen
60 from IPython.utils.timing import clock, clock2
61 from IPython.utils.timing import clock, clock2
61 from IPython.utils.warn import warn, error
62 from IPython.utils.warn import warn, error
62 from IPython.utils.ipstruct import Struct
63 from IPython.utils.ipstruct import Struct
63 import IPython.utils.generics
64 import IPython.utils.generics
64
65
65 #-----------------------------------------------------------------------------
66 #-----------------------------------------------------------------------------
66 # Utility functions
67 # Utility functions
67 #-----------------------------------------------------------------------------
68 #-----------------------------------------------------------------------------
68
69
69 def on_off(tag):
70 def on_off(tag):
70 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
71 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
71 return ['OFF','ON'][tag]
72 return ['OFF','ON'][tag]
72
73
73 class Bunch: pass
74 class Bunch: pass
74
75
75 def compress_dhist(dh):
76 def compress_dhist(dh):
76 head, tail = dh[:-10], dh[-10:]
77 head, tail = dh[:-10], dh[-10:]
77
78
78 newhead = []
79 newhead = []
79 done = set()
80 done = set()
80 for h in head:
81 for h in head:
81 if h in done:
82 if h in done:
82 continue
83 continue
83 newhead.append(h)
84 newhead.append(h)
84 done.add(h)
85 done.add(h)
85
86
86 return newhead + tail
87 return newhead + tail
87
88
88 def needs_local_scope(func):
89 def needs_local_scope(func):
89 """Decorator to mark magic functions which need to local scope to run."""
90 """Decorator to mark magic functions which need to local scope to run."""
90 func.needs_local_scope = True
91 func.needs_local_scope = True
91 return func
92 return func
92
93
93 # Used for exception handling in magic_edit
94 # Used for exception handling in magic_edit
94 class MacroToEdit(ValueError): pass
95 class MacroToEdit(ValueError): pass
95
96
96 #***************************************************************************
97 #***************************************************************************
97 # Main class implementing Magic functionality
98 # Main class implementing Magic functionality
98
99
99 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
100 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
100 # on construction of the main InteractiveShell object. Something odd is going
101 # on construction of the main InteractiveShell object. Something odd is going
101 # on with super() calls, Configurable and the MRO... For now leave it as-is, but
102 # on with super() calls, Configurable and the MRO... For now leave it as-is, but
102 # eventually this needs to be clarified.
103 # eventually this needs to be clarified.
103 # BG: This is because InteractiveShell inherits from this, but is itself a
104 # BG: This is because InteractiveShell inherits from this, but is itself a
104 # Configurable. This messes up the MRO in some way. The fix is that we need to
105 # Configurable. This messes up the MRO in some way. The fix is that we need to
105 # make Magic a configurable that InteractiveShell does not subclass.
106 # make Magic a configurable that InteractiveShell does not subclass.
106
107
107 class Magic:
108 class Magic:
108 """Magic functions for InteractiveShell.
109 """Magic functions for InteractiveShell.
109
110
110 Shell functions which can be reached as %function_name. All magic
111 Shell functions which can be reached as %function_name. All magic
111 functions should accept a string, which they can parse for their own
112 functions should accept a string, which they can parse for their own
112 needs. This can make some functions easier to type, eg `%cd ../`
113 needs. This can make some functions easier to type, eg `%cd ../`
113 vs. `%cd("../")`
114 vs. `%cd("../")`
114
115
115 ALL definitions MUST begin with the prefix magic_. The user won't need it
116 ALL definitions MUST begin with the prefix magic_. The user won't need it
116 at the command line, but it is is needed in the definition. """
117 at the command line, but it is is needed in the definition. """
117
118
118 # class globals
119 # class globals
119 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
120 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
120 'Automagic is ON, % prefix NOT needed for magic functions.']
121 'Automagic is ON, % prefix NOT needed for magic functions.']
121
122
122 #......................................................................
123 #......................................................................
123 # some utility functions
124 # some utility functions
124
125
125 def __init__(self,shell):
126 def __init__(self,shell):
126
127
127 self.options_table = {}
128 self.options_table = {}
128 if profile is None:
129 if profile is None:
129 self.magic_prun = self.profile_missing_notice
130 self.magic_prun = self.profile_missing_notice
130 self.shell = shell
131 self.shell = shell
131
132
132 # namespace for holding state we may need
133 # namespace for holding state we may need
133 self._magic_state = Bunch()
134 self._magic_state = Bunch()
134
135
135 def profile_missing_notice(self, *args, **kwargs):
136 def profile_missing_notice(self, *args, **kwargs):
136 error("""\
137 error("""\
137 The profile module could not be found. It has been removed from the standard
138 The profile module could not be found. It has been removed from the standard
138 python packages because of its non-free license. To use profiling, install the
139 python packages because of its non-free license. To use profiling, install the
139 python-profiler package from non-free.""")
140 python-profiler package from non-free.""")
140
141
141 def default_option(self,fn,optstr):
142 def default_option(self,fn,optstr):
142 """Make an entry in the options_table for fn, with value optstr"""
143 """Make an entry in the options_table for fn, with value optstr"""
143
144
144 if fn not in self.lsmagic():
145 if fn not in self.lsmagic():
145 error("%s is not a magic function" % fn)
146 error("%s is not a magic function" % fn)
146 self.options_table[fn] = optstr
147 self.options_table[fn] = optstr
147
148
148 def lsmagic(self):
149 def lsmagic(self):
149 """Return a list of currently available magic functions.
150 """Return a list of currently available magic functions.
150
151
151 Gives a list of the bare names after mangling (['ls','cd', ...], not
152 Gives a list of the bare names after mangling (['ls','cd', ...], not
152 ['magic_ls','magic_cd',...]"""
153 ['magic_ls','magic_cd',...]"""
153
154
154 # FIXME. This needs a cleanup, in the way the magics list is built.
155 # FIXME. This needs a cleanup, in the way the magics list is built.
155
156
156 # magics in class definition
157 # magics in class definition
157 class_magic = lambda fn: fn.startswith('magic_') and \
158 class_magic = lambda fn: fn.startswith('magic_') and \
158 callable(Magic.__dict__[fn])
159 callable(Magic.__dict__[fn])
159 # in instance namespace (run-time user additions)
160 # in instance namespace (run-time user additions)
160 inst_magic = lambda fn: fn.startswith('magic_') and \
161 inst_magic = lambda fn: fn.startswith('magic_') and \
161 callable(self.__dict__[fn])
162 callable(self.__dict__[fn])
162 # and bound magics by user (so they can access self):
163 # and bound magics by user (so they can access self):
163 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
164 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
164 callable(self.__class__.__dict__[fn])
165 callable(self.__class__.__dict__[fn])
165 magics = filter(class_magic,Magic.__dict__.keys()) + \
166 magics = filter(class_magic,Magic.__dict__.keys()) + \
166 filter(inst_magic,self.__dict__.keys()) + \
167 filter(inst_magic,self.__dict__.keys()) + \
167 filter(inst_bound_magic,self.__class__.__dict__.keys())
168 filter(inst_bound_magic,self.__class__.__dict__.keys())
168 out = []
169 out = []
169 for fn in set(magics):
170 for fn in set(magics):
170 out.append(fn.replace('magic_','',1))
171 out.append(fn.replace('magic_','',1))
171 out.sort()
172 out.sort()
172 return out
173 return out
173
174
174 def extract_input_lines(self, range_str, raw=False):
175 def extract_input_lines(self, range_str, raw=False):
175 """Return as a string a set of input history slices.
176 """Return as a string a set of input history slices.
176
177
177 Inputs:
178 Inputs:
178
179
179 - range_str: the set of slices is given as a string, like
180 - range_str: the set of slices is given as a string, like
180 "~5/6-~4/2 4:8 9", since this function is for use by magic functions
181 "~5/6-~4/2 4:8 9", since this function is for use by magic functions
181 which get their arguments as strings. The number before the / is the
182 which get their arguments as strings. The number before the / is the
182 session number: ~n goes n back from the current session.
183 session number: ~n goes n back from the current session.
183
184
184 Optional inputs:
185 Optional inputs:
185
186
186 - raw(False): by default, the processed input is used. If this is
187 - raw(False): by default, the processed input is used. If this is
187 true, the raw input history is used instead.
188 true, the raw input history is used instead.
188
189
189 Note that slices can be called with two notations:
190 Note that slices can be called with two notations:
190
191
191 N:M -> standard python form, means including items N...(M-1).
192 N:M -> standard python form, means including items N...(M-1).
192
193
193 N-M -> include items N..M (closed endpoint)."""
194 N-M -> include items N..M (closed endpoint)."""
194 lines = self.shell.history_manager.\
195 lines = self.shell.history_manager.\
195 get_range_by_str(range_str, raw=raw)
196 get_range_by_str(range_str, raw=raw)
196 return "\n".join(x for _, _, x in lines)
197 return "\n".join(x for _, _, x in lines)
197
198
198 def arg_err(self,func):
199 def arg_err(self,func):
199 """Print docstring if incorrect arguments were passed"""
200 """Print docstring if incorrect arguments were passed"""
200 print 'Error in arguments:'
201 print 'Error in arguments:'
201 print oinspect.getdoc(func)
202 print oinspect.getdoc(func)
202
203
203 def format_latex(self,strng):
204 def format_latex(self,strng):
204 """Format a string for latex inclusion."""
205 """Format a string for latex inclusion."""
205
206
206 # Characters that need to be escaped for latex:
207 # Characters that need to be escaped for latex:
207 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
208 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
208 # Magic command names as headers:
209 # Magic command names as headers:
209 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
210 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
210 re.MULTILINE)
211 re.MULTILINE)
211 # Magic commands
212 # Magic commands
212 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
213 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
213 re.MULTILINE)
214 re.MULTILINE)
214 # Paragraph continue
215 # Paragraph continue
215 par_re = re.compile(r'\\$',re.MULTILINE)
216 par_re = re.compile(r'\\$',re.MULTILINE)
216
217
217 # The "\n" symbol
218 # The "\n" symbol
218 newline_re = re.compile(r'\\n')
219 newline_re = re.compile(r'\\n')
219
220
220 # Now build the string for output:
221 # Now build the string for output:
221 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
222 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
222 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
223 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
223 strng)
224 strng)
224 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
225 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
225 strng = par_re.sub(r'\\\\',strng)
226 strng = par_re.sub(r'\\\\',strng)
226 strng = escape_re.sub(r'\\\1',strng)
227 strng = escape_re.sub(r'\\\1',strng)
227 strng = newline_re.sub(r'\\textbackslash{}n',strng)
228 strng = newline_re.sub(r'\\textbackslash{}n',strng)
228 return strng
229 return strng
229
230
230 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
231 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
231 """Parse options passed to an argument string.
232 """Parse options passed to an argument string.
232
233
233 The interface is similar to that of getopt(), but it returns back a
234 The interface is similar to that of getopt(), but it returns back a
234 Struct with the options as keys and the stripped argument string still
235 Struct with the options as keys and the stripped argument string still
235 as a string.
236 as a string.
236
237
237 arg_str is quoted as a true sys.argv vector by using shlex.split.
238 arg_str is quoted as a true sys.argv vector by using shlex.split.
238 This allows us to easily expand variables, glob files, quote
239 This allows us to easily expand variables, glob files, quote
239 arguments, etc.
240 arguments, etc.
240
241
241 Options:
242 Options:
242 -mode: default 'string'. If given as 'list', the argument string is
243 -mode: default 'string'. If given as 'list', the argument string is
243 returned as a list (split on whitespace) instead of a string.
244 returned as a list (split on whitespace) instead of a string.
244
245
245 -list_all: put all option values in lists. Normally only options
246 -list_all: put all option values in lists. Normally only options
246 appearing more than once are put in a list.
247 appearing more than once are put in a list.
247
248
248 -posix (True): whether to split the input line in POSIX mode or not,
249 -posix (True): whether to split the input line in POSIX mode or not,
249 as per the conventions outlined in the shlex module from the
250 as per the conventions outlined in the shlex module from the
250 standard library."""
251 standard library."""
251
252
252 # inject default options at the beginning of the input line
253 # inject default options at the beginning of the input line
253 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
254 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
254 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
255 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
255
256
256 mode = kw.get('mode','string')
257 mode = kw.get('mode','string')
257 if mode not in ['string','list']:
258 if mode not in ['string','list']:
258 raise ValueError,'incorrect mode given: %s' % mode
259 raise ValueError,'incorrect mode given: %s' % mode
259 # Get options
260 # Get options
260 list_all = kw.get('list_all',0)
261 list_all = kw.get('list_all',0)
261 posix = kw.get('posix', os.name == 'posix')
262 posix = kw.get('posix', os.name == 'posix')
262
263
263 # Check if we have more than one argument to warrant extra processing:
264 # Check if we have more than one argument to warrant extra processing:
264 odict = {} # Dictionary with options
265 odict = {} # Dictionary with options
265 args = arg_str.split()
266 args = arg_str.split()
266 if len(args) >= 1:
267 if len(args) >= 1:
267 # If the list of inputs only has 0 or 1 thing in it, there's no
268 # If the list of inputs only has 0 or 1 thing in it, there's no
268 # need to look for options
269 # need to look for options
269 argv = arg_split(arg_str,posix)
270 argv = arg_split(arg_str,posix)
270 # Do regular option processing
271 # Do regular option processing
271 try:
272 try:
272 opts,args = getopt(argv,opt_str,*long_opts)
273 opts,args = getopt(argv,opt_str,*long_opts)
273 except GetoptError,e:
274 except GetoptError,e:
274 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
275 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
275 " ".join(long_opts)))
276 " ".join(long_opts)))
276 for o,a in opts:
277 for o,a in opts:
277 if o.startswith('--'):
278 if o.startswith('--'):
278 o = o[2:]
279 o = o[2:]
279 else:
280 else:
280 o = o[1:]
281 o = o[1:]
281 try:
282 try:
282 odict[o].append(a)
283 odict[o].append(a)
283 except AttributeError:
284 except AttributeError:
284 odict[o] = [odict[o],a]
285 odict[o] = [odict[o],a]
285 except KeyError:
286 except KeyError:
286 if list_all:
287 if list_all:
287 odict[o] = [a]
288 odict[o] = [a]
288 else:
289 else:
289 odict[o] = a
290 odict[o] = a
290
291
291 # Prepare opts,args for return
292 # Prepare opts,args for return
292 opts = Struct(odict)
293 opts = Struct(odict)
293 if mode == 'string':
294 if mode == 'string':
294 args = ' '.join(args)
295 args = ' '.join(args)
295
296
296 return opts,args
297 return opts,args
297
298
298 #......................................................................
299 #......................................................................
299 # And now the actual magic functions
300 # And now the actual magic functions
300
301
301 # Functions for IPython shell work (vars,funcs, config, etc)
302 # Functions for IPython shell work (vars,funcs, config, etc)
302 def magic_lsmagic(self, parameter_s = ''):
303 def magic_lsmagic(self, parameter_s = ''):
303 """List currently available magic functions."""
304 """List currently available magic functions."""
304 mesc = ESC_MAGIC
305 mesc = ESC_MAGIC
305 print 'Available magic functions:\n'+mesc+\
306 print 'Available magic functions:\n'+mesc+\
306 (' '+mesc).join(self.lsmagic())
307 (' '+mesc).join(self.lsmagic())
307 print '\n' + Magic.auto_status[self.shell.automagic]
308 print '\n' + Magic.auto_status[self.shell.automagic]
308 return None
309 return None
309
310
310 def magic_magic(self, parameter_s = ''):
311 def magic_magic(self, parameter_s = ''):
311 """Print information about the magic function system.
312 """Print information about the magic function system.
312
313
313 Supported formats: -latex, -brief, -rest
314 Supported formats: -latex, -brief, -rest
314 """
315 """
315
316
316 mode = ''
317 mode = ''
317 try:
318 try:
318 if parameter_s.split()[0] == '-latex':
319 if parameter_s.split()[0] == '-latex':
319 mode = 'latex'
320 mode = 'latex'
320 if parameter_s.split()[0] == '-brief':
321 if parameter_s.split()[0] == '-brief':
321 mode = 'brief'
322 mode = 'brief'
322 if parameter_s.split()[0] == '-rest':
323 if parameter_s.split()[0] == '-rest':
323 mode = 'rest'
324 mode = 'rest'
324 rest_docs = []
325 rest_docs = []
325 except:
326 except:
326 pass
327 pass
327
328
328 magic_docs = []
329 magic_docs = []
329 for fname in self.lsmagic():
330 for fname in self.lsmagic():
330 mname = 'magic_' + fname
331 mname = 'magic_' + fname
331 for space in (Magic,self,self.__class__):
332 for space in (Magic,self,self.__class__):
332 try:
333 try:
333 fn = space.__dict__[mname]
334 fn = space.__dict__[mname]
334 except KeyError:
335 except KeyError:
335 pass
336 pass
336 else:
337 else:
337 break
338 break
338 if mode == 'brief':
339 if mode == 'brief':
339 # only first line
340 # only first line
340 if fn.__doc__:
341 if fn.__doc__:
341 fndoc = fn.__doc__.split('\n',1)[0]
342 fndoc = fn.__doc__.split('\n',1)[0]
342 else:
343 else:
343 fndoc = 'No documentation'
344 fndoc = 'No documentation'
344 else:
345 else:
345 if fn.__doc__:
346 if fn.__doc__:
346 fndoc = fn.__doc__.rstrip()
347 fndoc = fn.__doc__.rstrip()
347 else:
348 else:
348 fndoc = 'No documentation'
349 fndoc = 'No documentation'
349
350
350
351
351 if mode == 'rest':
352 if mode == 'rest':
352 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
353 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
353 fname,fndoc))
354 fname,fndoc))
354
355
355 else:
356 else:
356 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
357 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
357 fname,fndoc))
358 fname,fndoc))
358
359
359 magic_docs = ''.join(magic_docs)
360 magic_docs = ''.join(magic_docs)
360
361
361 if mode == 'rest':
362 if mode == 'rest':
362 return "".join(rest_docs)
363 return "".join(rest_docs)
363
364
364 if mode == 'latex':
365 if mode == 'latex':
365 print self.format_latex(magic_docs)
366 print self.format_latex(magic_docs)
366 return
367 return
367 else:
368 else:
368 magic_docs = format_screen(magic_docs)
369 magic_docs = format_screen(magic_docs)
369 if mode == 'brief':
370 if mode == 'brief':
370 return magic_docs
371 return magic_docs
371
372
372 outmsg = """
373 outmsg = """
373 IPython's 'magic' functions
374 IPython's 'magic' functions
374 ===========================
375 ===========================
375
376
376 The magic function system provides a series of functions which allow you to
377 The magic function system provides a series of functions which allow you to
377 control the behavior of IPython itself, plus a lot of system-type
378 control the behavior of IPython itself, plus a lot of system-type
378 features. All these functions are prefixed with a % character, but parameters
379 features. All these functions are prefixed with a % character, but parameters
379 are given without parentheses or quotes.
380 are given without parentheses or quotes.
380
381
381 NOTE: If you have 'automagic' enabled (via the command line option or with the
382 NOTE: If you have 'automagic' enabled (via the command line option or with the
382 %automagic function), you don't need to type in the % explicitly. By default,
383 %automagic function), you don't need to type in the % explicitly. By default,
383 IPython ships with automagic on, so you should only rarely need the % escape.
384 IPython ships with automagic on, so you should only rarely need the % escape.
384
385
385 Example: typing '%cd mydir' (without the quotes) changes you working directory
386 Example: typing '%cd mydir' (without the quotes) changes you working directory
386 to 'mydir', if it exists.
387 to 'mydir', if it exists.
387
388
388 You can define your own magic functions to extend the system. See the supplied
389 You can define your own magic functions to extend the system. See the supplied
389 ipythonrc and example-magic.py files for details (in your ipython
390 ipythonrc and example-magic.py files for details (in your ipython
390 configuration directory, typically $HOME/.config/ipython on Linux or $HOME/.ipython elsewhere).
391 configuration directory, typically $HOME/.config/ipython on Linux or $HOME/.ipython elsewhere).
391
392
392 You can also define your own aliased names for magic functions. In your
393 You can also define your own aliased names for magic functions. In your
393 ipythonrc file, placing a line like:
394 ipythonrc file, placing a line like:
394
395
395 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
396 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
396
397
397 will define %pf as a new name for %profile.
398 will define %pf as a new name for %profile.
398
399
399 You can also call magics in code using the magic() function, which IPython
400 You can also call magics in code using the magic() function, which IPython
400 automatically adds to the builtin namespace. Type 'magic?' for details.
401 automatically adds to the builtin namespace. Type 'magic?' for details.
401
402
402 For a list of the available magic functions, use %lsmagic. For a description
403 For a list of the available magic functions, use %lsmagic. For a description
403 of any of them, type %magic_name?, e.g. '%cd?'.
404 of any of them, type %magic_name?, e.g. '%cd?'.
404
405
405 Currently the magic system has the following functions:\n"""
406 Currently the magic system has the following functions:\n"""
406
407
407 mesc = ESC_MAGIC
408 mesc = ESC_MAGIC
408 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
409 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
409 "\n\n%s%s\n\n%s" % (outmsg,
410 "\n\n%s%s\n\n%s" % (outmsg,
410 magic_docs,mesc,mesc,
411 magic_docs,mesc,mesc,
411 (' '+mesc).join(self.lsmagic()),
412 (' '+mesc).join(self.lsmagic()),
412 Magic.auto_status[self.shell.automagic] ) )
413 Magic.auto_status[self.shell.automagic] ) )
413 page.page(outmsg)
414 page.page(outmsg)
414
415
415 def magic_automagic(self, parameter_s = ''):
416 def magic_automagic(self, parameter_s = ''):
416 """Make magic functions callable without having to type the initial %.
417 """Make magic functions callable without having to type the initial %.
417
418
418 Without argumentsl toggles on/off (when off, you must call it as
419 Without argumentsl toggles on/off (when off, you must call it as
419 %automagic, of course). With arguments it sets the value, and you can
420 %automagic, of course). With arguments it sets the value, and you can
420 use any of (case insensitive):
421 use any of (case insensitive):
421
422
422 - on,1,True: to activate
423 - on,1,True: to activate
423
424
424 - off,0,False: to deactivate.
425 - off,0,False: to deactivate.
425
426
426 Note that magic functions have lowest priority, so if there's a
427 Note that magic functions have lowest priority, so if there's a
427 variable whose name collides with that of a magic fn, automagic won't
428 variable whose name collides with that of a magic fn, automagic won't
428 work for that function (you get the variable instead). However, if you
429 work for that function (you get the variable instead). However, if you
429 delete the variable (del var), the previously shadowed magic function
430 delete the variable (del var), the previously shadowed magic function
430 becomes visible to automagic again."""
431 becomes visible to automagic again."""
431
432
432 arg = parameter_s.lower()
433 arg = parameter_s.lower()
433 if parameter_s in ('on','1','true'):
434 if parameter_s in ('on','1','true'):
434 self.shell.automagic = True
435 self.shell.automagic = True
435 elif parameter_s in ('off','0','false'):
436 elif parameter_s in ('off','0','false'):
436 self.shell.automagic = False
437 self.shell.automagic = False
437 else:
438 else:
438 self.shell.automagic = not self.shell.automagic
439 self.shell.automagic = not self.shell.automagic
439 print '\n' + Magic.auto_status[self.shell.automagic]
440 print '\n' + Magic.auto_status[self.shell.automagic]
440
441
441 @skip_doctest
442 @skip_doctest
442 def magic_autocall(self, parameter_s = ''):
443 def magic_autocall(self, parameter_s = ''):
443 """Make functions callable without having to type parentheses.
444 """Make functions callable without having to type parentheses.
444
445
445 Usage:
446 Usage:
446
447
447 %autocall [mode]
448 %autocall [mode]
448
449
449 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
450 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
450 value is toggled on and off (remembering the previous state).
451 value is toggled on and off (remembering the previous state).
451
452
452 In more detail, these values mean:
453 In more detail, these values mean:
453
454
454 0 -> fully disabled
455 0 -> fully disabled
455
456
456 1 -> active, but do not apply if there are no arguments on the line.
457 1 -> active, but do not apply if there are no arguments on the line.
457
458
458 In this mode, you get:
459 In this mode, you get:
459
460
460 In [1]: callable
461 In [1]: callable
461 Out[1]: <built-in function callable>
462 Out[1]: <built-in function callable>
462
463
463 In [2]: callable 'hello'
464 In [2]: callable 'hello'
464 ------> callable('hello')
465 ------> callable('hello')
465 Out[2]: False
466 Out[2]: False
466
467
467 2 -> Active always. Even if no arguments are present, the callable
468 2 -> Active always. Even if no arguments are present, the callable
468 object is called:
469 object is called:
469
470
470 In [2]: float
471 In [2]: float
471 ------> float()
472 ------> float()
472 Out[2]: 0.0
473 Out[2]: 0.0
473
474
474 Note that even with autocall off, you can still use '/' at the start of
475 Note that even with autocall off, you can still use '/' at the start of
475 a line to treat the first argument on the command line as a function
476 a line to treat the first argument on the command line as a function
476 and add parentheses to it:
477 and add parentheses to it:
477
478
478 In [8]: /str 43
479 In [8]: /str 43
479 ------> str(43)
480 ------> str(43)
480 Out[8]: '43'
481 Out[8]: '43'
481
482
482 # all-random (note for auto-testing)
483 # all-random (note for auto-testing)
483 """
484 """
484
485
485 if parameter_s:
486 if parameter_s:
486 arg = int(parameter_s)
487 arg = int(parameter_s)
487 else:
488 else:
488 arg = 'toggle'
489 arg = 'toggle'
489
490
490 if not arg in (0,1,2,'toggle'):
491 if not arg in (0,1,2,'toggle'):
491 error('Valid modes: (0->Off, 1->Smart, 2->Full')
492 error('Valid modes: (0->Off, 1->Smart, 2->Full')
492 return
493 return
493
494
494 if arg in (0,1,2):
495 if arg in (0,1,2):
495 self.shell.autocall = arg
496 self.shell.autocall = arg
496 else: # toggle
497 else: # toggle
497 if self.shell.autocall:
498 if self.shell.autocall:
498 self._magic_state.autocall_save = self.shell.autocall
499 self._magic_state.autocall_save = self.shell.autocall
499 self.shell.autocall = 0
500 self.shell.autocall = 0
500 else:
501 else:
501 try:
502 try:
502 self.shell.autocall = self._magic_state.autocall_save
503 self.shell.autocall = self._magic_state.autocall_save
503 except AttributeError:
504 except AttributeError:
504 self.shell.autocall = self._magic_state.autocall_save = 1
505 self.shell.autocall = self._magic_state.autocall_save = 1
505
506
506 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
507 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
507
508
508
509
509 def magic_page(self, parameter_s=''):
510 def magic_page(self, parameter_s=''):
510 """Pretty print the object and display it through a pager.
511 """Pretty print the object and display it through a pager.
511
512
512 %page [options] OBJECT
513 %page [options] OBJECT
513
514
514 If no object is given, use _ (last output).
515 If no object is given, use _ (last output).
515
516
516 Options:
517 Options:
517
518
518 -r: page str(object), don't pretty-print it."""
519 -r: page str(object), don't pretty-print it."""
519
520
520 # After a function contributed by Olivier Aubert, slightly modified.
521 # After a function contributed by Olivier Aubert, slightly modified.
521
522
522 # Process options/args
523 # Process options/args
523 opts,args = self.parse_options(parameter_s,'r')
524 opts,args = self.parse_options(parameter_s,'r')
524 raw = 'r' in opts
525 raw = 'r' in opts
525
526
526 oname = args and args or '_'
527 oname = args and args or '_'
527 info = self._ofind(oname)
528 info = self._ofind(oname)
528 if info['found']:
529 if info['found']:
529 txt = (raw and str or pformat)( info['obj'] )
530 txt = (raw and str or pformat)( info['obj'] )
530 page.page(txt)
531 page.page(txt)
531 else:
532 else:
532 print 'Object `%s` not found' % oname
533 print 'Object `%s` not found' % oname
533
534
534 def magic_profile(self, parameter_s=''):
535 def magic_profile(self, parameter_s=''):
535 """Print your currently active IPython profile."""
536 """Print your currently active IPython profile."""
536 if self.shell.profile:
537 print self.shell.profile
537 printpl('Current IPython profile: $self.shell.profile.')
538 else:
539 print 'No profile active.'
540
538
541 def magic_pinfo(self, parameter_s='', namespaces=None):
539 def magic_pinfo(self, parameter_s='', namespaces=None):
542 """Provide detailed information about an object.
540 """Provide detailed information about an object.
543
541
544 '%pinfo object' is just a synonym for object? or ?object."""
542 '%pinfo object' is just a synonym for object? or ?object."""
545
543
546 #print 'pinfo par: <%s>' % parameter_s # dbg
544 #print 'pinfo par: <%s>' % parameter_s # dbg
547
545
548
546
549 # detail_level: 0 -> obj? , 1 -> obj??
547 # detail_level: 0 -> obj? , 1 -> obj??
550 detail_level = 0
548 detail_level = 0
551 # We need to detect if we got called as 'pinfo pinfo foo', which can
549 # We need to detect if we got called as 'pinfo pinfo foo', which can
552 # happen if the user types 'pinfo foo?' at the cmd line.
550 # happen if the user types 'pinfo foo?' at the cmd line.
553 pinfo,qmark1,oname,qmark2 = \
551 pinfo,qmark1,oname,qmark2 = \
554 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
552 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
555 if pinfo or qmark1 or qmark2:
553 if pinfo or qmark1 or qmark2:
556 detail_level = 1
554 detail_level = 1
557 if "*" in oname:
555 if "*" in oname:
558 self.magic_psearch(oname)
556 self.magic_psearch(oname)
559 else:
557 else:
560 self.shell._inspect('pinfo', oname, detail_level=detail_level,
558 self.shell._inspect('pinfo', oname, detail_level=detail_level,
561 namespaces=namespaces)
559 namespaces=namespaces)
562
560
563 def magic_pinfo2(self, parameter_s='', namespaces=None):
561 def magic_pinfo2(self, parameter_s='', namespaces=None):
564 """Provide extra detailed information about an object.
562 """Provide extra detailed information about an object.
565
563
566 '%pinfo2 object' is just a synonym for object?? or ??object."""
564 '%pinfo2 object' is just a synonym for object?? or ??object."""
567 self.shell._inspect('pinfo', parameter_s, detail_level=1,
565 self.shell._inspect('pinfo', parameter_s, detail_level=1,
568 namespaces=namespaces)
566 namespaces=namespaces)
569
567
570 @skip_doctest
568 @skip_doctest
571 def magic_pdef(self, parameter_s='', namespaces=None):
569 def magic_pdef(self, parameter_s='', namespaces=None):
572 """Print the definition header for any callable object.
570 """Print the definition header for any callable object.
573
571
574 If the object is a class, print the constructor information.
572 If the object is a class, print the constructor information.
575
573
576 Examples
574 Examples
577 --------
575 --------
578 ::
576 ::
579
577
580 In [3]: %pdef urllib.urlopen
578 In [3]: %pdef urllib.urlopen
581 urllib.urlopen(url, data=None, proxies=None)
579 urllib.urlopen(url, data=None, proxies=None)
582 """
580 """
583 self._inspect('pdef',parameter_s, namespaces)
581 self._inspect('pdef',parameter_s, namespaces)
584
582
585 def magic_pdoc(self, parameter_s='', namespaces=None):
583 def magic_pdoc(self, parameter_s='', namespaces=None):
586 """Print the docstring for an object.
584 """Print the docstring for an object.
587
585
588 If the given object is a class, it will print both the class and the
586 If the given object is a class, it will print both the class and the
589 constructor docstrings."""
587 constructor docstrings."""
590 self._inspect('pdoc',parameter_s, namespaces)
588 self._inspect('pdoc',parameter_s, namespaces)
591
589
592 def magic_psource(self, parameter_s='', namespaces=None):
590 def magic_psource(self, parameter_s='', namespaces=None):
593 """Print (or run through pager) the source code for an object."""
591 """Print (or run through pager) the source code for an object."""
594 self._inspect('psource',parameter_s, namespaces)
592 self._inspect('psource',parameter_s, namespaces)
595
593
596 def magic_pfile(self, parameter_s=''):
594 def magic_pfile(self, parameter_s=''):
597 """Print (or run through pager) the file where an object is defined.
595 """Print (or run through pager) the file where an object is defined.
598
596
599 The file opens at the line where the object definition begins. IPython
597 The file opens at the line where the object definition begins. IPython
600 will honor the environment variable PAGER if set, and otherwise will
598 will honor the environment variable PAGER if set, and otherwise will
601 do its best to print the file in a convenient form.
599 do its best to print the file in a convenient form.
602
600
603 If the given argument is not an object currently defined, IPython will
601 If the given argument is not an object currently defined, IPython will
604 try to interpret it as a filename (automatically adding a .py extension
602 try to interpret it as a filename (automatically adding a .py extension
605 if needed). You can thus use %pfile as a syntax highlighting code
603 if needed). You can thus use %pfile as a syntax highlighting code
606 viewer."""
604 viewer."""
607
605
608 # first interpret argument as an object name
606 # first interpret argument as an object name
609 out = self._inspect('pfile',parameter_s)
607 out = self._inspect('pfile',parameter_s)
610 # if not, try the input as a filename
608 # if not, try the input as a filename
611 if out == 'not found':
609 if out == 'not found':
612 try:
610 try:
613 filename = get_py_filename(parameter_s)
611 filename = get_py_filename(parameter_s)
614 except IOError,msg:
612 except IOError,msg:
615 print msg
613 print msg
616 return
614 return
617 page.page(self.shell.inspector.format(file(filename).read()))
615 page.page(self.shell.inspector.format(file(filename).read()))
618
616
619 def magic_psearch(self, parameter_s=''):
617 def magic_psearch(self, parameter_s=''):
620 """Search for object in namespaces by wildcard.
618 """Search for object in namespaces by wildcard.
621
619
622 %psearch [options] PATTERN [OBJECT TYPE]
620 %psearch [options] PATTERN [OBJECT TYPE]
623
621
624 Note: ? can be used as a synonym for %psearch, at the beginning or at
622 Note: ? can be used as a synonym for %psearch, at the beginning or at
625 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
623 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
626 rest of the command line must be unchanged (options come first), so
624 rest of the command line must be unchanged (options come first), so
627 for example the following forms are equivalent
625 for example the following forms are equivalent
628
626
629 %psearch -i a* function
627 %psearch -i a* function
630 -i a* function?
628 -i a* function?
631 ?-i a* function
629 ?-i a* function
632
630
633 Arguments:
631 Arguments:
634
632
635 PATTERN
633 PATTERN
636
634
637 where PATTERN is a string containing * as a wildcard similar to its
635 where PATTERN is a string containing * as a wildcard similar to its
638 use in a shell. The pattern is matched in all namespaces on the
636 use in a shell. The pattern is matched in all namespaces on the
639 search path. By default objects starting with a single _ are not
637 search path. By default objects starting with a single _ are not
640 matched, many IPython generated objects have a single
638 matched, many IPython generated objects have a single
641 underscore. The default is case insensitive matching. Matching is
639 underscore. The default is case insensitive matching. Matching is
642 also done on the attributes of objects and not only on the objects
640 also done on the attributes of objects and not only on the objects
643 in a module.
641 in a module.
644
642
645 [OBJECT TYPE]
643 [OBJECT TYPE]
646
644
647 Is the name of a python type from the types module. The name is
645 Is the name of a python type from the types module. The name is
648 given in lowercase without the ending type, ex. StringType is
646 given in lowercase without the ending type, ex. StringType is
649 written string. By adding a type here only objects matching the
647 written string. By adding a type here only objects matching the
650 given type are matched. Using all here makes the pattern match all
648 given type are matched. Using all here makes the pattern match all
651 types (this is the default).
649 types (this is the default).
652
650
653 Options:
651 Options:
654
652
655 -a: makes the pattern match even objects whose names start with a
653 -a: makes the pattern match even objects whose names start with a
656 single underscore. These names are normally ommitted from the
654 single underscore. These names are normally ommitted from the
657 search.
655 search.
658
656
659 -i/-c: make the pattern case insensitive/sensitive. If neither of
657 -i/-c: make the pattern case insensitive/sensitive. If neither of
660 these options is given, the default is read from your ipythonrc
658 these options is given, the default is read from your ipythonrc
661 file. The option name which sets this value is
659 file. The option name which sets this value is
662 'wildcards_case_sensitive'. If this option is not specified in your
660 'wildcards_case_sensitive'. If this option is not specified in your
663 ipythonrc file, IPython's internal default is to do a case sensitive
661 ipythonrc file, IPython's internal default is to do a case sensitive
664 search.
662 search.
665
663
666 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
664 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
667 specifiy can be searched in any of the following namespaces:
665 specifiy can be searched in any of the following namespaces:
668 'builtin', 'user', 'user_global','internal', 'alias', where
666 'builtin', 'user', 'user_global','internal', 'alias', where
669 'builtin' and 'user' are the search defaults. Note that you should
667 'builtin' and 'user' are the search defaults. Note that you should
670 not use quotes when specifying namespaces.
668 not use quotes when specifying namespaces.
671
669
672 'Builtin' contains the python module builtin, 'user' contains all
670 'Builtin' contains the python module builtin, 'user' contains all
673 user data, 'alias' only contain the shell aliases and no python
671 user data, 'alias' only contain the shell aliases and no python
674 objects, 'internal' contains objects used by IPython. The
672 objects, 'internal' contains objects used by IPython. The
675 'user_global' namespace is only used by embedded IPython instances,
673 'user_global' namespace is only used by embedded IPython instances,
676 and it contains module-level globals. You can add namespaces to the
674 and it contains module-level globals. You can add namespaces to the
677 search with -s or exclude them with -e (these options can be given
675 search with -s or exclude them with -e (these options can be given
678 more than once).
676 more than once).
679
677
680 Examples:
678 Examples:
681
679
682 %psearch a* -> objects beginning with an a
680 %psearch a* -> objects beginning with an a
683 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
681 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
684 %psearch a* function -> all functions beginning with an a
682 %psearch a* function -> all functions beginning with an a
685 %psearch re.e* -> objects beginning with an e in module re
683 %psearch re.e* -> objects beginning with an e in module re
686 %psearch r*.e* -> objects that start with e in modules starting in r
684 %psearch r*.e* -> objects that start with e in modules starting in r
687 %psearch r*.* string -> all strings in modules beginning with r
685 %psearch r*.* string -> all strings in modules beginning with r
688
686
689 Case sensitve search:
687 Case sensitve search:
690
688
691 %psearch -c a* list all object beginning with lower case a
689 %psearch -c a* list all object beginning with lower case a
692
690
693 Show objects beginning with a single _:
691 Show objects beginning with a single _:
694
692
695 %psearch -a _* list objects beginning with a single underscore"""
693 %psearch -a _* list objects beginning with a single underscore"""
696 try:
694 try:
697 parameter_s = parameter_s.encode('ascii')
695 parameter_s = parameter_s.encode('ascii')
698 except UnicodeEncodeError:
696 except UnicodeEncodeError:
699 print 'Python identifiers can only contain ascii characters.'
697 print 'Python identifiers can only contain ascii characters.'
700 return
698 return
701
699
702 # default namespaces to be searched
700 # default namespaces to be searched
703 def_search = ['user','builtin']
701 def_search = ['user','builtin']
704
702
705 # Process options/args
703 # Process options/args
706 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
704 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
707 opt = opts.get
705 opt = opts.get
708 shell = self.shell
706 shell = self.shell
709 psearch = shell.inspector.psearch
707 psearch = shell.inspector.psearch
710
708
711 # select case options
709 # select case options
712 if opts.has_key('i'):
710 if opts.has_key('i'):
713 ignore_case = True
711 ignore_case = True
714 elif opts.has_key('c'):
712 elif opts.has_key('c'):
715 ignore_case = False
713 ignore_case = False
716 else:
714 else:
717 ignore_case = not shell.wildcards_case_sensitive
715 ignore_case = not shell.wildcards_case_sensitive
718
716
719 # Build list of namespaces to search from user options
717 # Build list of namespaces to search from user options
720 def_search.extend(opt('s',[]))
718 def_search.extend(opt('s',[]))
721 ns_exclude = ns_exclude=opt('e',[])
719 ns_exclude = ns_exclude=opt('e',[])
722 ns_search = [nm for nm in def_search if nm not in ns_exclude]
720 ns_search = [nm for nm in def_search if nm not in ns_exclude]
723
721
724 # Call the actual search
722 # Call the actual search
725 try:
723 try:
726 psearch(args,shell.ns_table,ns_search,
724 psearch(args,shell.ns_table,ns_search,
727 show_all=opt('a'),ignore_case=ignore_case)
725 show_all=opt('a'),ignore_case=ignore_case)
728 except:
726 except:
729 shell.showtraceback()
727 shell.showtraceback()
730
728
731 @skip_doctest
729 @skip_doctest
732 def magic_who_ls(self, parameter_s=''):
730 def magic_who_ls(self, parameter_s=''):
733 """Return a sorted list of all interactive variables.
731 """Return a sorted list of all interactive variables.
734
732
735 If arguments are given, only variables of types matching these
733 If arguments are given, only variables of types matching these
736 arguments are returned.
734 arguments are returned.
737
735
738 Examples
736 Examples
739 --------
737 --------
740
738
741 Define two variables and list them with who_ls::
739 Define two variables and list them with who_ls::
742
740
743 In [1]: alpha = 123
741 In [1]: alpha = 123
744
742
745 In [2]: beta = 'test'
743 In [2]: beta = 'test'
746
744
747 In [3]: %who_ls
745 In [3]: %who_ls
748 Out[3]: ['alpha', 'beta']
746 Out[3]: ['alpha', 'beta']
749
747
750 In [4]: %who_ls int
748 In [4]: %who_ls int
751 Out[4]: ['alpha']
749 Out[4]: ['alpha']
752
750
753 In [5]: %who_ls str
751 In [5]: %who_ls str
754 Out[5]: ['beta']
752 Out[5]: ['beta']
755 """
753 """
756
754
757 user_ns = self.shell.user_ns
755 user_ns = self.shell.user_ns
758 internal_ns = self.shell.internal_ns
756 internal_ns = self.shell.internal_ns
759 user_ns_hidden = self.shell.user_ns_hidden
757 user_ns_hidden = self.shell.user_ns_hidden
760 out = [ i for i in user_ns
758 out = [ i for i in user_ns
761 if not i.startswith('_') \
759 if not i.startswith('_') \
762 and not (i in internal_ns or i in user_ns_hidden) ]
760 and not (i in internal_ns or i in user_ns_hidden) ]
763
761
764 typelist = parameter_s.split()
762 typelist = parameter_s.split()
765 if typelist:
763 if typelist:
766 typeset = set(typelist)
764 typeset = set(typelist)
767 out = [i for i in out if type(user_ns[i]).__name__ in typeset]
765 out = [i for i in out if type(user_ns[i]).__name__ in typeset]
768
766
769 out.sort()
767 out.sort()
770 return out
768 return out
771
769
772 @skip_doctest
770 @skip_doctest
773 def magic_who(self, parameter_s=''):
771 def magic_who(self, parameter_s=''):
774 """Print all interactive variables, with some minimal formatting.
772 """Print all interactive variables, with some minimal formatting.
775
773
776 If any arguments are given, only variables whose type matches one of
774 If any arguments are given, only variables whose type matches one of
777 these are printed. For example:
775 these are printed. For example:
778
776
779 %who function str
777 %who function str
780
778
781 will only list functions and strings, excluding all other types of
779 will only list functions and strings, excluding all other types of
782 variables. To find the proper type names, simply use type(var) at a
780 variables. To find the proper type names, simply use type(var) at a
783 command line to see how python prints type names. For example:
781 command line to see how python prints type names. For example:
784
782
785 In [1]: type('hello')\\
783 In [1]: type('hello')\\
786 Out[1]: <type 'str'>
784 Out[1]: <type 'str'>
787
785
788 indicates that the type name for strings is 'str'.
786 indicates that the type name for strings is 'str'.
789
787
790 %who always excludes executed names loaded through your configuration
788 %who always excludes executed names loaded through your configuration
791 file and things which are internal to IPython.
789 file and things which are internal to IPython.
792
790
793 This is deliberate, as typically you may load many modules and the
791 This is deliberate, as typically you may load many modules and the
794 purpose of %who is to show you only what you've manually defined.
792 purpose of %who is to show you only what you've manually defined.
795
793
796 Examples
794 Examples
797 --------
795 --------
798
796
799 Define two variables and list them with who::
797 Define two variables and list them with who::
800
798
801 In [1]: alpha = 123
799 In [1]: alpha = 123
802
800
803 In [2]: beta = 'test'
801 In [2]: beta = 'test'
804
802
805 In [3]: %who
803 In [3]: %who
806 alpha beta
804 alpha beta
807
805
808 In [4]: %who int
806 In [4]: %who int
809 alpha
807 alpha
810
808
811 In [5]: %who str
809 In [5]: %who str
812 beta
810 beta
813 """
811 """
814
812
815 varlist = self.magic_who_ls(parameter_s)
813 varlist = self.magic_who_ls(parameter_s)
816 if not varlist:
814 if not varlist:
817 if parameter_s:
815 if parameter_s:
818 print 'No variables match your requested type.'
816 print 'No variables match your requested type.'
819 else:
817 else:
820 print 'Interactive namespace is empty.'
818 print 'Interactive namespace is empty.'
821 return
819 return
822
820
823 # if we have variables, move on...
821 # if we have variables, move on...
824 count = 0
822 count = 0
825 for i in varlist:
823 for i in varlist:
826 print i+'\t',
824 print i+'\t',
827 count += 1
825 count += 1
828 if count > 8:
826 if count > 8:
829 count = 0
827 count = 0
830 print
828 print
831 print
829 print
832
830
833 @skip_doctest
831 @skip_doctest
834 def magic_whos(self, parameter_s=''):
832 def magic_whos(self, parameter_s=''):
835 """Like %who, but gives some extra information about each variable.
833 """Like %who, but gives some extra information about each variable.
836
834
837 The same type filtering of %who can be applied here.
835 The same type filtering of %who can be applied here.
838
836
839 For all variables, the type is printed. Additionally it prints:
837 For all variables, the type is printed. Additionally it prints:
840
838
841 - For {},[],(): their length.
839 - For {},[],(): their length.
842
840
843 - For numpy arrays, a summary with shape, number of
841 - For numpy arrays, a summary with shape, number of
844 elements, typecode and size in memory.
842 elements, typecode and size in memory.
845
843
846 - Everything else: a string representation, snipping their middle if
844 - Everything else: a string representation, snipping their middle if
847 too long.
845 too long.
848
846
849 Examples
847 Examples
850 --------
848 --------
851
849
852 Define two variables and list them with whos::
850 Define two variables and list them with whos::
853
851
854 In [1]: alpha = 123
852 In [1]: alpha = 123
855
853
856 In [2]: beta = 'test'
854 In [2]: beta = 'test'
857
855
858 In [3]: %whos
856 In [3]: %whos
859 Variable Type Data/Info
857 Variable Type Data/Info
860 --------------------------------
858 --------------------------------
861 alpha int 123
859 alpha int 123
862 beta str test
860 beta str test
863 """
861 """
864
862
865 varnames = self.magic_who_ls(parameter_s)
863 varnames = self.magic_who_ls(parameter_s)
866 if not varnames:
864 if not varnames:
867 if parameter_s:
865 if parameter_s:
868 print 'No variables match your requested type.'
866 print 'No variables match your requested type.'
869 else:
867 else:
870 print 'Interactive namespace is empty.'
868 print 'Interactive namespace is empty.'
871 return
869 return
872
870
873 # if we have variables, move on...
871 # if we have variables, move on...
874
872
875 # for these types, show len() instead of data:
873 # for these types, show len() instead of data:
876 seq_types = ['dict', 'list', 'tuple']
874 seq_types = ['dict', 'list', 'tuple']
877
875
878 # for numpy/Numeric arrays, display summary info
876 # for numpy/Numeric arrays, display summary info
879 try:
877 try:
880 import numpy
878 import numpy
881 except ImportError:
879 except ImportError:
882 ndarray_type = None
880 ndarray_type = None
883 else:
881 else:
884 ndarray_type = numpy.ndarray.__name__
882 ndarray_type = numpy.ndarray.__name__
885 try:
883 try:
886 import Numeric
884 import Numeric
887 except ImportError:
885 except ImportError:
888 array_type = None
886 array_type = None
889 else:
887 else:
890 array_type = Numeric.ArrayType.__name__
888 array_type = Numeric.ArrayType.__name__
891
889
892 # Find all variable names and types so we can figure out column sizes
890 # Find all variable names and types so we can figure out column sizes
893 def get_vars(i):
891 def get_vars(i):
894 return self.shell.user_ns[i]
892 return self.shell.user_ns[i]
895
893
896 # some types are well known and can be shorter
894 # some types are well known and can be shorter
897 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
895 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
898 def type_name(v):
896 def type_name(v):
899 tn = type(v).__name__
897 tn = type(v).__name__
900 return abbrevs.get(tn,tn)
898 return abbrevs.get(tn,tn)
901
899
902 varlist = map(get_vars,varnames)
900 varlist = map(get_vars,varnames)
903
901
904 typelist = []
902 typelist = []
905 for vv in varlist:
903 for vv in varlist:
906 tt = type_name(vv)
904 tt = type_name(vv)
907
905
908 if tt=='instance':
906 if tt=='instance':
909 typelist.append( abbrevs.get(str(vv.__class__),
907 typelist.append( abbrevs.get(str(vv.__class__),
910 str(vv.__class__)))
908 str(vv.__class__)))
911 else:
909 else:
912 typelist.append(tt)
910 typelist.append(tt)
913
911
914 # column labels and # of spaces as separator
912 # column labels and # of spaces as separator
915 varlabel = 'Variable'
913 varlabel = 'Variable'
916 typelabel = 'Type'
914 typelabel = 'Type'
917 datalabel = 'Data/Info'
915 datalabel = 'Data/Info'
918 colsep = 3
916 colsep = 3
919 # variable format strings
917 # variable format strings
920 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
918 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
921 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
919 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
922 aformat = "%s: %s elems, type `%s`, %s bytes"
920 aformat = "%s: %s elems, type `%s`, %s bytes"
923 # find the size of the columns to format the output nicely
921 # find the size of the columns to format the output nicely
924 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
922 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
925 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
923 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
926 # table header
924 # table header
927 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
925 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
928 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
926 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
929 # and the table itself
927 # and the table itself
930 kb = 1024
928 kb = 1024
931 Mb = 1048576 # kb**2
929 Mb = 1048576 # kb**2
932 for vname,var,vtype in zip(varnames,varlist,typelist):
930 for vname,var,vtype in zip(varnames,varlist,typelist):
933 print itpl(vformat),
931 print itpl(vformat),
934 if vtype in seq_types:
932 if vtype in seq_types:
935 print "n="+str(len(var))
933 print "n="+str(len(var))
936 elif vtype in [array_type,ndarray_type]:
934 elif vtype in [array_type,ndarray_type]:
937 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
935 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
938 if vtype==ndarray_type:
936 if vtype==ndarray_type:
939 # numpy
937 # numpy
940 vsize = var.size
938 vsize = var.size
941 vbytes = vsize*var.itemsize
939 vbytes = vsize*var.itemsize
942 vdtype = var.dtype
940 vdtype = var.dtype
943 else:
941 else:
944 # Numeric
942 # Numeric
945 vsize = Numeric.size(var)
943 vsize = Numeric.size(var)
946 vbytes = vsize*var.itemsize()
944 vbytes = vsize*var.itemsize()
947 vdtype = var.typecode()
945 vdtype = var.typecode()
948
946
949 if vbytes < 100000:
947 if vbytes < 100000:
950 print aformat % (vshape,vsize,vdtype,vbytes)
948 print aformat % (vshape,vsize,vdtype,vbytes)
951 else:
949 else:
952 print aformat % (vshape,vsize,vdtype,vbytes),
950 print aformat % (vshape,vsize,vdtype,vbytes),
953 if vbytes < Mb:
951 if vbytes < Mb:
954 print '(%s kb)' % (vbytes/kb,)
952 print '(%s kb)' % (vbytes/kb,)
955 else:
953 else:
956 print '(%s Mb)' % (vbytes/Mb,)
954 print '(%s Mb)' % (vbytes/Mb,)
957 else:
955 else:
958 try:
956 try:
959 vstr = str(var)
957 vstr = str(var)
960 except UnicodeEncodeError:
958 except UnicodeEncodeError:
961 vstr = unicode(var).encode(sys.getdefaultencoding(),
959 vstr = unicode(var).encode(sys.getdefaultencoding(),
962 'backslashreplace')
960 'backslashreplace')
963 vstr = vstr.replace('\n','\\n')
961 vstr = vstr.replace('\n','\\n')
964 if len(vstr) < 50:
962 if len(vstr) < 50:
965 print vstr
963 print vstr
966 else:
964 else:
967 printpl(vfmt_short)
965 printpl(vfmt_short)
968
966
969 def magic_reset(self, parameter_s=''):
967 def magic_reset(self, parameter_s=''):
970 """Resets the namespace by removing all names defined by the user.
968 """Resets the namespace by removing all names defined by the user.
971
969
972 Parameters
970 Parameters
973 ----------
971 ----------
974 -f : force reset without asking for confirmation.
972 -f : force reset without asking for confirmation.
975
973
976 -s : 'Soft' reset: Only clears your namespace, leaving history intact.
974 -s : 'Soft' reset: Only clears your namespace, leaving history intact.
977 References to objects may be kept. By default (without this option),
975 References to objects may be kept. By default (without this option),
978 we do a 'hard' reset, giving you a new session and removing all
976 we do a 'hard' reset, giving you a new session and removing all
979 references to objects from the current session.
977 references to objects from the current session.
980
978
981 Examples
979 Examples
982 --------
980 --------
983 In [6]: a = 1
981 In [6]: a = 1
984
982
985 In [7]: a
983 In [7]: a
986 Out[7]: 1
984 Out[7]: 1
987
985
988 In [8]: 'a' in _ip.user_ns
986 In [8]: 'a' in _ip.user_ns
989 Out[8]: True
987 Out[8]: True
990
988
991 In [9]: %reset -f
989 In [9]: %reset -f
992
990
993 In [1]: 'a' in _ip.user_ns
991 In [1]: 'a' in _ip.user_ns
994 Out[1]: False
992 Out[1]: False
995 """
993 """
996 opts, args = self.parse_options(parameter_s,'sf')
994 opts, args = self.parse_options(parameter_s,'sf')
997 if 'f' in opts:
995 if 'f' in opts:
998 ans = True
996 ans = True
999 else:
997 else:
1000 ans = self.shell.ask_yes_no(
998 ans = self.shell.ask_yes_no(
1001 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
999 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1002 if not ans:
1000 if not ans:
1003 print 'Nothing done.'
1001 print 'Nothing done.'
1004 return
1002 return
1005
1003
1006 if 's' in opts: # Soft reset
1004 if 's' in opts: # Soft reset
1007 user_ns = self.shell.user_ns
1005 user_ns = self.shell.user_ns
1008 for i in self.magic_who_ls():
1006 for i in self.magic_who_ls():
1009 del(user_ns[i])
1007 del(user_ns[i])
1010
1008
1011 else: # Hard reset
1009 else: # Hard reset
1012 self.shell.reset(new_session = False)
1010 self.shell.reset(new_session = False)
1013
1011
1014
1012
1015
1013
1016 def magic_reset_selective(self, parameter_s=''):
1014 def magic_reset_selective(self, parameter_s=''):
1017 """Resets the namespace by removing names defined by the user.
1015 """Resets the namespace by removing names defined by the user.
1018
1016
1019 Input/Output history are left around in case you need them.
1017 Input/Output history are left around in case you need them.
1020
1018
1021 %reset_selective [-f] regex
1019 %reset_selective [-f] regex
1022
1020
1023 No action is taken if regex is not included
1021 No action is taken if regex is not included
1024
1022
1025 Options
1023 Options
1026 -f : force reset without asking for confirmation.
1024 -f : force reset without asking for confirmation.
1027
1025
1028 Examples
1026 Examples
1029 --------
1027 --------
1030
1028
1031 We first fully reset the namespace so your output looks identical to
1029 We first fully reset the namespace so your output looks identical to
1032 this example for pedagogical reasons; in practice you do not need a
1030 this example for pedagogical reasons; in practice you do not need a
1033 full reset.
1031 full reset.
1034
1032
1035 In [1]: %reset -f
1033 In [1]: %reset -f
1036
1034
1037 Now, with a clean namespace we can make a few variables and use
1035 Now, with a clean namespace we can make a few variables and use
1038 %reset_selective to only delete names that match our regexp:
1036 %reset_selective to only delete names that match our regexp:
1039
1037
1040 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1038 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1041
1039
1042 In [3]: who_ls
1040 In [3]: who_ls
1043 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1041 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1044
1042
1045 In [4]: %reset_selective -f b[2-3]m
1043 In [4]: %reset_selective -f b[2-3]m
1046
1044
1047 In [5]: who_ls
1045 In [5]: who_ls
1048 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1046 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1049
1047
1050 In [6]: %reset_selective -f d
1048 In [6]: %reset_selective -f d
1051
1049
1052 In [7]: who_ls
1050 In [7]: who_ls
1053 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1051 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1054
1052
1055 In [8]: %reset_selective -f c
1053 In [8]: %reset_selective -f c
1056
1054
1057 In [9]: who_ls
1055 In [9]: who_ls
1058 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1056 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1059
1057
1060 In [10]: %reset_selective -f b
1058 In [10]: %reset_selective -f b
1061
1059
1062 In [11]: who_ls
1060 In [11]: who_ls
1063 Out[11]: ['a']
1061 Out[11]: ['a']
1064 """
1062 """
1065
1063
1066 opts, regex = self.parse_options(parameter_s,'f')
1064 opts, regex = self.parse_options(parameter_s,'f')
1067
1065
1068 if opts.has_key('f'):
1066 if opts.has_key('f'):
1069 ans = True
1067 ans = True
1070 else:
1068 else:
1071 ans = self.shell.ask_yes_no(
1069 ans = self.shell.ask_yes_no(
1072 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1070 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1073 if not ans:
1071 if not ans:
1074 print 'Nothing done.'
1072 print 'Nothing done.'
1075 return
1073 return
1076 user_ns = self.shell.user_ns
1074 user_ns = self.shell.user_ns
1077 if not regex:
1075 if not regex:
1078 print 'No regex pattern specified. Nothing done.'
1076 print 'No regex pattern specified. Nothing done.'
1079 return
1077 return
1080 else:
1078 else:
1081 try:
1079 try:
1082 m = re.compile(regex)
1080 m = re.compile(regex)
1083 except TypeError:
1081 except TypeError:
1084 raise TypeError('regex must be a string or compiled pattern')
1082 raise TypeError('regex must be a string or compiled pattern')
1085 for i in self.magic_who_ls():
1083 for i in self.magic_who_ls():
1086 if m.search(i):
1084 if m.search(i):
1087 del(user_ns[i])
1085 del(user_ns[i])
1088
1086
1089 def magic_xdel(self, parameter_s=''):
1087 def magic_xdel(self, parameter_s=''):
1090 """Delete a variable, trying to clear it from anywhere that
1088 """Delete a variable, trying to clear it from anywhere that
1091 IPython's machinery has references to it. By default, this uses
1089 IPython's machinery has references to it. By default, this uses
1092 the identity of the named object in the user namespace to remove
1090 the identity of the named object in the user namespace to remove
1093 references held under other names. The object is also removed
1091 references held under other names. The object is also removed
1094 from the output history.
1092 from the output history.
1095
1093
1096 Options
1094 Options
1097 -n : Delete the specified name from all namespaces, without
1095 -n : Delete the specified name from all namespaces, without
1098 checking their identity.
1096 checking their identity.
1099 """
1097 """
1100 opts, varname = self.parse_options(parameter_s,'n')
1098 opts, varname = self.parse_options(parameter_s,'n')
1101 try:
1099 try:
1102 self.shell.del_var(varname, ('n' in opts))
1100 self.shell.del_var(varname, ('n' in opts))
1103 except (NameError, ValueError) as e:
1101 except (NameError, ValueError) as e:
1104 print type(e).__name__ +": "+ str(e)
1102 print type(e).__name__ +": "+ str(e)
1105
1103
1106 def magic_logstart(self,parameter_s=''):
1104 def magic_logstart(self,parameter_s=''):
1107 """Start logging anywhere in a session.
1105 """Start logging anywhere in a session.
1108
1106
1109 %logstart [-o|-r|-t] [log_name [log_mode]]
1107 %logstart [-o|-r|-t] [log_name [log_mode]]
1110
1108
1111 If no name is given, it defaults to a file named 'ipython_log.py' in your
1109 If no name is given, it defaults to a file named 'ipython_log.py' in your
1112 current directory, in 'rotate' mode (see below).
1110 current directory, in 'rotate' mode (see below).
1113
1111
1114 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1112 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1115 history up to that point and then continues logging.
1113 history up to that point and then continues logging.
1116
1114
1117 %logstart takes a second optional parameter: logging mode. This can be one
1115 %logstart takes a second optional parameter: logging mode. This can be one
1118 of (note that the modes are given unquoted):\\
1116 of (note that the modes are given unquoted):\\
1119 append: well, that says it.\\
1117 append: well, that says it.\\
1120 backup: rename (if exists) to name~ and start name.\\
1118 backup: rename (if exists) to name~ and start name.\\
1121 global: single logfile in your home dir, appended to.\\
1119 global: single logfile in your home dir, appended to.\\
1122 over : overwrite existing log.\\
1120 over : overwrite existing log.\\
1123 rotate: create rotating logs name.1~, name.2~, etc.
1121 rotate: create rotating logs name.1~, name.2~, etc.
1124
1122
1125 Options:
1123 Options:
1126
1124
1127 -o: log also IPython's output. In this mode, all commands which
1125 -o: log also IPython's output. In this mode, all commands which
1128 generate an Out[NN] prompt are recorded to the logfile, right after
1126 generate an Out[NN] prompt are recorded to the logfile, right after
1129 their corresponding input line. The output lines are always
1127 their corresponding input line. The output lines are always
1130 prepended with a '#[Out]# ' marker, so that the log remains valid
1128 prepended with a '#[Out]# ' marker, so that the log remains valid
1131 Python code.
1129 Python code.
1132
1130
1133 Since this marker is always the same, filtering only the output from
1131 Since this marker is always the same, filtering only the output from
1134 a log is very easy, using for example a simple awk call:
1132 a log is very easy, using for example a simple awk call:
1135
1133
1136 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1134 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1137
1135
1138 -r: log 'raw' input. Normally, IPython's logs contain the processed
1136 -r: log 'raw' input. Normally, IPython's logs contain the processed
1139 input, so that user lines are logged in their final form, converted
1137 input, so that user lines are logged in their final form, converted
1140 into valid Python. For example, %Exit is logged as
1138 into valid Python. For example, %Exit is logged as
1141 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1139 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1142 exactly as typed, with no transformations applied.
1140 exactly as typed, with no transformations applied.
1143
1141
1144 -t: put timestamps before each input line logged (these are put in
1142 -t: put timestamps before each input line logged (these are put in
1145 comments)."""
1143 comments)."""
1146
1144
1147 opts,par = self.parse_options(parameter_s,'ort')
1145 opts,par = self.parse_options(parameter_s,'ort')
1148 log_output = 'o' in opts
1146 log_output = 'o' in opts
1149 log_raw_input = 'r' in opts
1147 log_raw_input = 'r' in opts
1150 timestamp = 't' in opts
1148 timestamp = 't' in opts
1151
1149
1152 logger = self.shell.logger
1150 logger = self.shell.logger
1153
1151
1154 # if no args are given, the defaults set in the logger constructor by
1152 # if no args are given, the defaults set in the logger constructor by
1155 # ipytohn remain valid
1153 # ipytohn remain valid
1156 if par:
1154 if par:
1157 try:
1155 try:
1158 logfname,logmode = par.split()
1156 logfname,logmode = par.split()
1159 except:
1157 except:
1160 logfname = par
1158 logfname = par
1161 logmode = 'backup'
1159 logmode = 'backup'
1162 else:
1160 else:
1163 logfname = logger.logfname
1161 logfname = logger.logfname
1164 logmode = logger.logmode
1162 logmode = logger.logmode
1165 # put logfname into rc struct as if it had been called on the command
1163 # put logfname into rc struct as if it had been called on the command
1166 # line, so it ends up saved in the log header Save it in case we need
1164 # line, so it ends up saved in the log header Save it in case we need
1167 # to restore it...
1165 # to restore it...
1168 old_logfile = self.shell.logfile
1166 old_logfile = self.shell.logfile
1169 if logfname:
1167 if logfname:
1170 logfname = os.path.expanduser(logfname)
1168 logfname = os.path.expanduser(logfname)
1171 self.shell.logfile = logfname
1169 self.shell.logfile = logfname
1172
1170
1173 loghead = '# IPython log file\n\n'
1171 loghead = '# IPython log file\n\n'
1174 try:
1172 try:
1175 started = logger.logstart(logfname,loghead,logmode,
1173 started = logger.logstart(logfname,loghead,logmode,
1176 log_output,timestamp,log_raw_input)
1174 log_output,timestamp,log_raw_input)
1177 except:
1175 except:
1178 self.shell.logfile = old_logfile
1176 self.shell.logfile = old_logfile
1179 warn("Couldn't start log: %s" % sys.exc_info()[1])
1177 warn("Couldn't start log: %s" % sys.exc_info()[1])
1180 else:
1178 else:
1181 # log input history up to this point, optionally interleaving
1179 # log input history up to this point, optionally interleaving
1182 # output if requested
1180 # output if requested
1183
1181
1184 if timestamp:
1182 if timestamp:
1185 # disable timestamping for the previous history, since we've
1183 # disable timestamping for the previous history, since we've
1186 # lost those already (no time machine here).
1184 # lost those already (no time machine here).
1187 logger.timestamp = False
1185 logger.timestamp = False
1188
1186
1189 if log_raw_input:
1187 if log_raw_input:
1190 input_hist = self.shell.history_manager.input_hist_raw
1188 input_hist = self.shell.history_manager.input_hist_raw
1191 else:
1189 else:
1192 input_hist = self.shell.history_manager.input_hist_parsed
1190 input_hist = self.shell.history_manager.input_hist_parsed
1193
1191
1194 if log_output:
1192 if log_output:
1195 log_write = logger.log_write
1193 log_write = logger.log_write
1196 output_hist = self.shell.history_manager.output_hist
1194 output_hist = self.shell.history_manager.output_hist
1197 for n in range(1,len(input_hist)-1):
1195 for n in range(1,len(input_hist)-1):
1198 log_write(input_hist[n].rstrip() + '\n')
1196 log_write(input_hist[n].rstrip() + '\n')
1199 if n in output_hist:
1197 if n in output_hist:
1200 log_write(repr(output_hist[n]),'output')
1198 log_write(repr(output_hist[n]),'output')
1201 else:
1199 else:
1202 logger.log_write('\n'.join(input_hist[1:]))
1200 logger.log_write('\n'.join(input_hist[1:]))
1203 logger.log_write('\n')
1201 logger.log_write('\n')
1204 if timestamp:
1202 if timestamp:
1205 # re-enable timestamping
1203 # re-enable timestamping
1206 logger.timestamp = True
1204 logger.timestamp = True
1207
1205
1208 print ('Activating auto-logging. '
1206 print ('Activating auto-logging. '
1209 'Current session state plus future input saved.')
1207 'Current session state plus future input saved.')
1210 logger.logstate()
1208 logger.logstate()
1211
1209
1212 def magic_logstop(self,parameter_s=''):
1210 def magic_logstop(self,parameter_s=''):
1213 """Fully stop logging and close log file.
1211 """Fully stop logging and close log file.
1214
1212
1215 In order to start logging again, a new %logstart call needs to be made,
1213 In order to start logging again, a new %logstart call needs to be made,
1216 possibly (though not necessarily) with a new filename, mode and other
1214 possibly (though not necessarily) with a new filename, mode and other
1217 options."""
1215 options."""
1218 self.logger.logstop()
1216 self.logger.logstop()
1219
1217
1220 def magic_logoff(self,parameter_s=''):
1218 def magic_logoff(self,parameter_s=''):
1221 """Temporarily stop logging.
1219 """Temporarily stop logging.
1222
1220
1223 You must have previously started logging."""
1221 You must have previously started logging."""
1224 self.shell.logger.switch_log(0)
1222 self.shell.logger.switch_log(0)
1225
1223
1226 def magic_logon(self,parameter_s=''):
1224 def magic_logon(self,parameter_s=''):
1227 """Restart logging.
1225 """Restart logging.
1228
1226
1229 This function is for restarting logging which you've temporarily
1227 This function is for restarting logging which you've temporarily
1230 stopped with %logoff. For starting logging for the first time, you
1228 stopped with %logoff. For starting logging for the first time, you
1231 must use the %logstart function, which allows you to specify an
1229 must use the %logstart function, which allows you to specify an
1232 optional log filename."""
1230 optional log filename."""
1233
1231
1234 self.shell.logger.switch_log(1)
1232 self.shell.logger.switch_log(1)
1235
1233
1236 def magic_logstate(self,parameter_s=''):
1234 def magic_logstate(self,parameter_s=''):
1237 """Print the status of the logging system."""
1235 """Print the status of the logging system."""
1238
1236
1239 self.shell.logger.logstate()
1237 self.shell.logger.logstate()
1240
1238
1241 def magic_pdb(self, parameter_s=''):
1239 def magic_pdb(self, parameter_s=''):
1242 """Control the automatic calling of the pdb interactive debugger.
1240 """Control the automatic calling of the pdb interactive debugger.
1243
1241
1244 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1242 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1245 argument it works as a toggle.
1243 argument it works as a toggle.
1246
1244
1247 When an exception is triggered, IPython can optionally call the
1245 When an exception is triggered, IPython can optionally call the
1248 interactive pdb debugger after the traceback printout. %pdb toggles
1246 interactive pdb debugger after the traceback printout. %pdb toggles
1249 this feature on and off.
1247 this feature on and off.
1250
1248
1251 The initial state of this feature is set in your ipythonrc
1249 The initial state of this feature is set in your ipythonrc
1252 configuration file (the variable is called 'pdb').
1250 configuration file (the variable is called 'pdb').
1253
1251
1254 If you want to just activate the debugger AFTER an exception has fired,
1252 If you want to just activate the debugger AFTER an exception has fired,
1255 without having to type '%pdb on' and rerunning your code, you can use
1253 without having to type '%pdb on' and rerunning your code, you can use
1256 the %debug magic."""
1254 the %debug magic."""
1257
1255
1258 par = parameter_s.strip().lower()
1256 par = parameter_s.strip().lower()
1259
1257
1260 if par:
1258 if par:
1261 try:
1259 try:
1262 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1260 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1263 except KeyError:
1261 except KeyError:
1264 print ('Incorrect argument. Use on/1, off/0, '
1262 print ('Incorrect argument. Use on/1, off/0, '
1265 'or nothing for a toggle.')
1263 'or nothing for a toggle.')
1266 return
1264 return
1267 else:
1265 else:
1268 # toggle
1266 # toggle
1269 new_pdb = not self.shell.call_pdb
1267 new_pdb = not self.shell.call_pdb
1270
1268
1271 # set on the shell
1269 # set on the shell
1272 self.shell.call_pdb = new_pdb
1270 self.shell.call_pdb = new_pdb
1273 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1271 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1274
1272
1275 def magic_debug(self, parameter_s=''):
1273 def magic_debug(self, parameter_s=''):
1276 """Activate the interactive debugger in post-mortem mode.
1274 """Activate the interactive debugger in post-mortem mode.
1277
1275
1278 If an exception has just occurred, this lets you inspect its stack
1276 If an exception has just occurred, this lets you inspect its stack
1279 frames interactively. Note that this will always work only on the last
1277 frames interactively. Note that this will always work only on the last
1280 traceback that occurred, so you must call this quickly after an
1278 traceback that occurred, so you must call this quickly after an
1281 exception that you wish to inspect has fired, because if another one
1279 exception that you wish to inspect has fired, because if another one
1282 occurs, it clobbers the previous one.
1280 occurs, it clobbers the previous one.
1283
1281
1284 If you want IPython to automatically do this on every exception, see
1282 If you want IPython to automatically do this on every exception, see
1285 the %pdb magic for more details.
1283 the %pdb magic for more details.
1286 """
1284 """
1287 self.shell.debugger(force=True)
1285 self.shell.debugger(force=True)
1288
1286
1289 @skip_doctest
1287 @skip_doctest
1290 def magic_prun(self, parameter_s ='',user_mode=1,
1288 def magic_prun(self, parameter_s ='',user_mode=1,
1291 opts=None,arg_lst=None,prog_ns=None):
1289 opts=None,arg_lst=None,prog_ns=None):
1292
1290
1293 """Run a statement through the python code profiler.
1291 """Run a statement through the python code profiler.
1294
1292
1295 Usage:
1293 Usage:
1296 %prun [options] statement
1294 %prun [options] statement
1297
1295
1298 The given statement (which doesn't require quote marks) is run via the
1296 The given statement (which doesn't require quote marks) is run via the
1299 python profiler in a manner similar to the profile.run() function.
1297 python profiler in a manner similar to the profile.run() function.
1300 Namespaces are internally managed to work correctly; profile.run
1298 Namespaces are internally managed to work correctly; profile.run
1301 cannot be used in IPython because it makes certain assumptions about
1299 cannot be used in IPython because it makes certain assumptions about
1302 namespaces which do not hold under IPython.
1300 namespaces which do not hold under IPython.
1303
1301
1304 Options:
1302 Options:
1305
1303
1306 -l <limit>: you can place restrictions on what or how much of the
1304 -l <limit>: you can place restrictions on what or how much of the
1307 profile gets printed. The limit value can be:
1305 profile gets printed. The limit value can be:
1308
1306
1309 * A string: only information for function names containing this string
1307 * A string: only information for function names containing this string
1310 is printed.
1308 is printed.
1311
1309
1312 * An integer: only these many lines are printed.
1310 * An integer: only these many lines are printed.
1313
1311
1314 * A float (between 0 and 1): this fraction of the report is printed
1312 * A float (between 0 and 1): this fraction of the report is printed
1315 (for example, use a limit of 0.4 to see the topmost 40% only).
1313 (for example, use a limit of 0.4 to see the topmost 40% only).
1316
1314
1317 You can combine several limits with repeated use of the option. For
1315 You can combine several limits with repeated use of the option. For
1318 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1316 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1319 information about class constructors.
1317 information about class constructors.
1320
1318
1321 -r: return the pstats.Stats object generated by the profiling. This
1319 -r: return the pstats.Stats object generated by the profiling. This
1322 object has all the information about the profile in it, and you can
1320 object has all the information about the profile in it, and you can
1323 later use it for further analysis or in other functions.
1321 later use it for further analysis or in other functions.
1324
1322
1325 -s <key>: sort profile by given key. You can provide more than one key
1323 -s <key>: sort profile by given key. You can provide more than one key
1326 by using the option several times: '-s key1 -s key2 -s key3...'. The
1324 by using the option several times: '-s key1 -s key2 -s key3...'. The
1327 default sorting key is 'time'.
1325 default sorting key is 'time'.
1328
1326
1329 The following is copied verbatim from the profile documentation
1327 The following is copied verbatim from the profile documentation
1330 referenced below:
1328 referenced below:
1331
1329
1332 When more than one key is provided, additional keys are used as
1330 When more than one key is provided, additional keys are used as
1333 secondary criteria when the there is equality in all keys selected
1331 secondary criteria when the there is equality in all keys selected
1334 before them.
1332 before them.
1335
1333
1336 Abbreviations can be used for any key names, as long as the
1334 Abbreviations can be used for any key names, as long as the
1337 abbreviation is unambiguous. The following are the keys currently
1335 abbreviation is unambiguous. The following are the keys currently
1338 defined:
1336 defined:
1339
1337
1340 Valid Arg Meaning
1338 Valid Arg Meaning
1341 "calls" call count
1339 "calls" call count
1342 "cumulative" cumulative time
1340 "cumulative" cumulative time
1343 "file" file name
1341 "file" file name
1344 "module" file name
1342 "module" file name
1345 "pcalls" primitive call count
1343 "pcalls" primitive call count
1346 "line" line number
1344 "line" line number
1347 "name" function name
1345 "name" function name
1348 "nfl" name/file/line
1346 "nfl" name/file/line
1349 "stdname" standard name
1347 "stdname" standard name
1350 "time" internal time
1348 "time" internal time
1351
1349
1352 Note that all sorts on statistics are in descending order (placing
1350 Note that all sorts on statistics are in descending order (placing
1353 most time consuming items first), where as name, file, and line number
1351 most time consuming items first), where as name, file, and line number
1354 searches are in ascending order (i.e., alphabetical). The subtle
1352 searches are in ascending order (i.e., alphabetical). The subtle
1355 distinction between "nfl" and "stdname" is that the standard name is a
1353 distinction between "nfl" and "stdname" is that the standard name is a
1356 sort of the name as printed, which means that the embedded line
1354 sort of the name as printed, which means that the embedded line
1357 numbers get compared in an odd way. For example, lines 3, 20, and 40
1355 numbers get compared in an odd way. For example, lines 3, 20, and 40
1358 would (if the file names were the same) appear in the string order
1356 would (if the file names were the same) appear in the string order
1359 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1357 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1360 line numbers. In fact, sort_stats("nfl") is the same as
1358 line numbers. In fact, sort_stats("nfl") is the same as
1361 sort_stats("name", "file", "line").
1359 sort_stats("name", "file", "line").
1362
1360
1363 -T <filename>: save profile results as shown on screen to a text
1361 -T <filename>: save profile results as shown on screen to a text
1364 file. The profile is still shown on screen.
1362 file. The profile is still shown on screen.
1365
1363
1366 -D <filename>: save (via dump_stats) profile statistics to given
1364 -D <filename>: save (via dump_stats) profile statistics to given
1367 filename. This data is in a format understod by the pstats module, and
1365 filename. This data is in a format understod by the pstats module, and
1368 is generated by a call to the dump_stats() method of profile
1366 is generated by a call to the dump_stats() method of profile
1369 objects. The profile is still shown on screen.
1367 objects. The profile is still shown on screen.
1370
1368
1371 If you want to run complete programs under the profiler's control, use
1369 If you want to run complete programs under the profiler's control, use
1372 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1370 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1373 contains profiler specific options as described here.
1371 contains profiler specific options as described here.
1374
1372
1375 You can read the complete documentation for the profile module with::
1373 You can read the complete documentation for the profile module with::
1376
1374
1377 In [1]: import profile; profile.help()
1375 In [1]: import profile; profile.help()
1378 """
1376 """
1379
1377
1380 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1378 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1381 # protect user quote marks
1379 # protect user quote marks
1382 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1380 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1383
1381
1384 if user_mode: # regular user call
1382 if user_mode: # regular user call
1385 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1383 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1386 list_all=1)
1384 list_all=1)
1387 namespace = self.shell.user_ns
1385 namespace = self.shell.user_ns
1388 else: # called to run a program by %run -p
1386 else: # called to run a program by %run -p
1389 try:
1387 try:
1390 filename = get_py_filename(arg_lst[0])
1388 filename = get_py_filename(arg_lst[0])
1391 except IOError,msg:
1389 except IOError,msg:
1392 error(msg)
1390 error(msg)
1393 return
1391 return
1394
1392
1395 arg_str = 'execfile(filename,prog_ns)'
1393 arg_str = 'execfile(filename,prog_ns)'
1396 namespace = locals()
1394 namespace = locals()
1397
1395
1398 opts.merge(opts_def)
1396 opts.merge(opts_def)
1399
1397
1400 prof = profile.Profile()
1398 prof = profile.Profile()
1401 try:
1399 try:
1402 prof = prof.runctx(arg_str,namespace,namespace)
1400 prof = prof.runctx(arg_str,namespace,namespace)
1403 sys_exit = ''
1401 sys_exit = ''
1404 except SystemExit:
1402 except SystemExit:
1405 sys_exit = """*** SystemExit exception caught in code being profiled."""
1403 sys_exit = """*** SystemExit exception caught in code being profiled."""
1406
1404
1407 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1405 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1408
1406
1409 lims = opts.l
1407 lims = opts.l
1410 if lims:
1408 if lims:
1411 lims = [] # rebuild lims with ints/floats/strings
1409 lims = [] # rebuild lims with ints/floats/strings
1412 for lim in opts.l:
1410 for lim in opts.l:
1413 try:
1411 try:
1414 lims.append(int(lim))
1412 lims.append(int(lim))
1415 except ValueError:
1413 except ValueError:
1416 try:
1414 try:
1417 lims.append(float(lim))
1415 lims.append(float(lim))
1418 except ValueError:
1416 except ValueError:
1419 lims.append(lim)
1417 lims.append(lim)
1420
1418
1421 # Trap output.
1419 # Trap output.
1422 stdout_trap = StringIO()
1420 stdout_trap = StringIO()
1423
1421
1424 if hasattr(stats,'stream'):
1422 if hasattr(stats,'stream'):
1425 # In newer versions of python, the stats object has a 'stream'
1423 # In newer versions of python, the stats object has a 'stream'
1426 # attribute to write into.
1424 # attribute to write into.
1427 stats.stream = stdout_trap
1425 stats.stream = stdout_trap
1428 stats.print_stats(*lims)
1426 stats.print_stats(*lims)
1429 else:
1427 else:
1430 # For older versions, we manually redirect stdout during printing
1428 # For older versions, we manually redirect stdout during printing
1431 sys_stdout = sys.stdout
1429 sys_stdout = sys.stdout
1432 try:
1430 try:
1433 sys.stdout = stdout_trap
1431 sys.stdout = stdout_trap
1434 stats.print_stats(*lims)
1432 stats.print_stats(*lims)
1435 finally:
1433 finally:
1436 sys.stdout = sys_stdout
1434 sys.stdout = sys_stdout
1437
1435
1438 output = stdout_trap.getvalue()
1436 output = stdout_trap.getvalue()
1439 output = output.rstrip()
1437 output = output.rstrip()
1440
1438
1441 page.page(output)
1439 page.page(output)
1442 print sys_exit,
1440 print sys_exit,
1443
1441
1444 dump_file = opts.D[0]
1442 dump_file = opts.D[0]
1445 text_file = opts.T[0]
1443 text_file = opts.T[0]
1446 if dump_file:
1444 if dump_file:
1447 prof.dump_stats(dump_file)
1445 prof.dump_stats(dump_file)
1448 print '\n*** Profile stats marshalled to file',\
1446 print '\n*** Profile stats marshalled to file',\
1449 `dump_file`+'.',sys_exit
1447 `dump_file`+'.',sys_exit
1450 if text_file:
1448 if text_file:
1451 pfile = file(text_file,'w')
1449 pfile = file(text_file,'w')
1452 pfile.write(output)
1450 pfile.write(output)
1453 pfile.close()
1451 pfile.close()
1454 print '\n*** Profile printout saved to text file',\
1452 print '\n*** Profile printout saved to text file',\
1455 `text_file`+'.',sys_exit
1453 `text_file`+'.',sys_exit
1456
1454
1457 if opts.has_key('r'):
1455 if opts.has_key('r'):
1458 return stats
1456 return stats
1459 else:
1457 else:
1460 return None
1458 return None
1461
1459
1462 @skip_doctest
1460 @skip_doctest
1463 def magic_run(self, parameter_s ='',runner=None,
1461 def magic_run(self, parameter_s ='',runner=None,
1464 file_finder=get_py_filename):
1462 file_finder=get_py_filename):
1465 """Run the named file inside IPython as a program.
1463 """Run the named file inside IPython as a program.
1466
1464
1467 Usage:\\
1465 Usage:\\
1468 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1466 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1469
1467
1470 Parameters after the filename are passed as command-line arguments to
1468 Parameters after the filename are passed as command-line arguments to
1471 the program (put in sys.argv). Then, control returns to IPython's
1469 the program (put in sys.argv). Then, control returns to IPython's
1472 prompt.
1470 prompt.
1473
1471
1474 This is similar to running at a system prompt:\\
1472 This is similar to running at a system prompt:\\
1475 $ python file args\\
1473 $ python file args\\
1476 but with the advantage of giving you IPython's tracebacks, and of
1474 but with the advantage of giving you IPython's tracebacks, and of
1477 loading all variables into your interactive namespace for further use
1475 loading all variables into your interactive namespace for further use
1478 (unless -p is used, see below).
1476 (unless -p is used, see below).
1479
1477
1480 The file is executed in a namespace initially consisting only of
1478 The file is executed in a namespace initially consisting only of
1481 __name__=='__main__' and sys.argv constructed as indicated. It thus
1479 __name__=='__main__' and sys.argv constructed as indicated. It thus
1482 sees its environment as if it were being run as a stand-alone program
1480 sees its environment as if it were being run as a stand-alone program
1483 (except for sharing global objects such as previously imported
1481 (except for sharing global objects such as previously imported
1484 modules). But after execution, the IPython interactive namespace gets
1482 modules). But after execution, the IPython interactive namespace gets
1485 updated with all variables defined in the program (except for __name__
1483 updated with all variables defined in the program (except for __name__
1486 and sys.argv). This allows for very convenient loading of code for
1484 and sys.argv). This allows for very convenient loading of code for
1487 interactive work, while giving each program a 'clean sheet' to run in.
1485 interactive work, while giving each program a 'clean sheet' to run in.
1488
1486
1489 Options:
1487 Options:
1490
1488
1491 -n: __name__ is NOT set to '__main__', but to the running file's name
1489 -n: __name__ is NOT set to '__main__', but to the running file's name
1492 without extension (as python does under import). This allows running
1490 without extension (as python does under import). This allows running
1493 scripts and reloading the definitions in them without calling code
1491 scripts and reloading the definitions in them without calling code
1494 protected by an ' if __name__ == "__main__" ' clause.
1492 protected by an ' if __name__ == "__main__" ' clause.
1495
1493
1496 -i: run the file in IPython's namespace instead of an empty one. This
1494 -i: run the file in IPython's namespace instead of an empty one. This
1497 is useful if you are experimenting with code written in a text editor
1495 is useful if you are experimenting with code written in a text editor
1498 which depends on variables defined interactively.
1496 which depends on variables defined interactively.
1499
1497
1500 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1498 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1501 being run. This is particularly useful if IPython is being used to
1499 being run. This is particularly useful if IPython is being used to
1502 run unittests, which always exit with a sys.exit() call. In such
1500 run unittests, which always exit with a sys.exit() call. In such
1503 cases you are interested in the output of the test results, not in
1501 cases you are interested in the output of the test results, not in
1504 seeing a traceback of the unittest module.
1502 seeing a traceback of the unittest module.
1505
1503
1506 -t: print timing information at the end of the run. IPython will give
1504 -t: print timing information at the end of the run. IPython will give
1507 you an estimated CPU time consumption for your script, which under
1505 you an estimated CPU time consumption for your script, which under
1508 Unix uses the resource module to avoid the wraparound problems of
1506 Unix uses the resource module to avoid the wraparound problems of
1509 time.clock(). Under Unix, an estimate of time spent on system tasks
1507 time.clock(). Under Unix, an estimate of time spent on system tasks
1510 is also given (for Windows platforms this is reported as 0.0).
1508 is also given (for Windows platforms this is reported as 0.0).
1511
1509
1512 If -t is given, an additional -N<N> option can be given, where <N>
1510 If -t is given, an additional -N<N> option can be given, where <N>
1513 must be an integer indicating how many times you want the script to
1511 must be an integer indicating how many times you want the script to
1514 run. The final timing report will include total and per run results.
1512 run. The final timing report will include total and per run results.
1515
1513
1516 For example (testing the script uniq_stable.py):
1514 For example (testing the script uniq_stable.py):
1517
1515
1518 In [1]: run -t uniq_stable
1516 In [1]: run -t uniq_stable
1519
1517
1520 IPython CPU timings (estimated):\\
1518 IPython CPU timings (estimated):\\
1521 User : 0.19597 s.\\
1519 User : 0.19597 s.\\
1522 System: 0.0 s.\\
1520 System: 0.0 s.\\
1523
1521
1524 In [2]: run -t -N5 uniq_stable
1522 In [2]: run -t -N5 uniq_stable
1525
1523
1526 IPython CPU timings (estimated):\\
1524 IPython CPU timings (estimated):\\
1527 Total runs performed: 5\\
1525 Total runs performed: 5\\
1528 Times : Total Per run\\
1526 Times : Total Per run\\
1529 User : 0.910862 s, 0.1821724 s.\\
1527 User : 0.910862 s, 0.1821724 s.\\
1530 System: 0.0 s, 0.0 s.
1528 System: 0.0 s, 0.0 s.
1531
1529
1532 -d: run your program under the control of pdb, the Python debugger.
1530 -d: run your program under the control of pdb, the Python debugger.
1533 This allows you to execute your program step by step, watch variables,
1531 This allows you to execute your program step by step, watch variables,
1534 etc. Internally, what IPython does is similar to calling:
1532 etc. Internally, what IPython does is similar to calling:
1535
1533
1536 pdb.run('execfile("YOURFILENAME")')
1534 pdb.run('execfile("YOURFILENAME")')
1537
1535
1538 with a breakpoint set on line 1 of your file. You can change the line
1536 with a breakpoint set on line 1 of your file. You can change the line
1539 number for this automatic breakpoint to be <N> by using the -bN option
1537 number for this automatic breakpoint to be <N> by using the -bN option
1540 (where N must be an integer). For example:
1538 (where N must be an integer). For example:
1541
1539
1542 %run -d -b40 myscript
1540 %run -d -b40 myscript
1543
1541
1544 will set the first breakpoint at line 40 in myscript.py. Note that
1542 will set the first breakpoint at line 40 in myscript.py. Note that
1545 the first breakpoint must be set on a line which actually does
1543 the first breakpoint must be set on a line which actually does
1546 something (not a comment or docstring) for it to stop execution.
1544 something (not a comment or docstring) for it to stop execution.
1547
1545
1548 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1546 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1549 first enter 'c' (without qoutes) to start execution up to the first
1547 first enter 'c' (without qoutes) to start execution up to the first
1550 breakpoint.
1548 breakpoint.
1551
1549
1552 Entering 'help' gives information about the use of the debugger. You
1550 Entering 'help' gives information about the use of the debugger. You
1553 can easily see pdb's full documentation with "import pdb;pdb.help()"
1551 can easily see pdb's full documentation with "import pdb;pdb.help()"
1554 at a prompt.
1552 at a prompt.
1555
1553
1556 -p: run program under the control of the Python profiler module (which
1554 -p: run program under the control of the Python profiler module (which
1557 prints a detailed report of execution times, function calls, etc).
1555 prints a detailed report of execution times, function calls, etc).
1558
1556
1559 You can pass other options after -p which affect the behavior of the
1557 You can pass other options after -p which affect the behavior of the
1560 profiler itself. See the docs for %prun for details.
1558 profiler itself. See the docs for %prun for details.
1561
1559
1562 In this mode, the program's variables do NOT propagate back to the
1560 In this mode, the program's variables do NOT propagate back to the
1563 IPython interactive namespace (because they remain in the namespace
1561 IPython interactive namespace (because they remain in the namespace
1564 where the profiler executes them).
1562 where the profiler executes them).
1565
1563
1566 Internally this triggers a call to %prun, see its documentation for
1564 Internally this triggers a call to %prun, see its documentation for
1567 details on the options available specifically for profiling.
1565 details on the options available specifically for profiling.
1568
1566
1569 There is one special usage for which the text above doesn't apply:
1567 There is one special usage for which the text above doesn't apply:
1570 if the filename ends with .ipy, the file is run as ipython script,
1568 if the filename ends with .ipy, the file is run as ipython script,
1571 just as if the commands were written on IPython prompt.
1569 just as if the commands were written on IPython prompt.
1572 """
1570 """
1573
1571
1574 # get arguments and set sys.argv for program to be run.
1572 # get arguments and set sys.argv for program to be run.
1575 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1573 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1576 mode='list',list_all=1)
1574 mode='list',list_all=1)
1577
1575
1578 try:
1576 try:
1579 filename = file_finder(arg_lst[0])
1577 filename = file_finder(arg_lst[0])
1580 except IndexError:
1578 except IndexError:
1581 warn('you must provide at least a filename.')
1579 warn('you must provide at least a filename.')
1582 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1580 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1583 return
1581 return
1584 except IOError,msg:
1582 except IOError,msg:
1585 error(msg)
1583 error(msg)
1586 return
1584 return
1587
1585
1588 if filename.lower().endswith('.ipy'):
1586 if filename.lower().endswith('.ipy'):
1589 self.shell.safe_execfile_ipy(filename)
1587 self.shell.safe_execfile_ipy(filename)
1590 return
1588 return
1591
1589
1592 # Control the response to exit() calls made by the script being run
1590 # Control the response to exit() calls made by the script being run
1593 exit_ignore = opts.has_key('e')
1591 exit_ignore = opts.has_key('e')
1594
1592
1595 # Make sure that the running script gets a proper sys.argv as if it
1593 # Make sure that the running script gets a proper sys.argv as if it
1596 # were run from a system shell.
1594 # were run from a system shell.
1597 save_argv = sys.argv # save it for later restoring
1595 save_argv = sys.argv # save it for later restoring
1598 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1596 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1599
1597
1600 if opts.has_key('i'):
1598 if opts.has_key('i'):
1601 # Run in user's interactive namespace
1599 # Run in user's interactive namespace
1602 prog_ns = self.shell.user_ns
1600 prog_ns = self.shell.user_ns
1603 __name__save = self.shell.user_ns['__name__']
1601 __name__save = self.shell.user_ns['__name__']
1604 prog_ns['__name__'] = '__main__'
1602 prog_ns['__name__'] = '__main__'
1605 main_mod = self.shell.new_main_mod(prog_ns)
1603 main_mod = self.shell.new_main_mod(prog_ns)
1606 else:
1604 else:
1607 # Run in a fresh, empty namespace
1605 # Run in a fresh, empty namespace
1608 if opts.has_key('n'):
1606 if opts.has_key('n'):
1609 name = os.path.splitext(os.path.basename(filename))[0]
1607 name = os.path.splitext(os.path.basename(filename))[0]
1610 else:
1608 else:
1611 name = '__main__'
1609 name = '__main__'
1612
1610
1613 main_mod = self.shell.new_main_mod()
1611 main_mod = self.shell.new_main_mod()
1614 prog_ns = main_mod.__dict__
1612 prog_ns = main_mod.__dict__
1615 prog_ns['__name__'] = name
1613 prog_ns['__name__'] = name
1616
1614
1617 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1615 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1618 # set the __file__ global in the script's namespace
1616 # set the __file__ global in the script's namespace
1619 prog_ns['__file__'] = filename
1617 prog_ns['__file__'] = filename
1620
1618
1621 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1619 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1622 # that, if we overwrite __main__, we replace it at the end
1620 # that, if we overwrite __main__, we replace it at the end
1623 main_mod_name = prog_ns['__name__']
1621 main_mod_name = prog_ns['__name__']
1624
1622
1625 if main_mod_name == '__main__':
1623 if main_mod_name == '__main__':
1626 restore_main = sys.modules['__main__']
1624 restore_main = sys.modules['__main__']
1627 else:
1625 else:
1628 restore_main = False
1626 restore_main = False
1629
1627
1630 # This needs to be undone at the end to prevent holding references to
1628 # This needs to be undone at the end to prevent holding references to
1631 # every single object ever created.
1629 # every single object ever created.
1632 sys.modules[main_mod_name] = main_mod
1630 sys.modules[main_mod_name] = main_mod
1633
1631
1634 try:
1632 try:
1635 stats = None
1633 stats = None
1636 with self.readline_no_record:
1634 with self.readline_no_record:
1637 if opts.has_key('p'):
1635 if opts.has_key('p'):
1638 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1636 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1639 else:
1637 else:
1640 if opts.has_key('d'):
1638 if opts.has_key('d'):
1641 deb = debugger.Pdb(self.shell.colors)
1639 deb = debugger.Pdb(self.shell.colors)
1642 # reset Breakpoint state, which is moronically kept
1640 # reset Breakpoint state, which is moronically kept
1643 # in a class
1641 # in a class
1644 bdb.Breakpoint.next = 1
1642 bdb.Breakpoint.next = 1
1645 bdb.Breakpoint.bplist = {}
1643 bdb.Breakpoint.bplist = {}
1646 bdb.Breakpoint.bpbynumber = [None]
1644 bdb.Breakpoint.bpbynumber = [None]
1647 # Set an initial breakpoint to stop execution
1645 # Set an initial breakpoint to stop execution
1648 maxtries = 10
1646 maxtries = 10
1649 bp = int(opts.get('b',[1])[0])
1647 bp = int(opts.get('b',[1])[0])
1650 checkline = deb.checkline(filename,bp)
1648 checkline = deb.checkline(filename,bp)
1651 if not checkline:
1649 if not checkline:
1652 for bp in range(bp+1,bp+maxtries+1):
1650 for bp in range(bp+1,bp+maxtries+1):
1653 if deb.checkline(filename,bp):
1651 if deb.checkline(filename,bp):
1654 break
1652 break
1655 else:
1653 else:
1656 msg = ("\nI failed to find a valid line to set "
1654 msg = ("\nI failed to find a valid line to set "
1657 "a breakpoint\n"
1655 "a breakpoint\n"
1658 "after trying up to line: %s.\n"
1656 "after trying up to line: %s.\n"
1659 "Please set a valid breakpoint manually "
1657 "Please set a valid breakpoint manually "
1660 "with the -b option." % bp)
1658 "with the -b option." % bp)
1661 error(msg)
1659 error(msg)
1662 return
1660 return
1663 # if we find a good linenumber, set the breakpoint
1661 # if we find a good linenumber, set the breakpoint
1664 deb.do_break('%s:%s' % (filename,bp))
1662 deb.do_break('%s:%s' % (filename,bp))
1665 # Start file run
1663 # Start file run
1666 print "NOTE: Enter 'c' at the",
1664 print "NOTE: Enter 'c' at the",
1667 print "%s prompt to start your script." % deb.prompt
1665 print "%s prompt to start your script." % deb.prompt
1668 try:
1666 try:
1669 deb.run('execfile("%s")' % filename,prog_ns)
1667 deb.run('execfile("%s")' % filename,prog_ns)
1670
1668
1671 except:
1669 except:
1672 etype, value, tb = sys.exc_info()
1670 etype, value, tb = sys.exc_info()
1673 # Skip three frames in the traceback: the %run one,
1671 # Skip three frames in the traceback: the %run one,
1674 # one inside bdb.py, and the command-line typed by the
1672 # one inside bdb.py, and the command-line typed by the
1675 # user (run by exec in pdb itself).
1673 # user (run by exec in pdb itself).
1676 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1674 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1677 else:
1675 else:
1678 if runner is None:
1676 if runner is None:
1679 runner = self.shell.safe_execfile
1677 runner = self.shell.safe_execfile
1680 if opts.has_key('t'):
1678 if opts.has_key('t'):
1681 # timed execution
1679 # timed execution
1682 try:
1680 try:
1683 nruns = int(opts['N'][0])
1681 nruns = int(opts['N'][0])
1684 if nruns < 1:
1682 if nruns < 1:
1685 error('Number of runs must be >=1')
1683 error('Number of runs must be >=1')
1686 return
1684 return
1687 except (KeyError):
1685 except (KeyError):
1688 nruns = 1
1686 nruns = 1
1689 if nruns == 1:
1687 if nruns == 1:
1690 t0 = clock2()
1688 t0 = clock2()
1691 runner(filename,prog_ns,prog_ns,
1689 runner(filename,prog_ns,prog_ns,
1692 exit_ignore=exit_ignore)
1690 exit_ignore=exit_ignore)
1693 t1 = clock2()
1691 t1 = clock2()
1694 t_usr = t1[0]-t0[0]
1692 t_usr = t1[0]-t0[0]
1695 t_sys = t1[1]-t0[1]
1693 t_sys = t1[1]-t0[1]
1696 print "\nIPython CPU timings (estimated):"
1694 print "\nIPython CPU timings (estimated):"
1697 print " User : %10s s." % t_usr
1695 print " User : %10s s." % t_usr
1698 print " System: %10s s." % t_sys
1696 print " System: %10s s." % t_sys
1699 else:
1697 else:
1700 runs = range(nruns)
1698 runs = range(nruns)
1701 t0 = clock2()
1699 t0 = clock2()
1702 for nr in runs:
1700 for nr in runs:
1703 runner(filename,prog_ns,prog_ns,
1701 runner(filename,prog_ns,prog_ns,
1704 exit_ignore=exit_ignore)
1702 exit_ignore=exit_ignore)
1705 t1 = clock2()
1703 t1 = clock2()
1706 t_usr = t1[0]-t0[0]
1704 t_usr = t1[0]-t0[0]
1707 t_sys = t1[1]-t0[1]
1705 t_sys = t1[1]-t0[1]
1708 print "\nIPython CPU timings (estimated):"
1706 print "\nIPython CPU timings (estimated):"
1709 print "Total runs performed:",nruns
1707 print "Total runs performed:",nruns
1710 print " Times : %10s %10s" % ('Total','Per run')
1708 print " Times : %10s %10s" % ('Total','Per run')
1711 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1709 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1712 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1710 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1713
1711
1714 else:
1712 else:
1715 # regular execution
1713 # regular execution
1716 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1714 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1717
1715
1718 if opts.has_key('i'):
1716 if opts.has_key('i'):
1719 self.shell.user_ns['__name__'] = __name__save
1717 self.shell.user_ns['__name__'] = __name__save
1720 else:
1718 else:
1721 # The shell MUST hold a reference to prog_ns so after %run
1719 # The shell MUST hold a reference to prog_ns so after %run
1722 # exits, the python deletion mechanism doesn't zero it out
1720 # exits, the python deletion mechanism doesn't zero it out
1723 # (leaving dangling references).
1721 # (leaving dangling references).
1724 self.shell.cache_main_mod(prog_ns,filename)
1722 self.shell.cache_main_mod(prog_ns,filename)
1725 # update IPython interactive namespace
1723 # update IPython interactive namespace
1726
1724
1727 # Some forms of read errors on the file may mean the
1725 # Some forms of read errors on the file may mean the
1728 # __name__ key was never set; using pop we don't have to
1726 # __name__ key was never set; using pop we don't have to
1729 # worry about a possible KeyError.
1727 # worry about a possible KeyError.
1730 prog_ns.pop('__name__', None)
1728 prog_ns.pop('__name__', None)
1731
1729
1732 self.shell.user_ns.update(prog_ns)
1730 self.shell.user_ns.update(prog_ns)
1733 finally:
1731 finally:
1734 # It's a bit of a mystery why, but __builtins__ can change from
1732 # It's a bit of a mystery why, but __builtins__ can change from
1735 # being a module to becoming a dict missing some key data after
1733 # being a module to becoming a dict missing some key data after
1736 # %run. As best I can see, this is NOT something IPython is doing
1734 # %run. As best I can see, this is NOT something IPython is doing
1737 # at all, and similar problems have been reported before:
1735 # at all, and similar problems have been reported before:
1738 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1736 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1739 # Since this seems to be done by the interpreter itself, the best
1737 # Since this seems to be done by the interpreter itself, the best
1740 # we can do is to at least restore __builtins__ for the user on
1738 # we can do is to at least restore __builtins__ for the user on
1741 # exit.
1739 # exit.
1742 self.shell.user_ns['__builtins__'] = __builtin__
1740 self.shell.user_ns['__builtins__'] = __builtin__
1743
1741
1744 # Ensure key global structures are restored
1742 # Ensure key global structures are restored
1745 sys.argv = save_argv
1743 sys.argv = save_argv
1746 if restore_main:
1744 if restore_main:
1747 sys.modules['__main__'] = restore_main
1745 sys.modules['__main__'] = restore_main
1748 else:
1746 else:
1749 # Remove from sys.modules the reference to main_mod we'd
1747 # Remove from sys.modules the reference to main_mod we'd
1750 # added. Otherwise it will trap references to objects
1748 # added. Otherwise it will trap references to objects
1751 # contained therein.
1749 # contained therein.
1752 del sys.modules[main_mod_name]
1750 del sys.modules[main_mod_name]
1753
1751
1754 return stats
1752 return stats
1755
1753
1756 @skip_doctest
1754 @skip_doctest
1757 def magic_timeit(self, parameter_s =''):
1755 def magic_timeit(self, parameter_s =''):
1758 """Time execution of a Python statement or expression
1756 """Time execution of a Python statement or expression
1759
1757
1760 Usage:\\
1758 Usage:\\
1761 %timeit [-n<N> -r<R> [-t|-c]] statement
1759 %timeit [-n<N> -r<R> [-t|-c]] statement
1762
1760
1763 Time execution of a Python statement or expression using the timeit
1761 Time execution of a Python statement or expression using the timeit
1764 module.
1762 module.
1765
1763
1766 Options:
1764 Options:
1767 -n<N>: execute the given statement <N> times in a loop. If this value
1765 -n<N>: execute the given statement <N> times in a loop. If this value
1768 is not given, a fitting value is chosen.
1766 is not given, a fitting value is chosen.
1769
1767
1770 -r<R>: repeat the loop iteration <R> times and take the best result.
1768 -r<R>: repeat the loop iteration <R> times and take the best result.
1771 Default: 3
1769 Default: 3
1772
1770
1773 -t: use time.time to measure the time, which is the default on Unix.
1771 -t: use time.time to measure the time, which is the default on Unix.
1774 This function measures wall time.
1772 This function measures wall time.
1775
1773
1776 -c: use time.clock to measure the time, which is the default on
1774 -c: use time.clock to measure the time, which is the default on
1777 Windows and measures wall time. On Unix, resource.getrusage is used
1775 Windows and measures wall time. On Unix, resource.getrusage is used
1778 instead and returns the CPU user time.
1776 instead and returns the CPU user time.
1779
1777
1780 -p<P>: use a precision of <P> digits to display the timing result.
1778 -p<P>: use a precision of <P> digits to display the timing result.
1781 Default: 3
1779 Default: 3
1782
1780
1783
1781
1784 Examples:
1782 Examples:
1785
1783
1786 In [1]: %timeit pass
1784 In [1]: %timeit pass
1787 10000000 loops, best of 3: 53.3 ns per loop
1785 10000000 loops, best of 3: 53.3 ns per loop
1788
1786
1789 In [2]: u = None
1787 In [2]: u = None
1790
1788
1791 In [3]: %timeit u is None
1789 In [3]: %timeit u is None
1792 10000000 loops, best of 3: 184 ns per loop
1790 10000000 loops, best of 3: 184 ns per loop
1793
1791
1794 In [4]: %timeit -r 4 u == None
1792 In [4]: %timeit -r 4 u == None
1795 1000000 loops, best of 4: 242 ns per loop
1793 1000000 loops, best of 4: 242 ns per loop
1796
1794
1797 In [5]: import time
1795 In [5]: import time
1798
1796
1799 In [6]: %timeit -n1 time.sleep(2)
1797 In [6]: %timeit -n1 time.sleep(2)
1800 1 loops, best of 3: 2 s per loop
1798 1 loops, best of 3: 2 s per loop
1801
1799
1802
1800
1803 The times reported by %timeit will be slightly higher than those
1801 The times reported by %timeit will be slightly higher than those
1804 reported by the timeit.py script when variables are accessed. This is
1802 reported by the timeit.py script when variables are accessed. This is
1805 due to the fact that %timeit executes the statement in the namespace
1803 due to the fact that %timeit executes the statement in the namespace
1806 of the shell, compared with timeit.py, which uses a single setup
1804 of the shell, compared with timeit.py, which uses a single setup
1807 statement to import function or create variables. Generally, the bias
1805 statement to import function or create variables. Generally, the bias
1808 does not matter as long as results from timeit.py are not mixed with
1806 does not matter as long as results from timeit.py are not mixed with
1809 those from %timeit."""
1807 those from %timeit."""
1810
1808
1811 import timeit
1809 import timeit
1812 import math
1810 import math
1813
1811
1814 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1812 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1815 # certain terminals. Until we figure out a robust way of
1813 # certain terminals. Until we figure out a robust way of
1816 # auto-detecting if the terminal can deal with it, use plain 'us' for
1814 # auto-detecting if the terminal can deal with it, use plain 'us' for
1817 # microseconds. I am really NOT happy about disabling the proper
1815 # microseconds. I am really NOT happy about disabling the proper
1818 # 'micro' prefix, but crashing is worse... If anyone knows what the
1816 # 'micro' prefix, but crashing is worse... If anyone knows what the
1819 # right solution for this is, I'm all ears...
1817 # right solution for this is, I'm all ears...
1820 #
1818 #
1821 # Note: using
1819 # Note: using
1822 #
1820 #
1823 # s = u'\xb5'
1821 # s = u'\xb5'
1824 # s.encode(sys.getdefaultencoding())
1822 # s.encode(sys.getdefaultencoding())
1825 #
1823 #
1826 # is not sufficient, as I've seen terminals where that fails but
1824 # is not sufficient, as I've seen terminals where that fails but
1827 # print s
1825 # print s
1828 #
1826 #
1829 # succeeds
1827 # succeeds
1830 #
1828 #
1831 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1829 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1832
1830
1833 #units = [u"s", u"ms",u'\xb5',"ns"]
1831 #units = [u"s", u"ms",u'\xb5',"ns"]
1834 units = [u"s", u"ms",u'us',"ns"]
1832 units = [u"s", u"ms",u'us',"ns"]
1835
1833
1836 scaling = [1, 1e3, 1e6, 1e9]
1834 scaling = [1, 1e3, 1e6, 1e9]
1837
1835
1838 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1836 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1839 posix=False)
1837 posix=False)
1840 if stmt == "":
1838 if stmt == "":
1841 return
1839 return
1842 timefunc = timeit.default_timer
1840 timefunc = timeit.default_timer
1843 number = int(getattr(opts, "n", 0))
1841 number = int(getattr(opts, "n", 0))
1844 repeat = int(getattr(opts, "r", timeit.default_repeat))
1842 repeat = int(getattr(opts, "r", timeit.default_repeat))
1845 precision = int(getattr(opts, "p", 3))
1843 precision = int(getattr(opts, "p", 3))
1846 if hasattr(opts, "t"):
1844 if hasattr(opts, "t"):
1847 timefunc = time.time
1845 timefunc = time.time
1848 if hasattr(opts, "c"):
1846 if hasattr(opts, "c"):
1849 timefunc = clock
1847 timefunc = clock
1850
1848
1851 timer = timeit.Timer(timer=timefunc)
1849 timer = timeit.Timer(timer=timefunc)
1852 # this code has tight coupling to the inner workings of timeit.Timer,
1850 # this code has tight coupling to the inner workings of timeit.Timer,
1853 # but is there a better way to achieve that the code stmt has access
1851 # but is there a better way to achieve that the code stmt has access
1854 # to the shell namespace?
1852 # to the shell namespace?
1855
1853
1856 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1854 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1857 'setup': "pass"}
1855 'setup': "pass"}
1858 # Track compilation time so it can be reported if too long
1856 # Track compilation time so it can be reported if too long
1859 # Minimum time above which compilation time will be reported
1857 # Minimum time above which compilation time will be reported
1860 tc_min = 0.1
1858 tc_min = 0.1
1861
1859
1862 t0 = clock()
1860 t0 = clock()
1863 code = compile(src, "<magic-timeit>", "exec")
1861 code = compile(src, "<magic-timeit>", "exec")
1864 tc = clock()-t0
1862 tc = clock()-t0
1865
1863
1866 ns = {}
1864 ns = {}
1867 exec code in self.shell.user_ns, ns
1865 exec code in self.shell.user_ns, ns
1868 timer.inner = ns["inner"]
1866 timer.inner = ns["inner"]
1869
1867
1870 if number == 0:
1868 if number == 0:
1871 # determine number so that 0.2 <= total time < 2.0
1869 # determine number so that 0.2 <= total time < 2.0
1872 number = 1
1870 number = 1
1873 for i in range(1, 10):
1871 for i in range(1, 10):
1874 if timer.timeit(number) >= 0.2:
1872 if timer.timeit(number) >= 0.2:
1875 break
1873 break
1876 number *= 10
1874 number *= 10
1877
1875
1878 best = min(timer.repeat(repeat, number)) / number
1876 best = min(timer.repeat(repeat, number)) / number
1879
1877
1880 if best > 0.0 and best < 1000.0:
1878 if best > 0.0 and best < 1000.0:
1881 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1879 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1882 elif best >= 1000.0:
1880 elif best >= 1000.0:
1883 order = 0
1881 order = 0
1884 else:
1882 else:
1885 order = 3
1883 order = 3
1886 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1884 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1887 precision,
1885 precision,
1888 best * scaling[order],
1886 best * scaling[order],
1889 units[order])
1887 units[order])
1890 if tc > tc_min:
1888 if tc > tc_min:
1891 print "Compiler time: %.2f s" % tc
1889 print "Compiler time: %.2f s" % tc
1892
1890
1893 @skip_doctest
1891 @skip_doctest
1894 @needs_local_scope
1892 @needs_local_scope
1895 def magic_time(self,parameter_s = ''):
1893 def magic_time(self,parameter_s = ''):
1896 """Time execution of a Python statement or expression.
1894 """Time execution of a Python statement or expression.
1897
1895
1898 The CPU and wall clock times are printed, and the value of the
1896 The CPU and wall clock times are printed, and the value of the
1899 expression (if any) is returned. Note that under Win32, system time
1897 expression (if any) is returned. Note that under Win32, system time
1900 is always reported as 0, since it can not be measured.
1898 is always reported as 0, since it can not be measured.
1901
1899
1902 This function provides very basic timing functionality. In Python
1900 This function provides very basic timing functionality. In Python
1903 2.3, the timeit module offers more control and sophistication, so this
1901 2.3, the timeit module offers more control and sophistication, so this
1904 could be rewritten to use it (patches welcome).
1902 could be rewritten to use it (patches welcome).
1905
1903
1906 Some examples:
1904 Some examples:
1907
1905
1908 In [1]: time 2**128
1906 In [1]: time 2**128
1909 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1907 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1910 Wall time: 0.00
1908 Wall time: 0.00
1911 Out[1]: 340282366920938463463374607431768211456L
1909 Out[1]: 340282366920938463463374607431768211456L
1912
1910
1913 In [2]: n = 1000000
1911 In [2]: n = 1000000
1914
1912
1915 In [3]: time sum(range(n))
1913 In [3]: time sum(range(n))
1916 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1914 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1917 Wall time: 1.37
1915 Wall time: 1.37
1918 Out[3]: 499999500000L
1916 Out[3]: 499999500000L
1919
1917
1920 In [4]: time print 'hello world'
1918 In [4]: time print 'hello world'
1921 hello world
1919 hello world
1922 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1920 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1923 Wall time: 0.00
1921 Wall time: 0.00
1924
1922
1925 Note that the time needed by Python to compile the given expression
1923 Note that the time needed by Python to compile the given expression
1926 will be reported if it is more than 0.1s. In this example, the
1924 will be reported if it is more than 0.1s. In this example, the
1927 actual exponentiation is done by Python at compilation time, so while
1925 actual exponentiation is done by Python at compilation time, so while
1928 the expression can take a noticeable amount of time to compute, that
1926 the expression can take a noticeable amount of time to compute, that
1929 time is purely due to the compilation:
1927 time is purely due to the compilation:
1930
1928
1931 In [5]: time 3**9999;
1929 In [5]: time 3**9999;
1932 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1930 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1933 Wall time: 0.00 s
1931 Wall time: 0.00 s
1934
1932
1935 In [6]: time 3**999999;
1933 In [6]: time 3**999999;
1936 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1934 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1937 Wall time: 0.00 s
1935 Wall time: 0.00 s
1938 Compiler : 0.78 s
1936 Compiler : 0.78 s
1939 """
1937 """
1940
1938
1941 # fail immediately if the given expression can't be compiled
1939 # fail immediately if the given expression can't be compiled
1942
1940
1943 expr = self.shell.prefilter(parameter_s,False)
1941 expr = self.shell.prefilter(parameter_s,False)
1944
1942
1945 # Minimum time above which compilation time will be reported
1943 # Minimum time above which compilation time will be reported
1946 tc_min = 0.1
1944 tc_min = 0.1
1947
1945
1948 try:
1946 try:
1949 mode = 'eval'
1947 mode = 'eval'
1950 t0 = clock()
1948 t0 = clock()
1951 code = compile(expr,'<timed eval>',mode)
1949 code = compile(expr,'<timed eval>',mode)
1952 tc = clock()-t0
1950 tc = clock()-t0
1953 except SyntaxError:
1951 except SyntaxError:
1954 mode = 'exec'
1952 mode = 'exec'
1955 t0 = clock()
1953 t0 = clock()
1956 code = compile(expr,'<timed exec>',mode)
1954 code = compile(expr,'<timed exec>',mode)
1957 tc = clock()-t0
1955 tc = clock()-t0
1958 # skew measurement as little as possible
1956 # skew measurement as little as possible
1959 glob = self.shell.user_ns
1957 glob = self.shell.user_ns
1960 locs = self._magic_locals
1958 locs = self._magic_locals
1961 clk = clock2
1959 clk = clock2
1962 wtime = time.time
1960 wtime = time.time
1963 # time execution
1961 # time execution
1964 wall_st = wtime()
1962 wall_st = wtime()
1965 if mode=='eval':
1963 if mode=='eval':
1966 st = clk()
1964 st = clk()
1967 out = eval(code, glob, locs)
1965 out = eval(code, glob, locs)
1968 end = clk()
1966 end = clk()
1969 else:
1967 else:
1970 st = clk()
1968 st = clk()
1971 exec code in glob, locs
1969 exec code in glob, locs
1972 end = clk()
1970 end = clk()
1973 out = None
1971 out = None
1974 wall_end = wtime()
1972 wall_end = wtime()
1975 # Compute actual times and report
1973 # Compute actual times and report
1976 wall_time = wall_end-wall_st
1974 wall_time = wall_end-wall_st
1977 cpu_user = end[0]-st[0]
1975 cpu_user = end[0]-st[0]
1978 cpu_sys = end[1]-st[1]
1976 cpu_sys = end[1]-st[1]
1979 cpu_tot = cpu_user+cpu_sys
1977 cpu_tot = cpu_user+cpu_sys
1980 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1978 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1981 (cpu_user,cpu_sys,cpu_tot)
1979 (cpu_user,cpu_sys,cpu_tot)
1982 print "Wall time: %.2f s" % wall_time
1980 print "Wall time: %.2f s" % wall_time
1983 if tc > tc_min:
1981 if tc > tc_min:
1984 print "Compiler : %.2f s" % tc
1982 print "Compiler : %.2f s" % tc
1985 return out
1983 return out
1986
1984
1987 @skip_doctest
1985 @skip_doctest
1988 def magic_macro(self,parameter_s = ''):
1986 def magic_macro(self,parameter_s = ''):
1989 """Define a macro for future re-execution. It accepts ranges of history,
1987 """Define a macro for future re-execution. It accepts ranges of history,
1990 filenames or string objects.
1988 filenames or string objects.
1991
1989
1992 Usage:\\
1990 Usage:\\
1993 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1991 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1994
1992
1995 Options:
1993 Options:
1996
1994
1997 -r: use 'raw' input. By default, the 'processed' history is used,
1995 -r: use 'raw' input. By default, the 'processed' history is used,
1998 so that magics are loaded in their transformed version to valid
1996 so that magics are loaded in their transformed version to valid
1999 Python. If this option is given, the raw input as typed as the
1997 Python. If this option is given, the raw input as typed as the
2000 command line is used instead.
1998 command line is used instead.
2001
1999
2002 This will define a global variable called `name` which is a string
2000 This will define a global variable called `name` which is a string
2003 made of joining the slices and lines you specify (n1,n2,... numbers
2001 made of joining the slices and lines you specify (n1,n2,... numbers
2004 above) from your input history into a single string. This variable
2002 above) from your input history into a single string. This variable
2005 acts like an automatic function which re-executes those lines as if
2003 acts like an automatic function which re-executes those lines as if
2006 you had typed them. You just type 'name' at the prompt and the code
2004 you had typed them. You just type 'name' at the prompt and the code
2007 executes.
2005 executes.
2008
2006
2009 The syntax for indicating input ranges is described in %history.
2007 The syntax for indicating input ranges is described in %history.
2010
2008
2011 Note: as a 'hidden' feature, you can also use traditional python slice
2009 Note: as a 'hidden' feature, you can also use traditional python slice
2012 notation, where N:M means numbers N through M-1.
2010 notation, where N:M means numbers N through M-1.
2013
2011
2014 For example, if your history contains (%hist prints it):
2012 For example, if your history contains (%hist prints it):
2015
2013
2016 44: x=1
2014 44: x=1
2017 45: y=3
2015 45: y=3
2018 46: z=x+y
2016 46: z=x+y
2019 47: print x
2017 47: print x
2020 48: a=5
2018 48: a=5
2021 49: print 'x',x,'y',y
2019 49: print 'x',x,'y',y
2022
2020
2023 you can create a macro with lines 44 through 47 (included) and line 49
2021 you can create a macro with lines 44 through 47 (included) and line 49
2024 called my_macro with:
2022 called my_macro with:
2025
2023
2026 In [55]: %macro my_macro 44-47 49
2024 In [55]: %macro my_macro 44-47 49
2027
2025
2028 Now, typing `my_macro` (without quotes) will re-execute all this code
2026 Now, typing `my_macro` (without quotes) will re-execute all this code
2029 in one pass.
2027 in one pass.
2030
2028
2031 You don't need to give the line-numbers in order, and any given line
2029 You don't need to give the line-numbers in order, and any given line
2032 number can appear multiple times. You can assemble macros with any
2030 number can appear multiple times. You can assemble macros with any
2033 lines from your input history in any order.
2031 lines from your input history in any order.
2034
2032
2035 The macro is a simple object which holds its value in an attribute,
2033 The macro is a simple object which holds its value in an attribute,
2036 but IPython's display system checks for macros and executes them as
2034 but IPython's display system checks for macros and executes them as
2037 code instead of printing them when you type their name.
2035 code instead of printing them when you type their name.
2038
2036
2039 You can view a macro's contents by explicitly printing it with:
2037 You can view a macro's contents by explicitly printing it with:
2040
2038
2041 'print macro_name'.
2039 'print macro_name'.
2042
2040
2043 """
2041 """
2044 opts,args = self.parse_options(parameter_s,'r',mode='list')
2042 opts,args = self.parse_options(parameter_s,'r',mode='list')
2045 if not args: # List existing macros
2043 if not args: # List existing macros
2046 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
2044 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
2047 isinstance(v, Macro))
2045 isinstance(v, Macro))
2048 if len(args) == 1:
2046 if len(args) == 1:
2049 raise UsageError(
2047 raise UsageError(
2050 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2048 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2051 name, codefrom = args[0], " ".join(args[1:])
2049 name, codefrom = args[0], " ".join(args[1:])
2052
2050
2053 #print 'rng',ranges # dbg
2051 #print 'rng',ranges # dbg
2054 try:
2052 try:
2055 lines = self.shell.find_user_code(codefrom, 'r' in opts)
2053 lines = self.shell.find_user_code(codefrom, 'r' in opts)
2056 except (ValueError, TypeError) as e:
2054 except (ValueError, TypeError) as e:
2057 print e.args[0]
2055 print e.args[0]
2058 return
2056 return
2059 macro = Macro(lines)
2057 macro = Macro(lines)
2060 self.shell.define_macro(name, macro)
2058 self.shell.define_macro(name, macro)
2061 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2059 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2062 print '=== Macro contents: ==='
2060 print '=== Macro contents: ==='
2063 print macro,
2061 print macro,
2064
2062
2065 def magic_save(self,parameter_s = ''):
2063 def magic_save(self,parameter_s = ''):
2066 """Save a set of lines or a macro to a given filename.
2064 """Save a set of lines or a macro to a given filename.
2067
2065
2068 Usage:\\
2066 Usage:\\
2069 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2067 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2070
2068
2071 Options:
2069 Options:
2072
2070
2073 -r: use 'raw' input. By default, the 'processed' history is used,
2071 -r: use 'raw' input. By default, the 'processed' history is used,
2074 so that magics are loaded in their transformed version to valid
2072 so that magics are loaded in their transformed version to valid
2075 Python. If this option is given, the raw input as typed as the
2073 Python. If this option is given, the raw input as typed as the
2076 command line is used instead.
2074 command line is used instead.
2077
2075
2078 This function uses the same syntax as %history for input ranges,
2076 This function uses the same syntax as %history for input ranges,
2079 then saves the lines to the filename you specify.
2077 then saves the lines to the filename you specify.
2080
2078
2081 It adds a '.py' extension to the file if you don't do so yourself, and
2079 It adds a '.py' extension to the file if you don't do so yourself, and
2082 it asks for confirmation before overwriting existing files."""
2080 it asks for confirmation before overwriting existing files."""
2083
2081
2084 opts,args = self.parse_options(parameter_s,'r',mode='list')
2082 opts,args = self.parse_options(parameter_s,'r',mode='list')
2085 fname, codefrom = args[0], " ".join(args[1:])
2083 fname, codefrom = args[0], " ".join(args[1:])
2086 if not fname.endswith('.py'):
2084 if not fname.endswith('.py'):
2087 fname += '.py'
2085 fname += '.py'
2088 if os.path.isfile(fname):
2086 if os.path.isfile(fname):
2089 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2087 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2090 if ans.lower() not in ['y','yes']:
2088 if ans.lower() not in ['y','yes']:
2091 print 'Operation cancelled.'
2089 print 'Operation cancelled.'
2092 return
2090 return
2093 try:
2091 try:
2094 cmds = self.shell.find_user_code(codefrom, 'r' in opts)
2092 cmds = self.shell.find_user_code(codefrom, 'r' in opts)
2095 except (TypeError, ValueError) as e:
2093 except (TypeError, ValueError) as e:
2096 print e.args[0]
2094 print e.args[0]
2097 return
2095 return
2098 if isinstance(cmds, unicode):
2096 if isinstance(cmds, unicode):
2099 cmds = cmds.encode("utf-8")
2097 cmds = cmds.encode("utf-8")
2100 with open(fname,'w') as f:
2098 with open(fname,'w') as f:
2101 f.write("# coding: utf-8\n")
2099 f.write("# coding: utf-8\n")
2102 f.write(cmds)
2100 f.write(cmds)
2103 print 'The following commands were written to file `%s`:' % fname
2101 print 'The following commands were written to file `%s`:' % fname
2104 print cmds
2102 print cmds
2105
2103
2106 def magic_pastebin(self, parameter_s = ''):
2104 def magic_pastebin(self, parameter_s = ''):
2107 """Upload code to the 'Lodge it' paste bin, returning the URL."""
2105 """Upload code to the 'Lodge it' paste bin, returning the URL."""
2108 try:
2106 try:
2109 code = self.shell.find_user_code(parameter_s)
2107 code = self.shell.find_user_code(parameter_s)
2110 except (ValueError, TypeError) as e:
2108 except (ValueError, TypeError) as e:
2111 print e.args[0]
2109 print e.args[0]
2112 return
2110 return
2113 pbserver = ServerProxy('http://paste.pocoo.org/xmlrpc/')
2111 pbserver = ServerProxy('http://paste.pocoo.org/xmlrpc/')
2114 id = pbserver.pastes.newPaste("python", code)
2112 id = pbserver.pastes.newPaste("python", code)
2115 return "http://paste.pocoo.org/show/" + id
2113 return "http://paste.pocoo.org/show/" + id
2116
2114
2117 def magic_loadpy(self, arg_s):
2115 def magic_loadpy(self, arg_s):
2118 """Load a .py python script into the GUI console.
2116 """Load a .py python script into the GUI console.
2119
2117
2120 This magic command can either take a local filename or a url::
2118 This magic command can either take a local filename or a url::
2121
2119
2122 %loadpy myscript.py
2120 %loadpy myscript.py
2123 %loadpy http://www.example.com/myscript.py
2121 %loadpy http://www.example.com/myscript.py
2124 """
2122 """
2125 if not arg_s.endswith('.py'):
2123 if not arg_s.endswith('.py'):
2126 raise ValueError('%%load only works with .py files: %s' % arg_s)
2124 raise ValueError('%%load only works with .py files: %s' % arg_s)
2127 if arg_s.startswith('http'):
2125 if arg_s.startswith('http'):
2128 import urllib2
2126 import urllib2
2129 response = urllib2.urlopen(arg_s)
2127 response = urllib2.urlopen(arg_s)
2130 content = response.read()
2128 content = response.read()
2131 else:
2129 else:
2132 content = open(arg_s).read()
2130 content = open(arg_s).read()
2133 self.set_next_input(content)
2131 self.set_next_input(content)
2134
2132
2135 def _find_edit_target(self, args, opts, last_call):
2133 def _find_edit_target(self, args, opts, last_call):
2136 """Utility method used by magic_edit to find what to edit."""
2134 """Utility method used by magic_edit to find what to edit."""
2137
2135
2138 def make_filename(arg):
2136 def make_filename(arg):
2139 "Make a filename from the given args"
2137 "Make a filename from the given args"
2140 try:
2138 try:
2141 filename = get_py_filename(arg)
2139 filename = get_py_filename(arg)
2142 except IOError:
2140 except IOError:
2143 # If it ends with .py but doesn't already exist, assume we want
2141 # If it ends with .py but doesn't already exist, assume we want
2144 # a new file.
2142 # a new file.
2145 if args.endswith('.py'):
2143 if args.endswith('.py'):
2146 filename = arg
2144 filename = arg
2147 else:
2145 else:
2148 filename = None
2146 filename = None
2149 return filename
2147 return filename
2150
2148
2151 # Set a few locals from the options for convenience:
2149 # Set a few locals from the options for convenience:
2152 opts_prev = 'p' in opts
2150 opts_prev = 'p' in opts
2153 opts_raw = 'r' in opts
2151 opts_raw = 'r' in opts
2154
2152
2155 # custom exceptions
2153 # custom exceptions
2156 class DataIsObject(Exception): pass
2154 class DataIsObject(Exception): pass
2157
2155
2158 # Default line number value
2156 # Default line number value
2159 lineno = opts.get('n',None)
2157 lineno = opts.get('n',None)
2160
2158
2161 if opts_prev:
2159 if opts_prev:
2162 args = '_%s' % last_call[0]
2160 args = '_%s' % last_call[0]
2163 if not self.shell.user_ns.has_key(args):
2161 if not self.shell.user_ns.has_key(args):
2164 args = last_call[1]
2162 args = last_call[1]
2165
2163
2166 # use last_call to remember the state of the previous call, but don't
2164 # use last_call to remember the state of the previous call, but don't
2167 # let it be clobbered by successive '-p' calls.
2165 # let it be clobbered by successive '-p' calls.
2168 try:
2166 try:
2169 last_call[0] = self.shell.displayhook.prompt_count
2167 last_call[0] = self.shell.displayhook.prompt_count
2170 if not opts_prev:
2168 if not opts_prev:
2171 last_call[1] = parameter_s
2169 last_call[1] = parameter_s
2172 except:
2170 except:
2173 pass
2171 pass
2174
2172
2175 # by default this is done with temp files, except when the given
2173 # by default this is done with temp files, except when the given
2176 # arg is a filename
2174 # arg is a filename
2177 use_temp = True
2175 use_temp = True
2178
2176
2179 data = ''
2177 data = ''
2180
2178
2181 # First, see if the arguments should be a filename.
2179 # First, see if the arguments should be a filename.
2182 filename = make_filename(args)
2180 filename = make_filename(args)
2183 if filename:
2181 if filename:
2184 use_temp = False
2182 use_temp = False
2185 elif args:
2183 elif args:
2186 # Mode where user specifies ranges of lines, like in %macro.
2184 # Mode where user specifies ranges of lines, like in %macro.
2187 data = self.extract_input_lines(args, opts_raw)
2185 data = self.extract_input_lines(args, opts_raw)
2188 if not data:
2186 if not data:
2189 try:
2187 try:
2190 # Load the parameter given as a variable. If not a string,
2188 # Load the parameter given as a variable. If not a string,
2191 # process it as an object instead (below)
2189 # process it as an object instead (below)
2192
2190
2193 #print '*** args',args,'type',type(args) # dbg
2191 #print '*** args',args,'type',type(args) # dbg
2194 data = eval(args, self.shell.user_ns)
2192 data = eval(args, self.shell.user_ns)
2195 if not isinstance(data, basestring):
2193 if not isinstance(data, basestring):
2196 raise DataIsObject
2194 raise DataIsObject
2197
2195
2198 except (NameError,SyntaxError):
2196 except (NameError,SyntaxError):
2199 # given argument is not a variable, try as a filename
2197 # given argument is not a variable, try as a filename
2200 filename = make_filename(args)
2198 filename = make_filename(args)
2201 if filename is None:
2199 if filename is None:
2202 warn("Argument given (%s) can't be found as a variable "
2200 warn("Argument given (%s) can't be found as a variable "
2203 "or as a filename." % args)
2201 "or as a filename." % args)
2204 return
2202 return
2205 use_temp = False
2203 use_temp = False
2206
2204
2207 except DataIsObject:
2205 except DataIsObject:
2208 # macros have a special edit function
2206 # macros have a special edit function
2209 if isinstance(data, Macro):
2207 if isinstance(data, Macro):
2210 raise MacroToEdit(data)
2208 raise MacroToEdit(data)
2211
2209
2212 # For objects, try to edit the file where they are defined
2210 # For objects, try to edit the file where they are defined
2213 try:
2211 try:
2214 filename = inspect.getabsfile(data)
2212 filename = inspect.getabsfile(data)
2215 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2213 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2216 # class created by %edit? Try to find source
2214 # class created by %edit? Try to find source
2217 # by looking for method definitions instead, the
2215 # by looking for method definitions instead, the
2218 # __module__ in those classes is FakeModule.
2216 # __module__ in those classes is FakeModule.
2219 attrs = [getattr(data, aname) for aname in dir(data)]
2217 attrs = [getattr(data, aname) for aname in dir(data)]
2220 for attr in attrs:
2218 for attr in attrs:
2221 if not inspect.ismethod(attr):
2219 if not inspect.ismethod(attr):
2222 continue
2220 continue
2223 filename = inspect.getabsfile(attr)
2221 filename = inspect.getabsfile(attr)
2224 if filename and 'fakemodule' not in filename.lower():
2222 if filename and 'fakemodule' not in filename.lower():
2225 # change the attribute to be the edit target instead
2223 # change the attribute to be the edit target instead
2226 data = attr
2224 data = attr
2227 break
2225 break
2228
2226
2229 datafile = 1
2227 datafile = 1
2230 except TypeError:
2228 except TypeError:
2231 filename = make_filename(args)
2229 filename = make_filename(args)
2232 datafile = 1
2230 datafile = 1
2233 warn('Could not find file where `%s` is defined.\n'
2231 warn('Could not find file where `%s` is defined.\n'
2234 'Opening a file named `%s`' % (args,filename))
2232 'Opening a file named `%s`' % (args,filename))
2235 # Now, make sure we can actually read the source (if it was in
2233 # Now, make sure we can actually read the source (if it was in
2236 # a temp file it's gone by now).
2234 # a temp file it's gone by now).
2237 if datafile:
2235 if datafile:
2238 try:
2236 try:
2239 if lineno is None:
2237 if lineno is None:
2240 lineno = inspect.getsourcelines(data)[1]
2238 lineno = inspect.getsourcelines(data)[1]
2241 except IOError:
2239 except IOError:
2242 filename = make_filename(args)
2240 filename = make_filename(args)
2243 if filename is None:
2241 if filename is None:
2244 warn('The file `%s` where `%s` was defined cannot '
2242 warn('The file `%s` where `%s` was defined cannot '
2245 'be read.' % (filename,data))
2243 'be read.' % (filename,data))
2246 return
2244 return
2247 use_temp = False
2245 use_temp = False
2248
2246
2249 if use_temp:
2247 if use_temp:
2250 filename = self.shell.mktempfile(data)
2248 filename = self.shell.mktempfile(data)
2251 print 'IPython will make a temporary file named:',filename
2249 print 'IPython will make a temporary file named:',filename
2252
2250
2253 return filename, lineno, use_temp
2251 return filename, lineno, use_temp
2254
2252
2255 def _edit_macro(self,mname,macro):
2253 def _edit_macro(self,mname,macro):
2256 """open an editor with the macro data in a file"""
2254 """open an editor with the macro data in a file"""
2257 filename = self.shell.mktempfile(macro.value)
2255 filename = self.shell.mktempfile(macro.value)
2258 self.shell.hooks.editor(filename)
2256 self.shell.hooks.editor(filename)
2259
2257
2260 # and make a new macro object, to replace the old one
2258 # and make a new macro object, to replace the old one
2261 mfile = open(filename)
2259 mfile = open(filename)
2262 mvalue = mfile.read()
2260 mvalue = mfile.read()
2263 mfile.close()
2261 mfile.close()
2264 self.shell.user_ns[mname] = Macro(mvalue)
2262 self.shell.user_ns[mname] = Macro(mvalue)
2265
2263
2266 def magic_ed(self,parameter_s=''):
2264 def magic_ed(self,parameter_s=''):
2267 """Alias to %edit."""
2265 """Alias to %edit."""
2268 return self.magic_edit(parameter_s)
2266 return self.magic_edit(parameter_s)
2269
2267
2270 @skip_doctest
2268 @skip_doctest
2271 def magic_edit(self,parameter_s='',last_call=['','']):
2269 def magic_edit(self,parameter_s='',last_call=['','']):
2272 """Bring up an editor and execute the resulting code.
2270 """Bring up an editor and execute the resulting code.
2273
2271
2274 Usage:
2272 Usage:
2275 %edit [options] [args]
2273 %edit [options] [args]
2276
2274
2277 %edit runs IPython's editor hook. The default version of this hook is
2275 %edit runs IPython's editor hook. The default version of this hook is
2278 set to call the __IPYTHON__.rc.editor command. This is read from your
2276 set to call the __IPYTHON__.rc.editor command. This is read from your
2279 environment variable $EDITOR. If this isn't found, it will default to
2277 environment variable $EDITOR. If this isn't found, it will default to
2280 vi under Linux/Unix and to notepad under Windows. See the end of this
2278 vi under Linux/Unix and to notepad under Windows. See the end of this
2281 docstring for how to change the editor hook.
2279 docstring for how to change the editor hook.
2282
2280
2283 You can also set the value of this editor via the command line option
2281 You can also set the value of this editor via the command line option
2284 '-editor' or in your ipythonrc file. This is useful if you wish to use
2282 '-editor' or in your ipythonrc file. This is useful if you wish to use
2285 specifically for IPython an editor different from your typical default
2283 specifically for IPython an editor different from your typical default
2286 (and for Windows users who typically don't set environment variables).
2284 (and for Windows users who typically don't set environment variables).
2287
2285
2288 This command allows you to conveniently edit multi-line code right in
2286 This command allows you to conveniently edit multi-line code right in
2289 your IPython session.
2287 your IPython session.
2290
2288
2291 If called without arguments, %edit opens up an empty editor with a
2289 If called without arguments, %edit opens up an empty editor with a
2292 temporary file and will execute the contents of this file when you
2290 temporary file and will execute the contents of this file when you
2293 close it (don't forget to save it!).
2291 close it (don't forget to save it!).
2294
2292
2295
2293
2296 Options:
2294 Options:
2297
2295
2298 -n <number>: open the editor at a specified line number. By default,
2296 -n <number>: open the editor at a specified line number. By default,
2299 the IPython editor hook uses the unix syntax 'editor +N filename', but
2297 the IPython editor hook uses the unix syntax 'editor +N filename', but
2300 you can configure this by providing your own modified hook if your
2298 you can configure this by providing your own modified hook if your
2301 favorite editor supports line-number specifications with a different
2299 favorite editor supports line-number specifications with a different
2302 syntax.
2300 syntax.
2303
2301
2304 -p: this will call the editor with the same data as the previous time
2302 -p: this will call the editor with the same data as the previous time
2305 it was used, regardless of how long ago (in your current session) it
2303 it was used, regardless of how long ago (in your current session) it
2306 was.
2304 was.
2307
2305
2308 -r: use 'raw' input. This option only applies to input taken from the
2306 -r: use 'raw' input. This option only applies to input taken from the
2309 user's history. By default, the 'processed' history is used, so that
2307 user's history. By default, the 'processed' history is used, so that
2310 magics are loaded in their transformed version to valid Python. If
2308 magics are loaded in their transformed version to valid Python. If
2311 this option is given, the raw input as typed as the command line is
2309 this option is given, the raw input as typed as the command line is
2312 used instead. When you exit the editor, it will be executed by
2310 used instead. When you exit the editor, it will be executed by
2313 IPython's own processor.
2311 IPython's own processor.
2314
2312
2315 -x: do not execute the edited code immediately upon exit. This is
2313 -x: do not execute the edited code immediately upon exit. This is
2316 mainly useful if you are editing programs which need to be called with
2314 mainly useful if you are editing programs which need to be called with
2317 command line arguments, which you can then do using %run.
2315 command line arguments, which you can then do using %run.
2318
2316
2319
2317
2320 Arguments:
2318 Arguments:
2321
2319
2322 If arguments are given, the following possibilites exist:
2320 If arguments are given, the following possibilites exist:
2323
2321
2324 - If the argument is a filename, IPython will load that into the
2322 - If the argument is a filename, IPython will load that into the
2325 editor. It will execute its contents with execfile() when you exit,
2323 editor. It will execute its contents with execfile() when you exit,
2326 loading any code in the file into your interactive namespace.
2324 loading any code in the file into your interactive namespace.
2327
2325
2328 - The arguments are ranges of input history, e.g. "7 ~1/4-6".
2326 - The arguments are ranges of input history, e.g. "7 ~1/4-6".
2329 The syntax is the same as in the %history magic.
2327 The syntax is the same as in the %history magic.
2330
2328
2331 - If the argument is a string variable, its contents are loaded
2329 - If the argument is a string variable, its contents are loaded
2332 into the editor. You can thus edit any string which contains
2330 into the editor. You can thus edit any string which contains
2333 python code (including the result of previous edits).
2331 python code (including the result of previous edits).
2334
2332
2335 - If the argument is the name of an object (other than a string),
2333 - If the argument is the name of an object (other than a string),
2336 IPython will try to locate the file where it was defined and open the
2334 IPython will try to locate the file where it was defined and open the
2337 editor at the point where it is defined. You can use `%edit function`
2335 editor at the point where it is defined. You can use `%edit function`
2338 to load an editor exactly at the point where 'function' is defined,
2336 to load an editor exactly at the point where 'function' is defined,
2339 edit it and have the file be executed automatically.
2337 edit it and have the file be executed automatically.
2340
2338
2341 If the object is a macro (see %macro for details), this opens up your
2339 If the object is a macro (see %macro for details), this opens up your
2342 specified editor with a temporary file containing the macro's data.
2340 specified editor with a temporary file containing the macro's data.
2343 Upon exit, the macro is reloaded with the contents of the file.
2341 Upon exit, the macro is reloaded with the contents of the file.
2344
2342
2345 Note: opening at an exact line is only supported under Unix, and some
2343 Note: opening at an exact line is only supported under Unix, and some
2346 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2344 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2347 '+NUMBER' parameter necessary for this feature. Good editors like
2345 '+NUMBER' parameter necessary for this feature. Good editors like
2348 (X)Emacs, vi, jed, pico and joe all do.
2346 (X)Emacs, vi, jed, pico and joe all do.
2349
2347
2350 After executing your code, %edit will return as output the code you
2348 After executing your code, %edit will return as output the code you
2351 typed in the editor (except when it was an existing file). This way
2349 typed in the editor (except when it was an existing file). This way
2352 you can reload the code in further invocations of %edit as a variable,
2350 you can reload the code in further invocations of %edit as a variable,
2353 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2351 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2354 the output.
2352 the output.
2355
2353
2356 Note that %edit is also available through the alias %ed.
2354 Note that %edit is also available through the alias %ed.
2357
2355
2358 This is an example of creating a simple function inside the editor and
2356 This is an example of creating a simple function inside the editor and
2359 then modifying it. First, start up the editor:
2357 then modifying it. First, start up the editor:
2360
2358
2361 In [1]: ed
2359 In [1]: ed
2362 Editing... done. Executing edited code...
2360 Editing... done. Executing edited code...
2363 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2361 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2364
2362
2365 We can then call the function foo():
2363 We can then call the function foo():
2366
2364
2367 In [2]: foo()
2365 In [2]: foo()
2368 foo() was defined in an editing session
2366 foo() was defined in an editing session
2369
2367
2370 Now we edit foo. IPython automatically loads the editor with the
2368 Now we edit foo. IPython automatically loads the editor with the
2371 (temporary) file where foo() was previously defined:
2369 (temporary) file where foo() was previously defined:
2372
2370
2373 In [3]: ed foo
2371 In [3]: ed foo
2374 Editing... done. Executing edited code...
2372 Editing... done. Executing edited code...
2375
2373
2376 And if we call foo() again we get the modified version:
2374 And if we call foo() again we get the modified version:
2377
2375
2378 In [4]: foo()
2376 In [4]: foo()
2379 foo() has now been changed!
2377 foo() has now been changed!
2380
2378
2381 Here is an example of how to edit a code snippet successive
2379 Here is an example of how to edit a code snippet successive
2382 times. First we call the editor:
2380 times. First we call the editor:
2383
2381
2384 In [5]: ed
2382 In [5]: ed
2385 Editing... done. Executing edited code...
2383 Editing... done. Executing edited code...
2386 hello
2384 hello
2387 Out[5]: "print 'hello'n"
2385 Out[5]: "print 'hello'n"
2388
2386
2389 Now we call it again with the previous output (stored in _):
2387 Now we call it again with the previous output (stored in _):
2390
2388
2391 In [6]: ed _
2389 In [6]: ed _
2392 Editing... done. Executing edited code...
2390 Editing... done. Executing edited code...
2393 hello world
2391 hello world
2394 Out[6]: "print 'hello world'n"
2392 Out[6]: "print 'hello world'n"
2395
2393
2396 Now we call it with the output #8 (stored in _8, also as Out[8]):
2394 Now we call it with the output #8 (stored in _8, also as Out[8]):
2397
2395
2398 In [7]: ed _8
2396 In [7]: ed _8
2399 Editing... done. Executing edited code...
2397 Editing... done. Executing edited code...
2400 hello again
2398 hello again
2401 Out[7]: "print 'hello again'n"
2399 Out[7]: "print 'hello again'n"
2402
2400
2403
2401
2404 Changing the default editor hook:
2402 Changing the default editor hook:
2405
2403
2406 If you wish to write your own editor hook, you can put it in a
2404 If you wish to write your own editor hook, you can put it in a
2407 configuration file which you load at startup time. The default hook
2405 configuration file which you load at startup time. The default hook
2408 is defined in the IPython.core.hooks module, and you can use that as a
2406 is defined in the IPython.core.hooks module, and you can use that as a
2409 starting example for further modifications. That file also has
2407 starting example for further modifications. That file also has
2410 general instructions on how to set a new hook for use once you've
2408 general instructions on how to set a new hook for use once you've
2411 defined it."""
2409 defined it."""
2412 opts,args = self.parse_options(parameter_s,'prxn:')
2410 opts,args = self.parse_options(parameter_s,'prxn:')
2413
2411
2414 try:
2412 try:
2415 filename, lineno, is_temp = self._find_edit_target(args, opts, last_call)
2413 filename, lineno, is_temp = self._find_edit_target(args, opts, last_call)
2416 except MacroToEdit as e:
2414 except MacroToEdit as e:
2417 self._edit_macro(args, e.args[0])
2415 self._edit_macro(args, e.args[0])
2418 return
2416 return
2419
2417
2420 # do actual editing here
2418 # do actual editing here
2421 print 'Editing...',
2419 print 'Editing...',
2422 sys.stdout.flush()
2420 sys.stdout.flush()
2423 try:
2421 try:
2424 # Quote filenames that may have spaces in them
2422 # Quote filenames that may have spaces in them
2425 if ' ' in filename:
2423 if ' ' in filename:
2426 filename = "'%s'" % filename
2424 filename = "'%s'" % filename
2427 self.shell.hooks.editor(filename,lineno)
2425 self.shell.hooks.editor(filename,lineno)
2428 except TryNext:
2426 except TryNext:
2429 warn('Could not open editor')
2427 warn('Could not open editor')
2430 return
2428 return
2431
2429
2432 # XXX TODO: should this be generalized for all string vars?
2430 # XXX TODO: should this be generalized for all string vars?
2433 # For now, this is special-cased to blocks created by cpaste
2431 # For now, this is special-cased to blocks created by cpaste
2434 if args.strip() == 'pasted_block':
2432 if args.strip() == 'pasted_block':
2435 self.shell.user_ns['pasted_block'] = file_read(filename)
2433 self.shell.user_ns['pasted_block'] = file_read(filename)
2436
2434
2437 if 'x' in opts: # -x prevents actual execution
2435 if 'x' in opts: # -x prevents actual execution
2438 print
2436 print
2439 else:
2437 else:
2440 print 'done. Executing edited code...'
2438 print 'done. Executing edited code...'
2441 if 'r' in opts: # Untranslated IPython code
2439 if 'r' in opts: # Untranslated IPython code
2442 self.shell.run_cell(file_read(filename),
2440 self.shell.run_cell(file_read(filename),
2443 store_history=False)
2441 store_history=False)
2444 else:
2442 else:
2445 self.shell.safe_execfile(filename,self.shell.user_ns,
2443 self.shell.safe_execfile(filename,self.shell.user_ns,
2446 self.shell.user_ns)
2444 self.shell.user_ns)
2447
2445
2448 if is_temp:
2446 if is_temp:
2449 try:
2447 try:
2450 return open(filename).read()
2448 return open(filename).read()
2451 except IOError,msg:
2449 except IOError,msg:
2452 if msg.filename == filename:
2450 if msg.filename == filename:
2453 warn('File not found. Did you forget to save?')
2451 warn('File not found. Did you forget to save?')
2454 return
2452 return
2455 else:
2453 else:
2456 self.shell.showtraceback()
2454 self.shell.showtraceback()
2457
2455
2458 def magic_xmode(self,parameter_s = ''):
2456 def magic_xmode(self,parameter_s = ''):
2459 """Switch modes for the exception handlers.
2457 """Switch modes for the exception handlers.
2460
2458
2461 Valid modes: Plain, Context and Verbose.
2459 Valid modes: Plain, Context and Verbose.
2462
2460
2463 If called without arguments, acts as a toggle."""
2461 If called without arguments, acts as a toggle."""
2464
2462
2465 def xmode_switch_err(name):
2463 def xmode_switch_err(name):
2466 warn('Error changing %s exception modes.\n%s' %
2464 warn('Error changing %s exception modes.\n%s' %
2467 (name,sys.exc_info()[1]))
2465 (name,sys.exc_info()[1]))
2468
2466
2469 shell = self.shell
2467 shell = self.shell
2470 new_mode = parameter_s.strip().capitalize()
2468 new_mode = parameter_s.strip().capitalize()
2471 try:
2469 try:
2472 shell.InteractiveTB.set_mode(mode=new_mode)
2470 shell.InteractiveTB.set_mode(mode=new_mode)
2473 print 'Exception reporting mode:',shell.InteractiveTB.mode
2471 print 'Exception reporting mode:',shell.InteractiveTB.mode
2474 except:
2472 except:
2475 xmode_switch_err('user')
2473 xmode_switch_err('user')
2476
2474
2477 def magic_colors(self,parameter_s = ''):
2475 def magic_colors(self,parameter_s = ''):
2478 """Switch color scheme for prompts, info system and exception handlers.
2476 """Switch color scheme for prompts, info system and exception handlers.
2479
2477
2480 Currently implemented schemes: NoColor, Linux, LightBG.
2478 Currently implemented schemes: NoColor, Linux, LightBG.
2481
2479
2482 Color scheme names are not case-sensitive.
2480 Color scheme names are not case-sensitive.
2483
2481
2484 Examples
2482 Examples
2485 --------
2483 --------
2486 To get a plain black and white terminal::
2484 To get a plain black and white terminal::
2487
2485
2488 %colors nocolor
2486 %colors nocolor
2489 """
2487 """
2490
2488
2491 def color_switch_err(name):
2489 def color_switch_err(name):
2492 warn('Error changing %s color schemes.\n%s' %
2490 warn('Error changing %s color schemes.\n%s' %
2493 (name,sys.exc_info()[1]))
2491 (name,sys.exc_info()[1]))
2494
2492
2495
2493
2496 new_scheme = parameter_s.strip()
2494 new_scheme = parameter_s.strip()
2497 if not new_scheme:
2495 if not new_scheme:
2498 raise UsageError(
2496 raise UsageError(
2499 "%colors: you must specify a color scheme. See '%colors?'")
2497 "%colors: you must specify a color scheme. See '%colors?'")
2500 return
2498 return
2501 # local shortcut
2499 # local shortcut
2502 shell = self.shell
2500 shell = self.shell
2503
2501
2504 import IPython.utils.rlineimpl as readline
2502 import IPython.utils.rlineimpl as readline
2505
2503
2506 if not readline.have_readline and sys.platform == "win32":
2504 if not readline.have_readline and sys.platform == "win32":
2507 msg = """\
2505 msg = """\
2508 Proper color support under MS Windows requires the pyreadline library.
2506 Proper color support under MS Windows requires the pyreadline library.
2509 You can find it at:
2507 You can find it at:
2510 http://ipython.scipy.org/moin/PyReadline/Intro
2508 http://ipython.scipy.org/moin/PyReadline/Intro
2511 Gary's readline needs the ctypes module, from:
2509 Gary's readline needs the ctypes module, from:
2512 http://starship.python.net/crew/theller/ctypes
2510 http://starship.python.net/crew/theller/ctypes
2513 (Note that ctypes is already part of Python versions 2.5 and newer).
2511 (Note that ctypes is already part of Python versions 2.5 and newer).
2514
2512
2515 Defaulting color scheme to 'NoColor'"""
2513 Defaulting color scheme to 'NoColor'"""
2516 new_scheme = 'NoColor'
2514 new_scheme = 'NoColor'
2517 warn(msg)
2515 warn(msg)
2518
2516
2519 # readline option is 0
2517 # readline option is 0
2520 if not shell.has_readline:
2518 if not shell.has_readline:
2521 new_scheme = 'NoColor'
2519 new_scheme = 'NoColor'
2522
2520
2523 # Set prompt colors
2521 # Set prompt colors
2524 try:
2522 try:
2525 shell.displayhook.set_colors(new_scheme)
2523 shell.displayhook.set_colors(new_scheme)
2526 except:
2524 except:
2527 color_switch_err('prompt')
2525 color_switch_err('prompt')
2528 else:
2526 else:
2529 shell.colors = \
2527 shell.colors = \
2530 shell.displayhook.color_table.active_scheme_name
2528 shell.displayhook.color_table.active_scheme_name
2531 # Set exception colors
2529 # Set exception colors
2532 try:
2530 try:
2533 shell.InteractiveTB.set_colors(scheme = new_scheme)
2531 shell.InteractiveTB.set_colors(scheme = new_scheme)
2534 shell.SyntaxTB.set_colors(scheme = new_scheme)
2532 shell.SyntaxTB.set_colors(scheme = new_scheme)
2535 except:
2533 except:
2536 color_switch_err('exception')
2534 color_switch_err('exception')
2537
2535
2538 # Set info (for 'object?') colors
2536 # Set info (for 'object?') colors
2539 if shell.color_info:
2537 if shell.color_info:
2540 try:
2538 try:
2541 shell.inspector.set_active_scheme(new_scheme)
2539 shell.inspector.set_active_scheme(new_scheme)
2542 except:
2540 except:
2543 color_switch_err('object inspector')
2541 color_switch_err('object inspector')
2544 else:
2542 else:
2545 shell.inspector.set_active_scheme('NoColor')
2543 shell.inspector.set_active_scheme('NoColor')
2546
2544
2547 def magic_pprint(self, parameter_s=''):
2545 def magic_pprint(self, parameter_s=''):
2548 """Toggle pretty printing on/off."""
2546 """Toggle pretty printing on/off."""
2549 ptformatter = self.shell.display_formatter.formatters['text/plain']
2547 ptformatter = self.shell.display_formatter.formatters['text/plain']
2550 ptformatter.pprint = bool(1 - ptformatter.pprint)
2548 ptformatter.pprint = bool(1 - ptformatter.pprint)
2551 print 'Pretty printing has been turned', \
2549 print 'Pretty printing has been turned', \
2552 ['OFF','ON'][ptformatter.pprint]
2550 ['OFF','ON'][ptformatter.pprint]
2553
2551
2554 #......................................................................
2552 #......................................................................
2555 # Functions to implement unix shell-type things
2553 # Functions to implement unix shell-type things
2556
2554
2557 @skip_doctest
2555 @skip_doctest
2558 def magic_alias(self, parameter_s = ''):
2556 def magic_alias(self, parameter_s = ''):
2559 """Define an alias for a system command.
2557 """Define an alias for a system command.
2560
2558
2561 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2559 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2562
2560
2563 Then, typing 'alias_name params' will execute the system command 'cmd
2561 Then, typing 'alias_name params' will execute the system command 'cmd
2564 params' (from your underlying operating system).
2562 params' (from your underlying operating system).
2565
2563
2566 Aliases have lower precedence than magic functions and Python normal
2564 Aliases have lower precedence than magic functions and Python normal
2567 variables, so if 'foo' is both a Python variable and an alias, the
2565 variables, so if 'foo' is both a Python variable and an alias, the
2568 alias can not be executed until 'del foo' removes the Python variable.
2566 alias can not be executed until 'del foo' removes the Python variable.
2569
2567
2570 You can use the %l specifier in an alias definition to represent the
2568 You can use the %l specifier in an alias definition to represent the
2571 whole line when the alias is called. For example:
2569 whole line when the alias is called. For example:
2572
2570
2573 In [2]: alias bracket echo "Input in brackets: <%l>"
2571 In [2]: alias bracket echo "Input in brackets: <%l>"
2574 In [3]: bracket hello world
2572 In [3]: bracket hello world
2575 Input in brackets: <hello world>
2573 Input in brackets: <hello world>
2576
2574
2577 You can also define aliases with parameters using %s specifiers (one
2575 You can also define aliases with parameters using %s specifiers (one
2578 per parameter):
2576 per parameter):
2579
2577
2580 In [1]: alias parts echo first %s second %s
2578 In [1]: alias parts echo first %s second %s
2581 In [2]: %parts A B
2579 In [2]: %parts A B
2582 first A second B
2580 first A second B
2583 In [3]: %parts A
2581 In [3]: %parts A
2584 Incorrect number of arguments: 2 expected.
2582 Incorrect number of arguments: 2 expected.
2585 parts is an alias to: 'echo first %s second %s'
2583 parts is an alias to: 'echo first %s second %s'
2586
2584
2587 Note that %l and %s are mutually exclusive. You can only use one or
2585 Note that %l and %s are mutually exclusive. You can only use one or
2588 the other in your aliases.
2586 the other in your aliases.
2589
2587
2590 Aliases expand Python variables just like system calls using ! or !!
2588 Aliases expand Python variables just like system calls using ! or !!
2591 do: all expressions prefixed with '$' get expanded. For details of
2589 do: all expressions prefixed with '$' get expanded. For details of
2592 the semantic rules, see PEP-215:
2590 the semantic rules, see PEP-215:
2593 http://www.python.org/peps/pep-0215.html. This is the library used by
2591 http://www.python.org/peps/pep-0215.html. This is the library used by
2594 IPython for variable expansion. If you want to access a true shell
2592 IPython for variable expansion. If you want to access a true shell
2595 variable, an extra $ is necessary to prevent its expansion by IPython:
2593 variable, an extra $ is necessary to prevent its expansion by IPython:
2596
2594
2597 In [6]: alias show echo
2595 In [6]: alias show echo
2598 In [7]: PATH='A Python string'
2596 In [7]: PATH='A Python string'
2599 In [8]: show $PATH
2597 In [8]: show $PATH
2600 A Python string
2598 A Python string
2601 In [9]: show $$PATH
2599 In [9]: show $$PATH
2602 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2600 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2603
2601
2604 You can use the alias facility to acess all of $PATH. See the %rehash
2602 You can use the alias facility to acess all of $PATH. See the %rehash
2605 and %rehashx functions, which automatically create aliases for the
2603 and %rehashx functions, which automatically create aliases for the
2606 contents of your $PATH.
2604 contents of your $PATH.
2607
2605
2608 If called with no parameters, %alias prints the current alias table."""
2606 If called with no parameters, %alias prints the current alias table."""
2609
2607
2610 par = parameter_s.strip()
2608 par = parameter_s.strip()
2611 if not par:
2609 if not par:
2612 stored = self.db.get('stored_aliases', {} )
2610 stored = self.db.get('stored_aliases', {} )
2613 aliases = sorted(self.shell.alias_manager.aliases)
2611 aliases = sorted(self.shell.alias_manager.aliases)
2614 # for k, v in stored:
2612 # for k, v in stored:
2615 # atab.append(k, v[0])
2613 # atab.append(k, v[0])
2616
2614
2617 print "Total number of aliases:", len(aliases)
2615 print "Total number of aliases:", len(aliases)
2618 sys.stdout.flush()
2616 sys.stdout.flush()
2619 return aliases
2617 return aliases
2620
2618
2621 # Now try to define a new one
2619 # Now try to define a new one
2622 try:
2620 try:
2623 alias,cmd = par.split(None, 1)
2621 alias,cmd = par.split(None, 1)
2624 except:
2622 except:
2625 print oinspect.getdoc(self.magic_alias)
2623 print oinspect.getdoc(self.magic_alias)
2626 else:
2624 else:
2627 self.shell.alias_manager.soft_define_alias(alias, cmd)
2625 self.shell.alias_manager.soft_define_alias(alias, cmd)
2628 # end magic_alias
2626 # end magic_alias
2629
2627
2630 def magic_unalias(self, parameter_s = ''):
2628 def magic_unalias(self, parameter_s = ''):
2631 """Remove an alias"""
2629 """Remove an alias"""
2632
2630
2633 aname = parameter_s.strip()
2631 aname = parameter_s.strip()
2634 self.shell.alias_manager.undefine_alias(aname)
2632 self.shell.alias_manager.undefine_alias(aname)
2635 stored = self.db.get('stored_aliases', {} )
2633 stored = self.db.get('stored_aliases', {} )
2636 if aname in stored:
2634 if aname in stored:
2637 print "Removing %stored alias",aname
2635 print "Removing %stored alias",aname
2638 del stored[aname]
2636 del stored[aname]
2639 self.db['stored_aliases'] = stored
2637 self.db['stored_aliases'] = stored
2640
2638
2641 def magic_rehashx(self, parameter_s = ''):
2639 def magic_rehashx(self, parameter_s = ''):
2642 """Update the alias table with all executable files in $PATH.
2640 """Update the alias table with all executable files in $PATH.
2643
2641
2644 This version explicitly checks that every entry in $PATH is a file
2642 This version explicitly checks that every entry in $PATH is a file
2645 with execute access (os.X_OK), so it is much slower than %rehash.
2643 with execute access (os.X_OK), so it is much slower than %rehash.
2646
2644
2647 Under Windows, it checks executability as a match agains a
2645 Under Windows, it checks executability as a match agains a
2648 '|'-separated string of extensions, stored in the IPython config
2646 '|'-separated string of extensions, stored in the IPython config
2649 variable win_exec_ext. This defaults to 'exe|com|bat'.
2647 variable win_exec_ext. This defaults to 'exe|com|bat'.
2650
2648
2651 This function also resets the root module cache of module completer,
2649 This function also resets the root module cache of module completer,
2652 used on slow filesystems.
2650 used on slow filesystems.
2653 """
2651 """
2654 from IPython.core.alias import InvalidAliasError
2652 from IPython.core.alias import InvalidAliasError
2655
2653
2656 # for the benefit of module completer in ipy_completers.py
2654 # for the benefit of module completer in ipy_completers.py
2657 del self.db['rootmodules']
2655 del self.db['rootmodules']
2658
2656
2659 path = [os.path.abspath(os.path.expanduser(p)) for p in
2657 path = [os.path.abspath(os.path.expanduser(p)) for p in
2660 os.environ.get('PATH','').split(os.pathsep)]
2658 os.environ.get('PATH','').split(os.pathsep)]
2661 path = filter(os.path.isdir,path)
2659 path = filter(os.path.isdir,path)
2662
2660
2663 syscmdlist = []
2661 syscmdlist = []
2664 # Now define isexec in a cross platform manner.
2662 # Now define isexec in a cross platform manner.
2665 if os.name == 'posix':
2663 if os.name == 'posix':
2666 isexec = lambda fname:os.path.isfile(fname) and \
2664 isexec = lambda fname:os.path.isfile(fname) and \
2667 os.access(fname,os.X_OK)
2665 os.access(fname,os.X_OK)
2668 else:
2666 else:
2669 try:
2667 try:
2670 winext = os.environ['pathext'].replace(';','|').replace('.','')
2668 winext = os.environ['pathext'].replace(';','|').replace('.','')
2671 except KeyError:
2669 except KeyError:
2672 winext = 'exe|com|bat|py'
2670 winext = 'exe|com|bat|py'
2673 if 'py' not in winext:
2671 if 'py' not in winext:
2674 winext += '|py'
2672 winext += '|py'
2675 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2673 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2676 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2674 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2677 savedir = os.getcwd()
2675 savedir = os.getcwd()
2678
2676
2679 # Now walk the paths looking for executables to alias.
2677 # Now walk the paths looking for executables to alias.
2680 try:
2678 try:
2681 # write the whole loop for posix/Windows so we don't have an if in
2679 # write the whole loop for posix/Windows so we don't have an if in
2682 # the innermost part
2680 # the innermost part
2683 if os.name == 'posix':
2681 if os.name == 'posix':
2684 for pdir in path:
2682 for pdir in path:
2685 os.chdir(pdir)
2683 os.chdir(pdir)
2686 for ff in os.listdir(pdir):
2684 for ff in os.listdir(pdir):
2687 if isexec(ff):
2685 if isexec(ff):
2688 try:
2686 try:
2689 # Removes dots from the name since ipython
2687 # Removes dots from the name since ipython
2690 # will assume names with dots to be python.
2688 # will assume names with dots to be python.
2691 self.shell.alias_manager.define_alias(
2689 self.shell.alias_manager.define_alias(
2692 ff.replace('.',''), ff)
2690 ff.replace('.',''), ff)
2693 except InvalidAliasError:
2691 except InvalidAliasError:
2694 pass
2692 pass
2695 else:
2693 else:
2696 syscmdlist.append(ff)
2694 syscmdlist.append(ff)
2697 else:
2695 else:
2698 no_alias = self.shell.alias_manager.no_alias
2696 no_alias = self.shell.alias_manager.no_alias
2699 for pdir in path:
2697 for pdir in path:
2700 os.chdir(pdir)
2698 os.chdir(pdir)
2701 for ff in os.listdir(pdir):
2699 for ff in os.listdir(pdir):
2702 base, ext = os.path.splitext(ff)
2700 base, ext = os.path.splitext(ff)
2703 if isexec(ff) and base.lower() not in no_alias:
2701 if isexec(ff) and base.lower() not in no_alias:
2704 if ext.lower() == '.exe':
2702 if ext.lower() == '.exe':
2705 ff = base
2703 ff = base
2706 try:
2704 try:
2707 # Removes dots from the name since ipython
2705 # Removes dots from the name since ipython
2708 # will assume names with dots to be python.
2706 # will assume names with dots to be python.
2709 self.shell.alias_manager.define_alias(
2707 self.shell.alias_manager.define_alias(
2710 base.lower().replace('.',''), ff)
2708 base.lower().replace('.',''), ff)
2711 except InvalidAliasError:
2709 except InvalidAliasError:
2712 pass
2710 pass
2713 syscmdlist.append(ff)
2711 syscmdlist.append(ff)
2714 db = self.db
2712 db = self.db
2715 db['syscmdlist'] = syscmdlist
2713 db['syscmdlist'] = syscmdlist
2716 finally:
2714 finally:
2717 os.chdir(savedir)
2715 os.chdir(savedir)
2718
2716
2719 @skip_doctest
2717 @skip_doctest
2720 def magic_pwd(self, parameter_s = ''):
2718 def magic_pwd(self, parameter_s = ''):
2721 """Return the current working directory path.
2719 """Return the current working directory path.
2722
2720
2723 Examples
2721 Examples
2724 --------
2722 --------
2725 ::
2723 ::
2726
2724
2727 In [9]: pwd
2725 In [9]: pwd
2728 Out[9]: '/home/tsuser/sprint/ipython'
2726 Out[9]: '/home/tsuser/sprint/ipython'
2729 """
2727 """
2730 return os.getcwd()
2728 return os.getcwd()
2731
2729
2732 @skip_doctest
2730 @skip_doctest
2733 def magic_cd(self, parameter_s=''):
2731 def magic_cd(self, parameter_s=''):
2734 """Change the current working directory.
2732 """Change the current working directory.
2735
2733
2736 This command automatically maintains an internal list of directories
2734 This command automatically maintains an internal list of directories
2737 you visit during your IPython session, in the variable _dh. The
2735 you visit during your IPython session, in the variable _dh. The
2738 command %dhist shows this history nicely formatted. You can also
2736 command %dhist shows this history nicely formatted. You can also
2739 do 'cd -<tab>' to see directory history conveniently.
2737 do 'cd -<tab>' to see directory history conveniently.
2740
2738
2741 Usage:
2739 Usage:
2742
2740
2743 cd 'dir': changes to directory 'dir'.
2741 cd 'dir': changes to directory 'dir'.
2744
2742
2745 cd -: changes to the last visited directory.
2743 cd -: changes to the last visited directory.
2746
2744
2747 cd -<n>: changes to the n-th directory in the directory history.
2745 cd -<n>: changes to the n-th directory in the directory history.
2748
2746
2749 cd --foo: change to directory that matches 'foo' in history
2747 cd --foo: change to directory that matches 'foo' in history
2750
2748
2751 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2749 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2752 (note: cd <bookmark_name> is enough if there is no
2750 (note: cd <bookmark_name> is enough if there is no
2753 directory <bookmark_name>, but a bookmark with the name exists.)
2751 directory <bookmark_name>, but a bookmark with the name exists.)
2754 'cd -b <tab>' allows you to tab-complete bookmark names.
2752 'cd -b <tab>' allows you to tab-complete bookmark names.
2755
2753
2756 Options:
2754 Options:
2757
2755
2758 -q: quiet. Do not print the working directory after the cd command is
2756 -q: quiet. Do not print the working directory after the cd command is
2759 executed. By default IPython's cd command does print this directory,
2757 executed. By default IPython's cd command does print this directory,
2760 since the default prompts do not display path information.
2758 since the default prompts do not display path information.
2761
2759
2762 Note that !cd doesn't work for this purpose because the shell where
2760 Note that !cd doesn't work for this purpose because the shell where
2763 !command runs is immediately discarded after executing 'command'.
2761 !command runs is immediately discarded after executing 'command'.
2764
2762
2765 Examples
2763 Examples
2766 --------
2764 --------
2767 ::
2765 ::
2768
2766
2769 In [10]: cd parent/child
2767 In [10]: cd parent/child
2770 /home/tsuser/parent/child
2768 /home/tsuser/parent/child
2771 """
2769 """
2772
2770
2773 parameter_s = parameter_s.strip()
2771 parameter_s = parameter_s.strip()
2774 #bkms = self.shell.persist.get("bookmarks",{})
2772 #bkms = self.shell.persist.get("bookmarks",{})
2775
2773
2776 oldcwd = os.getcwd()
2774 oldcwd = os.getcwd()
2777 numcd = re.match(r'(-)(\d+)$',parameter_s)
2775 numcd = re.match(r'(-)(\d+)$',parameter_s)
2778 # jump in directory history by number
2776 # jump in directory history by number
2779 if numcd:
2777 if numcd:
2780 nn = int(numcd.group(2))
2778 nn = int(numcd.group(2))
2781 try:
2779 try:
2782 ps = self.shell.user_ns['_dh'][nn]
2780 ps = self.shell.user_ns['_dh'][nn]
2783 except IndexError:
2781 except IndexError:
2784 print 'The requested directory does not exist in history.'
2782 print 'The requested directory does not exist in history.'
2785 return
2783 return
2786 else:
2784 else:
2787 opts = {}
2785 opts = {}
2788 elif parameter_s.startswith('--'):
2786 elif parameter_s.startswith('--'):
2789 ps = None
2787 ps = None
2790 fallback = None
2788 fallback = None
2791 pat = parameter_s[2:]
2789 pat = parameter_s[2:]
2792 dh = self.shell.user_ns['_dh']
2790 dh = self.shell.user_ns['_dh']
2793 # first search only by basename (last component)
2791 # first search only by basename (last component)
2794 for ent in reversed(dh):
2792 for ent in reversed(dh):
2795 if pat in os.path.basename(ent) and os.path.isdir(ent):
2793 if pat in os.path.basename(ent) and os.path.isdir(ent):
2796 ps = ent
2794 ps = ent
2797 break
2795 break
2798
2796
2799 if fallback is None and pat in ent and os.path.isdir(ent):
2797 if fallback is None and pat in ent and os.path.isdir(ent):
2800 fallback = ent
2798 fallback = ent
2801
2799
2802 # if we have no last part match, pick the first full path match
2800 # if we have no last part match, pick the first full path match
2803 if ps is None:
2801 if ps is None:
2804 ps = fallback
2802 ps = fallback
2805
2803
2806 if ps is None:
2804 if ps is None:
2807 print "No matching entry in directory history"
2805 print "No matching entry in directory history"
2808 return
2806 return
2809 else:
2807 else:
2810 opts = {}
2808 opts = {}
2811
2809
2812
2810
2813 else:
2811 else:
2814 #turn all non-space-escaping backslashes to slashes,
2812 #turn all non-space-escaping backslashes to slashes,
2815 # for c:\windows\directory\names\
2813 # for c:\windows\directory\names\
2816 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2814 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2817 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2815 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2818 # jump to previous
2816 # jump to previous
2819 if ps == '-':
2817 if ps == '-':
2820 try:
2818 try:
2821 ps = self.shell.user_ns['_dh'][-2]
2819 ps = self.shell.user_ns['_dh'][-2]
2822 except IndexError:
2820 except IndexError:
2823 raise UsageError('%cd -: No previous directory to change to.')
2821 raise UsageError('%cd -: No previous directory to change to.')
2824 # jump to bookmark if needed
2822 # jump to bookmark if needed
2825 else:
2823 else:
2826 if not os.path.isdir(ps) or opts.has_key('b'):
2824 if not os.path.isdir(ps) or opts.has_key('b'):
2827 bkms = self.db.get('bookmarks', {})
2825 bkms = self.db.get('bookmarks', {})
2828
2826
2829 if bkms.has_key(ps):
2827 if bkms.has_key(ps):
2830 target = bkms[ps]
2828 target = bkms[ps]
2831 print '(bookmark:%s) -> %s' % (ps,target)
2829 print '(bookmark:%s) -> %s' % (ps,target)
2832 ps = target
2830 ps = target
2833 else:
2831 else:
2834 if opts.has_key('b'):
2832 if opts.has_key('b'):
2835 raise UsageError("Bookmark '%s' not found. "
2833 raise UsageError("Bookmark '%s' not found. "
2836 "Use '%%bookmark -l' to see your bookmarks." % ps)
2834 "Use '%%bookmark -l' to see your bookmarks." % ps)
2837
2835
2838 # at this point ps should point to the target dir
2836 # at this point ps should point to the target dir
2839 if ps:
2837 if ps:
2840 try:
2838 try:
2841 os.chdir(os.path.expanduser(ps))
2839 os.chdir(os.path.expanduser(ps))
2842 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2840 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2843 set_term_title('IPython: ' + abbrev_cwd())
2841 set_term_title('IPython: ' + abbrev_cwd())
2844 except OSError:
2842 except OSError:
2845 print sys.exc_info()[1]
2843 print sys.exc_info()[1]
2846 else:
2844 else:
2847 cwd = os.getcwd()
2845 cwd = os.getcwd()
2848 dhist = self.shell.user_ns['_dh']
2846 dhist = self.shell.user_ns['_dh']
2849 if oldcwd != cwd:
2847 if oldcwd != cwd:
2850 dhist.append(cwd)
2848 dhist.append(cwd)
2851 self.db['dhist'] = compress_dhist(dhist)[-100:]
2849 self.db['dhist'] = compress_dhist(dhist)[-100:]
2852
2850
2853 else:
2851 else:
2854 os.chdir(self.shell.home_dir)
2852 os.chdir(self.shell.home_dir)
2855 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2853 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2856 set_term_title('IPython: ' + '~')
2854 set_term_title('IPython: ' + '~')
2857 cwd = os.getcwd()
2855 cwd = os.getcwd()
2858 dhist = self.shell.user_ns['_dh']
2856 dhist = self.shell.user_ns['_dh']
2859
2857
2860 if oldcwd != cwd:
2858 if oldcwd != cwd:
2861 dhist.append(cwd)
2859 dhist.append(cwd)
2862 self.db['dhist'] = compress_dhist(dhist)[-100:]
2860 self.db['dhist'] = compress_dhist(dhist)[-100:]
2863 if not 'q' in opts and self.shell.user_ns['_dh']:
2861 if not 'q' in opts and self.shell.user_ns['_dh']:
2864 print self.shell.user_ns['_dh'][-1]
2862 print self.shell.user_ns['_dh'][-1]
2865
2863
2866
2864
2867 def magic_env(self, parameter_s=''):
2865 def magic_env(self, parameter_s=''):
2868 """List environment variables."""
2866 """List environment variables."""
2869
2867
2870 return os.environ.data
2868 return os.environ.data
2871
2869
2872 def magic_pushd(self, parameter_s=''):
2870 def magic_pushd(self, parameter_s=''):
2873 """Place the current dir on stack and change directory.
2871 """Place the current dir on stack and change directory.
2874
2872
2875 Usage:\\
2873 Usage:\\
2876 %pushd ['dirname']
2874 %pushd ['dirname']
2877 """
2875 """
2878
2876
2879 dir_s = self.shell.dir_stack
2877 dir_s = self.shell.dir_stack
2880 tgt = os.path.expanduser(parameter_s)
2878 tgt = os.path.expanduser(parameter_s)
2881 cwd = os.getcwd().replace(self.home_dir,'~')
2879 cwd = os.getcwd().replace(self.home_dir,'~')
2882 if tgt:
2880 if tgt:
2883 self.magic_cd(parameter_s)
2881 self.magic_cd(parameter_s)
2884 dir_s.insert(0,cwd)
2882 dir_s.insert(0,cwd)
2885 return self.magic_dirs()
2883 return self.magic_dirs()
2886
2884
2887 def magic_popd(self, parameter_s=''):
2885 def magic_popd(self, parameter_s=''):
2888 """Change to directory popped off the top of the stack.
2886 """Change to directory popped off the top of the stack.
2889 """
2887 """
2890 if not self.shell.dir_stack:
2888 if not self.shell.dir_stack:
2891 raise UsageError("%popd on empty stack")
2889 raise UsageError("%popd on empty stack")
2892 top = self.shell.dir_stack.pop(0)
2890 top = self.shell.dir_stack.pop(0)
2893 self.magic_cd(top)
2891 self.magic_cd(top)
2894 print "popd ->",top
2892 print "popd ->",top
2895
2893
2896 def magic_dirs(self, parameter_s=''):
2894 def magic_dirs(self, parameter_s=''):
2897 """Return the current directory stack."""
2895 """Return the current directory stack."""
2898
2896
2899 return self.shell.dir_stack
2897 return self.shell.dir_stack
2900
2898
2901 def magic_dhist(self, parameter_s=''):
2899 def magic_dhist(self, parameter_s=''):
2902 """Print your history of visited directories.
2900 """Print your history of visited directories.
2903
2901
2904 %dhist -> print full history\\
2902 %dhist -> print full history\\
2905 %dhist n -> print last n entries only\\
2903 %dhist n -> print last n entries only\\
2906 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2904 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2907
2905
2908 This history is automatically maintained by the %cd command, and
2906 This history is automatically maintained by the %cd command, and
2909 always available as the global list variable _dh. You can use %cd -<n>
2907 always available as the global list variable _dh. You can use %cd -<n>
2910 to go to directory number <n>.
2908 to go to directory number <n>.
2911
2909
2912 Note that most of time, you should view directory history by entering
2910 Note that most of time, you should view directory history by entering
2913 cd -<TAB>.
2911 cd -<TAB>.
2914
2912
2915 """
2913 """
2916
2914
2917 dh = self.shell.user_ns['_dh']
2915 dh = self.shell.user_ns['_dh']
2918 if parameter_s:
2916 if parameter_s:
2919 try:
2917 try:
2920 args = map(int,parameter_s.split())
2918 args = map(int,parameter_s.split())
2921 except:
2919 except:
2922 self.arg_err(Magic.magic_dhist)
2920 self.arg_err(Magic.magic_dhist)
2923 return
2921 return
2924 if len(args) == 1:
2922 if len(args) == 1:
2925 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2923 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2926 elif len(args) == 2:
2924 elif len(args) == 2:
2927 ini,fin = args
2925 ini,fin = args
2928 else:
2926 else:
2929 self.arg_err(Magic.magic_dhist)
2927 self.arg_err(Magic.magic_dhist)
2930 return
2928 return
2931 else:
2929 else:
2932 ini,fin = 0,len(dh)
2930 ini,fin = 0,len(dh)
2933 nlprint(dh,
2931 nlprint(dh,
2934 header = 'Directory history (kept in _dh)',
2932 header = 'Directory history (kept in _dh)',
2935 start=ini,stop=fin)
2933 start=ini,stop=fin)
2936
2934
2937 @skip_doctest
2935 @skip_doctest
2938 def magic_sc(self, parameter_s=''):
2936 def magic_sc(self, parameter_s=''):
2939 """Shell capture - execute a shell command and capture its output.
2937 """Shell capture - execute a shell command and capture its output.
2940
2938
2941 DEPRECATED. Suboptimal, retained for backwards compatibility.
2939 DEPRECATED. Suboptimal, retained for backwards compatibility.
2942
2940
2943 You should use the form 'var = !command' instead. Example:
2941 You should use the form 'var = !command' instead. Example:
2944
2942
2945 "%sc -l myfiles = ls ~" should now be written as
2943 "%sc -l myfiles = ls ~" should now be written as
2946
2944
2947 "myfiles = !ls ~"
2945 "myfiles = !ls ~"
2948
2946
2949 myfiles.s, myfiles.l and myfiles.n still apply as documented
2947 myfiles.s, myfiles.l and myfiles.n still apply as documented
2950 below.
2948 below.
2951
2949
2952 --
2950 --
2953 %sc [options] varname=command
2951 %sc [options] varname=command
2954
2952
2955 IPython will run the given command using commands.getoutput(), and
2953 IPython will run the given command using commands.getoutput(), and
2956 will then update the user's interactive namespace with a variable
2954 will then update the user's interactive namespace with a variable
2957 called varname, containing the value of the call. Your command can
2955 called varname, containing the value of the call. Your command can
2958 contain shell wildcards, pipes, etc.
2956 contain shell wildcards, pipes, etc.
2959
2957
2960 The '=' sign in the syntax is mandatory, and the variable name you
2958 The '=' sign in the syntax is mandatory, and the variable name you
2961 supply must follow Python's standard conventions for valid names.
2959 supply must follow Python's standard conventions for valid names.
2962
2960
2963 (A special format without variable name exists for internal use)
2961 (A special format without variable name exists for internal use)
2964
2962
2965 Options:
2963 Options:
2966
2964
2967 -l: list output. Split the output on newlines into a list before
2965 -l: list output. Split the output on newlines into a list before
2968 assigning it to the given variable. By default the output is stored
2966 assigning it to the given variable. By default the output is stored
2969 as a single string.
2967 as a single string.
2970
2968
2971 -v: verbose. Print the contents of the variable.
2969 -v: verbose. Print the contents of the variable.
2972
2970
2973 In most cases you should not need to split as a list, because the
2971 In most cases you should not need to split as a list, because the
2974 returned value is a special type of string which can automatically
2972 returned value is a special type of string which can automatically
2975 provide its contents either as a list (split on newlines) or as a
2973 provide its contents either as a list (split on newlines) or as a
2976 space-separated string. These are convenient, respectively, either
2974 space-separated string. These are convenient, respectively, either
2977 for sequential processing or to be passed to a shell command.
2975 for sequential processing or to be passed to a shell command.
2978
2976
2979 For example:
2977 For example:
2980
2978
2981 # all-random
2979 # all-random
2982
2980
2983 # Capture into variable a
2981 # Capture into variable a
2984 In [1]: sc a=ls *py
2982 In [1]: sc a=ls *py
2985
2983
2986 # a is a string with embedded newlines
2984 # a is a string with embedded newlines
2987 In [2]: a
2985 In [2]: a
2988 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2986 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2989
2987
2990 # which can be seen as a list:
2988 # which can be seen as a list:
2991 In [3]: a.l
2989 In [3]: a.l
2992 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2990 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2993
2991
2994 # or as a whitespace-separated string:
2992 # or as a whitespace-separated string:
2995 In [4]: a.s
2993 In [4]: a.s
2996 Out[4]: 'setup.py win32_manual_post_install.py'
2994 Out[4]: 'setup.py win32_manual_post_install.py'
2997
2995
2998 # a.s is useful to pass as a single command line:
2996 # a.s is useful to pass as a single command line:
2999 In [5]: !wc -l $a.s
2997 In [5]: !wc -l $a.s
3000 146 setup.py
2998 146 setup.py
3001 130 win32_manual_post_install.py
2999 130 win32_manual_post_install.py
3002 276 total
3000 276 total
3003
3001
3004 # while the list form is useful to loop over:
3002 # while the list form is useful to loop over:
3005 In [6]: for f in a.l:
3003 In [6]: for f in a.l:
3006 ...: !wc -l $f
3004 ...: !wc -l $f
3007 ...:
3005 ...:
3008 146 setup.py
3006 146 setup.py
3009 130 win32_manual_post_install.py
3007 130 win32_manual_post_install.py
3010
3008
3011 Similiarly, the lists returned by the -l option are also special, in
3009 Similiarly, the lists returned by the -l option are also special, in
3012 the sense that you can equally invoke the .s attribute on them to
3010 the sense that you can equally invoke the .s attribute on them to
3013 automatically get a whitespace-separated string from their contents:
3011 automatically get a whitespace-separated string from their contents:
3014
3012
3015 In [7]: sc -l b=ls *py
3013 In [7]: sc -l b=ls *py
3016
3014
3017 In [8]: b
3015 In [8]: b
3018 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3016 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3019
3017
3020 In [9]: b.s
3018 In [9]: b.s
3021 Out[9]: 'setup.py win32_manual_post_install.py'
3019 Out[9]: 'setup.py win32_manual_post_install.py'
3022
3020
3023 In summary, both the lists and strings used for ouptut capture have
3021 In summary, both the lists and strings used for ouptut capture have
3024 the following special attributes:
3022 the following special attributes:
3025
3023
3026 .l (or .list) : value as list.
3024 .l (or .list) : value as list.
3027 .n (or .nlstr): value as newline-separated string.
3025 .n (or .nlstr): value as newline-separated string.
3028 .s (or .spstr): value as space-separated string.
3026 .s (or .spstr): value as space-separated string.
3029 """
3027 """
3030
3028
3031 opts,args = self.parse_options(parameter_s,'lv')
3029 opts,args = self.parse_options(parameter_s,'lv')
3032 # Try to get a variable name and command to run
3030 # Try to get a variable name and command to run
3033 try:
3031 try:
3034 # the variable name must be obtained from the parse_options
3032 # the variable name must be obtained from the parse_options
3035 # output, which uses shlex.split to strip options out.
3033 # output, which uses shlex.split to strip options out.
3036 var,_ = args.split('=',1)
3034 var,_ = args.split('=',1)
3037 var = var.strip()
3035 var = var.strip()
3038 # But the the command has to be extracted from the original input
3036 # But the the command has to be extracted from the original input
3039 # parameter_s, not on what parse_options returns, to avoid the
3037 # parameter_s, not on what parse_options returns, to avoid the
3040 # quote stripping which shlex.split performs on it.
3038 # quote stripping which shlex.split performs on it.
3041 _,cmd = parameter_s.split('=',1)
3039 _,cmd = parameter_s.split('=',1)
3042 except ValueError:
3040 except ValueError:
3043 var,cmd = '',''
3041 var,cmd = '',''
3044 # If all looks ok, proceed
3042 # If all looks ok, proceed
3045 split = 'l' in opts
3043 split = 'l' in opts
3046 out = self.shell.getoutput(cmd, split=split)
3044 out = self.shell.getoutput(cmd, split=split)
3047 if opts.has_key('v'):
3045 if opts.has_key('v'):
3048 print '%s ==\n%s' % (var,pformat(out))
3046 print '%s ==\n%s' % (var,pformat(out))
3049 if var:
3047 if var:
3050 self.shell.user_ns.update({var:out})
3048 self.shell.user_ns.update({var:out})
3051 else:
3049 else:
3052 return out
3050 return out
3053
3051
3054 def magic_sx(self, parameter_s=''):
3052 def magic_sx(self, parameter_s=''):
3055 """Shell execute - run a shell command and capture its output.
3053 """Shell execute - run a shell command and capture its output.
3056
3054
3057 %sx command
3055 %sx command
3058
3056
3059 IPython will run the given command using commands.getoutput(), and
3057 IPython will run the given command using commands.getoutput(), and
3060 return the result formatted as a list (split on '\\n'). Since the
3058 return the result formatted as a list (split on '\\n'). Since the
3061 output is _returned_, it will be stored in ipython's regular output
3059 output is _returned_, it will be stored in ipython's regular output
3062 cache Out[N] and in the '_N' automatic variables.
3060 cache Out[N] and in the '_N' automatic variables.
3063
3061
3064 Notes:
3062 Notes:
3065
3063
3066 1) If an input line begins with '!!', then %sx is automatically
3064 1) If an input line begins with '!!', then %sx is automatically
3067 invoked. That is, while:
3065 invoked. That is, while:
3068 !ls
3066 !ls
3069 causes ipython to simply issue system('ls'), typing
3067 causes ipython to simply issue system('ls'), typing
3070 !!ls
3068 !!ls
3071 is a shorthand equivalent to:
3069 is a shorthand equivalent to:
3072 %sx ls
3070 %sx ls
3073
3071
3074 2) %sx differs from %sc in that %sx automatically splits into a list,
3072 2) %sx differs from %sc in that %sx automatically splits into a list,
3075 like '%sc -l'. The reason for this is to make it as easy as possible
3073 like '%sc -l'. The reason for this is to make it as easy as possible
3076 to process line-oriented shell output via further python commands.
3074 to process line-oriented shell output via further python commands.
3077 %sc is meant to provide much finer control, but requires more
3075 %sc is meant to provide much finer control, but requires more
3078 typing.
3076 typing.
3079
3077
3080 3) Just like %sc -l, this is a list with special attributes:
3078 3) Just like %sc -l, this is a list with special attributes:
3081
3079
3082 .l (or .list) : value as list.
3080 .l (or .list) : value as list.
3083 .n (or .nlstr): value as newline-separated string.
3081 .n (or .nlstr): value as newline-separated string.
3084 .s (or .spstr): value as whitespace-separated string.
3082 .s (or .spstr): value as whitespace-separated string.
3085
3083
3086 This is very useful when trying to use such lists as arguments to
3084 This is very useful when trying to use such lists as arguments to
3087 system commands."""
3085 system commands."""
3088
3086
3089 if parameter_s:
3087 if parameter_s:
3090 return self.shell.getoutput(parameter_s)
3088 return self.shell.getoutput(parameter_s)
3091
3089
3092
3090
3093 def magic_bookmark(self, parameter_s=''):
3091 def magic_bookmark(self, parameter_s=''):
3094 """Manage IPython's bookmark system.
3092 """Manage IPython's bookmark system.
3095
3093
3096 %bookmark <name> - set bookmark to current dir
3094 %bookmark <name> - set bookmark to current dir
3097 %bookmark <name> <dir> - set bookmark to <dir>
3095 %bookmark <name> <dir> - set bookmark to <dir>
3098 %bookmark -l - list all bookmarks
3096 %bookmark -l - list all bookmarks
3099 %bookmark -d <name> - remove bookmark
3097 %bookmark -d <name> - remove bookmark
3100 %bookmark -r - remove all bookmarks
3098 %bookmark -r - remove all bookmarks
3101
3099
3102 You can later on access a bookmarked folder with:
3100 You can later on access a bookmarked folder with:
3103 %cd -b <name>
3101 %cd -b <name>
3104 or simply '%cd <name>' if there is no directory called <name> AND
3102 or simply '%cd <name>' if there is no directory called <name> AND
3105 there is such a bookmark defined.
3103 there is such a bookmark defined.
3106
3104
3107 Your bookmarks persist through IPython sessions, but they are
3105 Your bookmarks persist through IPython sessions, but they are
3108 associated with each profile."""
3106 associated with each profile."""
3109
3107
3110 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3108 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3111 if len(args) > 2:
3109 if len(args) > 2:
3112 raise UsageError("%bookmark: too many arguments")
3110 raise UsageError("%bookmark: too many arguments")
3113
3111
3114 bkms = self.db.get('bookmarks',{})
3112 bkms = self.db.get('bookmarks',{})
3115
3113
3116 if opts.has_key('d'):
3114 if opts.has_key('d'):
3117 try:
3115 try:
3118 todel = args[0]
3116 todel = args[0]
3119 except IndexError:
3117 except IndexError:
3120 raise UsageError(
3118 raise UsageError(
3121 "%bookmark -d: must provide a bookmark to delete")
3119 "%bookmark -d: must provide a bookmark to delete")
3122 else:
3120 else:
3123 try:
3121 try:
3124 del bkms[todel]
3122 del bkms[todel]
3125 except KeyError:
3123 except KeyError:
3126 raise UsageError(
3124 raise UsageError(
3127 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3125 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3128
3126
3129 elif opts.has_key('r'):
3127 elif opts.has_key('r'):
3130 bkms = {}
3128 bkms = {}
3131 elif opts.has_key('l'):
3129 elif opts.has_key('l'):
3132 bks = bkms.keys()
3130 bks = bkms.keys()
3133 bks.sort()
3131 bks.sort()
3134 if bks:
3132 if bks:
3135 size = max(map(len,bks))
3133 size = max(map(len,bks))
3136 else:
3134 else:
3137 size = 0
3135 size = 0
3138 fmt = '%-'+str(size)+'s -> %s'
3136 fmt = '%-'+str(size)+'s -> %s'
3139 print 'Current bookmarks:'
3137 print 'Current bookmarks:'
3140 for bk in bks:
3138 for bk in bks:
3141 print fmt % (bk,bkms[bk])
3139 print fmt % (bk,bkms[bk])
3142 else:
3140 else:
3143 if not args:
3141 if not args:
3144 raise UsageError("%bookmark: You must specify the bookmark name")
3142 raise UsageError("%bookmark: You must specify the bookmark name")
3145 elif len(args)==1:
3143 elif len(args)==1:
3146 bkms[args[0]] = os.getcwd()
3144 bkms[args[0]] = os.getcwd()
3147 elif len(args)==2:
3145 elif len(args)==2:
3148 bkms[args[0]] = args[1]
3146 bkms[args[0]] = args[1]
3149 self.db['bookmarks'] = bkms
3147 self.db['bookmarks'] = bkms
3150
3148
3151 def magic_pycat(self, parameter_s=''):
3149 def magic_pycat(self, parameter_s=''):
3152 """Show a syntax-highlighted file through a pager.
3150 """Show a syntax-highlighted file through a pager.
3153
3151
3154 This magic is similar to the cat utility, but it will assume the file
3152 This magic is similar to the cat utility, but it will assume the file
3155 to be Python source and will show it with syntax highlighting. """
3153 to be Python source and will show it with syntax highlighting. """
3156
3154
3157 try:
3155 try:
3158 filename = get_py_filename(parameter_s)
3156 filename = get_py_filename(parameter_s)
3159 cont = file_read(filename)
3157 cont = file_read(filename)
3160 except IOError:
3158 except IOError:
3161 try:
3159 try:
3162 cont = eval(parameter_s,self.user_ns)
3160 cont = eval(parameter_s,self.user_ns)
3163 except NameError:
3161 except NameError:
3164 cont = None
3162 cont = None
3165 if cont is None:
3163 if cont is None:
3166 print "Error: no such file or variable"
3164 print "Error: no such file or variable"
3167 return
3165 return
3168
3166
3169 page.page(self.shell.pycolorize(cont))
3167 page.page(self.shell.pycolorize(cont))
3170
3168
3171 def _rerun_pasted(self):
3169 def _rerun_pasted(self):
3172 """ Rerun a previously pasted command.
3170 """ Rerun a previously pasted command.
3173 """
3171 """
3174 b = self.user_ns.get('pasted_block', None)
3172 b = self.user_ns.get('pasted_block', None)
3175 if b is None:
3173 if b is None:
3176 raise UsageError('No previous pasted block available')
3174 raise UsageError('No previous pasted block available')
3177 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3175 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3178 exec b in self.user_ns
3176 exec b in self.user_ns
3179
3177
3180 def _get_pasted_lines(self, sentinel):
3178 def _get_pasted_lines(self, sentinel):
3181 """ Yield pasted lines until the user enters the given sentinel value.
3179 """ Yield pasted lines until the user enters the given sentinel value.
3182 """
3180 """
3183 from IPython.core import interactiveshell
3181 from IPython.core import interactiveshell
3184 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3182 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3185 while True:
3183 while True:
3186 l = interactiveshell.raw_input_original(':')
3184 l = interactiveshell.raw_input_original(':')
3187 if l == sentinel:
3185 if l == sentinel:
3188 return
3186 return
3189 else:
3187 else:
3190 yield l
3188 yield l
3191
3189
3192 def _strip_pasted_lines_for_code(self, raw_lines):
3190 def _strip_pasted_lines_for_code(self, raw_lines):
3193 """ Strip non-code parts of a sequence of lines to return a block of
3191 """ Strip non-code parts of a sequence of lines to return a block of
3194 code.
3192 code.
3195 """
3193 """
3196 # Regular expressions that declare text we strip from the input:
3194 # Regular expressions that declare text we strip from the input:
3197 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3195 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3198 r'^\s*(\s?>)+', # Python input prompt
3196 r'^\s*(\s?>)+', # Python input prompt
3199 r'^\s*\.{3,}', # Continuation prompts
3197 r'^\s*\.{3,}', # Continuation prompts
3200 r'^\++',
3198 r'^\++',
3201 ]
3199 ]
3202
3200
3203 strip_from_start = map(re.compile,strip_re)
3201 strip_from_start = map(re.compile,strip_re)
3204
3202
3205 lines = []
3203 lines = []
3206 for l in raw_lines:
3204 for l in raw_lines:
3207 for pat in strip_from_start:
3205 for pat in strip_from_start:
3208 l = pat.sub('',l)
3206 l = pat.sub('',l)
3209 lines.append(l)
3207 lines.append(l)
3210
3208
3211 block = "\n".join(lines) + '\n'
3209 block = "\n".join(lines) + '\n'
3212 #print "block:\n",block
3210 #print "block:\n",block
3213 return block
3211 return block
3214
3212
3215 def _execute_block(self, block, par):
3213 def _execute_block(self, block, par):
3216 """ Execute a block, or store it in a variable, per the user's request.
3214 """ Execute a block, or store it in a variable, per the user's request.
3217 """
3215 """
3218 if not par:
3216 if not par:
3219 b = textwrap.dedent(block)
3217 b = textwrap.dedent(block)
3220 self.user_ns['pasted_block'] = b
3218 self.user_ns['pasted_block'] = b
3221 exec b in self.user_ns
3219 exec b in self.user_ns
3222 else:
3220 else:
3223 self.user_ns[par] = SList(block.splitlines())
3221 self.user_ns[par] = SList(block.splitlines())
3224 print "Block assigned to '%s'" % par
3222 print "Block assigned to '%s'" % par
3225
3223
3226 def magic_quickref(self,arg):
3224 def magic_quickref(self,arg):
3227 """ Show a quick reference sheet """
3225 """ Show a quick reference sheet """
3228 import IPython.core.usage
3226 import IPython.core.usage
3229 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3227 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3230
3228
3231 page.page(qr)
3229 page.page(qr)
3232
3230
3233 def magic_doctest_mode(self,parameter_s=''):
3231 def magic_doctest_mode(self,parameter_s=''):
3234 """Toggle doctest mode on and off.
3232 """Toggle doctest mode on and off.
3235
3233
3236 This mode is intended to make IPython behave as much as possible like a
3234 This mode is intended to make IPython behave as much as possible like a
3237 plain Python shell, from the perspective of how its prompts, exceptions
3235 plain Python shell, from the perspective of how its prompts, exceptions
3238 and output look. This makes it easy to copy and paste parts of a
3236 and output look. This makes it easy to copy and paste parts of a
3239 session into doctests. It does so by:
3237 session into doctests. It does so by:
3240
3238
3241 - Changing the prompts to the classic ``>>>`` ones.
3239 - Changing the prompts to the classic ``>>>`` ones.
3242 - Changing the exception reporting mode to 'Plain'.
3240 - Changing the exception reporting mode to 'Plain'.
3243 - Disabling pretty-printing of output.
3241 - Disabling pretty-printing of output.
3244
3242
3245 Note that IPython also supports the pasting of code snippets that have
3243 Note that IPython also supports the pasting of code snippets that have
3246 leading '>>>' and '...' prompts in them. This means that you can paste
3244 leading '>>>' and '...' prompts in them. This means that you can paste
3247 doctests from files or docstrings (even if they have leading
3245 doctests from files or docstrings (even if they have leading
3248 whitespace), and the code will execute correctly. You can then use
3246 whitespace), and the code will execute correctly. You can then use
3249 '%history -t' to see the translated history; this will give you the
3247 '%history -t' to see the translated history; this will give you the
3250 input after removal of all the leading prompts and whitespace, which
3248 input after removal of all the leading prompts and whitespace, which
3251 can be pasted back into an editor.
3249 can be pasted back into an editor.
3252
3250
3253 With these features, you can switch into this mode easily whenever you
3251 With these features, you can switch into this mode easily whenever you
3254 need to do testing and changes to doctests, without having to leave
3252 need to do testing and changes to doctests, without having to leave
3255 your existing IPython session.
3253 your existing IPython session.
3256 """
3254 """
3257
3255
3258 from IPython.utils.ipstruct import Struct
3256 from IPython.utils.ipstruct import Struct
3259
3257
3260 # Shorthands
3258 # Shorthands
3261 shell = self.shell
3259 shell = self.shell
3262 oc = shell.displayhook
3260 oc = shell.displayhook
3263 meta = shell.meta
3261 meta = shell.meta
3264 disp_formatter = self.shell.display_formatter
3262 disp_formatter = self.shell.display_formatter
3265 ptformatter = disp_formatter.formatters['text/plain']
3263 ptformatter = disp_formatter.formatters['text/plain']
3266 # dstore is a data store kept in the instance metadata bag to track any
3264 # dstore is a data store kept in the instance metadata bag to track any
3267 # changes we make, so we can undo them later.
3265 # changes we make, so we can undo them later.
3268 dstore = meta.setdefault('doctest_mode',Struct())
3266 dstore = meta.setdefault('doctest_mode',Struct())
3269 save_dstore = dstore.setdefault
3267 save_dstore = dstore.setdefault
3270
3268
3271 # save a few values we'll need to recover later
3269 # save a few values we'll need to recover later
3272 mode = save_dstore('mode',False)
3270 mode = save_dstore('mode',False)
3273 save_dstore('rc_pprint',ptformatter.pprint)
3271 save_dstore('rc_pprint',ptformatter.pprint)
3274 save_dstore('xmode',shell.InteractiveTB.mode)
3272 save_dstore('xmode',shell.InteractiveTB.mode)
3275 save_dstore('rc_separate_out',shell.separate_out)
3273 save_dstore('rc_separate_out',shell.separate_out)
3276 save_dstore('rc_separate_out2',shell.separate_out2)
3274 save_dstore('rc_separate_out2',shell.separate_out2)
3277 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3275 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3278 save_dstore('rc_separate_in',shell.separate_in)
3276 save_dstore('rc_separate_in',shell.separate_in)
3279 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
3277 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
3280
3278
3281 if mode == False:
3279 if mode == False:
3282 # turn on
3280 # turn on
3283 oc.prompt1.p_template = '>>> '
3281 oc.prompt1.p_template = '>>> '
3284 oc.prompt2.p_template = '... '
3282 oc.prompt2.p_template = '... '
3285 oc.prompt_out.p_template = ''
3283 oc.prompt_out.p_template = ''
3286
3284
3287 # Prompt separators like plain python
3285 # Prompt separators like plain python
3288 oc.input_sep = oc.prompt1.sep = ''
3286 oc.input_sep = oc.prompt1.sep = ''
3289 oc.output_sep = ''
3287 oc.output_sep = ''
3290 oc.output_sep2 = ''
3288 oc.output_sep2 = ''
3291
3289
3292 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3290 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3293 oc.prompt_out.pad_left = False
3291 oc.prompt_out.pad_left = False
3294
3292
3295 ptformatter.pprint = False
3293 ptformatter.pprint = False
3296 disp_formatter.plain_text_only = True
3294 disp_formatter.plain_text_only = True
3297
3295
3298 shell.magic_xmode('Plain')
3296 shell.magic_xmode('Plain')
3299 else:
3297 else:
3300 # turn off
3298 # turn off
3301 oc.prompt1.p_template = shell.prompt_in1
3299 oc.prompt1.p_template = shell.prompt_in1
3302 oc.prompt2.p_template = shell.prompt_in2
3300 oc.prompt2.p_template = shell.prompt_in2
3303 oc.prompt_out.p_template = shell.prompt_out
3301 oc.prompt_out.p_template = shell.prompt_out
3304
3302
3305 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3303 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3306
3304
3307 oc.output_sep = dstore.rc_separate_out
3305 oc.output_sep = dstore.rc_separate_out
3308 oc.output_sep2 = dstore.rc_separate_out2
3306 oc.output_sep2 = dstore.rc_separate_out2
3309
3307
3310 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3308 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3311 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3309 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3312
3310
3313 ptformatter.pprint = dstore.rc_pprint
3311 ptformatter.pprint = dstore.rc_pprint
3314 disp_formatter.plain_text_only = dstore.rc_plain_text_only
3312 disp_formatter.plain_text_only = dstore.rc_plain_text_only
3315
3313
3316 shell.magic_xmode(dstore.xmode)
3314 shell.magic_xmode(dstore.xmode)
3317
3315
3318 # Store new mode and inform
3316 # Store new mode and inform
3319 dstore.mode = bool(1-int(mode))
3317 dstore.mode = bool(1-int(mode))
3320 mode_label = ['OFF','ON'][dstore.mode]
3318 mode_label = ['OFF','ON'][dstore.mode]
3321 print 'Doctest mode is:', mode_label
3319 print 'Doctest mode is:', mode_label
3322
3320
3323 def magic_gui(self, parameter_s=''):
3321 def magic_gui(self, parameter_s=''):
3324 """Enable or disable IPython GUI event loop integration.
3322 """Enable or disable IPython GUI event loop integration.
3325
3323
3326 %gui [GUINAME]
3324 %gui [GUINAME]
3327
3325
3328 This magic replaces IPython's threaded shells that were activated
3326 This magic replaces IPython's threaded shells that were activated
3329 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3327 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3330 can now be enabled, disabled and changed at runtime and keyboard
3328 can now be enabled, disabled and changed at runtime and keyboard
3331 interrupts should work without any problems. The following toolkits
3329 interrupts should work without any problems. The following toolkits
3332 are supported: wxPython, PyQt4, PyGTK, and Tk::
3330 are supported: wxPython, PyQt4, PyGTK, and Tk::
3333
3331
3334 %gui wx # enable wxPython event loop integration
3332 %gui wx # enable wxPython event loop integration
3335 %gui qt4|qt # enable PyQt4 event loop integration
3333 %gui qt4|qt # enable PyQt4 event loop integration
3336 %gui gtk # enable PyGTK event loop integration
3334 %gui gtk # enable PyGTK event loop integration
3337 %gui tk # enable Tk event loop integration
3335 %gui tk # enable Tk event loop integration
3338 %gui # disable all event loop integration
3336 %gui # disable all event loop integration
3339
3337
3340 WARNING: after any of these has been called you can simply create
3338 WARNING: after any of these has been called you can simply create
3341 an application object, but DO NOT start the event loop yourself, as
3339 an application object, but DO NOT start the event loop yourself, as
3342 we have already handled that.
3340 we have already handled that.
3343 """
3341 """
3344 from IPython.lib.inputhook import enable_gui
3342 from IPython.lib.inputhook import enable_gui
3345 opts, arg = self.parse_options(parameter_s, '')
3343 opts, arg = self.parse_options(parameter_s, '')
3346 if arg=='': arg = None
3344 if arg=='': arg = None
3347 return enable_gui(arg)
3345 return enable_gui(arg)
3348
3346
3349 def magic_load_ext(self, module_str):
3347 def magic_load_ext(self, module_str):
3350 """Load an IPython extension by its module name."""
3348 """Load an IPython extension by its module name."""
3351 return self.extension_manager.load_extension(module_str)
3349 return self.extension_manager.load_extension(module_str)
3352
3350
3353 def magic_unload_ext(self, module_str):
3351 def magic_unload_ext(self, module_str):
3354 """Unload an IPython extension by its module name."""
3352 """Unload an IPython extension by its module name."""
3355 self.extension_manager.unload_extension(module_str)
3353 self.extension_manager.unload_extension(module_str)
3356
3354
3357 def magic_reload_ext(self, module_str):
3355 def magic_reload_ext(self, module_str):
3358 """Reload an IPython extension by its module name."""
3356 """Reload an IPython extension by its module name."""
3359 self.extension_manager.reload_extension(module_str)
3357 self.extension_manager.reload_extension(module_str)
3360
3358
3361 @skip_doctest
3359 @skip_doctest
3362 def magic_install_profiles(self, s):
3360 def magic_install_profiles(self, s):
3363 """Install the default IPython profiles into the .ipython dir.
3361 """Install the default IPython profiles into the .ipython dir.
3364
3362
3365 If the default profiles have already been installed, they will not
3363 If the default profiles have already been installed, they will not
3366 be overwritten. You can force overwriting them by using the ``-o``
3364 be overwritten. You can force overwriting them by using the ``-o``
3367 option::
3365 option::
3368
3366
3369 In [1]: %install_profiles -o
3367 In [1]: %install_profiles -o
3370 """
3368 """
3371 if '-o' in s:
3369 if '-o' in s:
3372 overwrite = True
3370 overwrite = True
3373 else:
3371 else:
3374 overwrite = False
3372 overwrite = False
3375 from IPython.config import profile
3373 from IPython.config import profile
3376 profile_dir = os.path.split(profile.__file__)[0]
3374 profile_dir = os.path.dirname(profile.__file__)
3377 ipython_dir = self.ipython_dir
3375 ipython_dir = self.ipython_dir
3378 files = os.listdir(profile_dir)
3376 print "Installing profiles to: %s [overwrite=%s]"(ipython_dir,overwrite)
3379
3377 for src in os.listdir(profile_dir):
3380 to_install = []
3378 if src.startswith('profile_'):
3381 for f in files:
3379 name = src.replace('profile_', '')
3382 if f.startswith('ipython_config'):
3380 print " %s"%name
3383 src = os.path.join(profile_dir, f)
3381 pd = ProfileDir.create_profile_dir_by_name(ipython_dir, name)
3384 dst = os.path.join(ipython_dir, f)
3382 pd.copy_config_file('ipython_config.py', path=src,
3385 if (not os.path.isfile(dst)) or overwrite:
3383 overwrite=overwrite)
3386 to_install.append((f, src, dst))
3387 if len(to_install)>0:
3388 print "Installing profiles to: ", ipython_dir
3389 for (f, src, dst) in to_install:
3390 shutil.copy(src, dst)
3391 print " %s" % f
3392
3384
3393 @skip_doctest
3385 @skip_doctest
3394 def magic_install_default_config(self, s):
3386 def magic_install_default_config(self, s):
3395 """Install IPython's default config file into the .ipython dir.
3387 """Install IPython's default config file into the .ipython dir.
3396
3388
3397 If the default config file (:file:`ipython_config.py`) is already
3389 If the default config file (:file:`ipython_config.py`) is already
3398 installed, it will not be overwritten. You can force overwriting
3390 installed, it will not be overwritten. You can force overwriting
3399 by using the ``-o`` option::
3391 by using the ``-o`` option::
3400
3392
3401 In [1]: %install_default_config
3393 In [1]: %install_default_config
3402 """
3394 """
3403 if '-o' in s:
3395 if '-o' in s:
3404 overwrite = True
3396 overwrite = True
3405 else:
3397 else:
3406 overwrite = False
3398 overwrite = False
3407 from IPython.config import default
3399 pd = self.shell.profile_dir
3408 config_dir = os.path.split(default.__file__)[0]
3400 print "Installing default config file in: %s" % pd.location
3409 ipython_dir = self.ipython_dir
3401 pd.copy_config_file('ipython_config.py', overwrite=overwrite)
3410 default_config_file_name = 'ipython_config.py'
3411 src = os.path.join(config_dir, default_config_file_name)
3412 dst = os.path.join(ipython_dir, default_config_file_name)
3413 if (not os.path.isfile(dst)) or overwrite:
3414 shutil.copy(src, dst)
3415 print "Installing default config file: %s" % dst
3416
3402
3417 # Pylab support: simple wrappers that activate pylab, load gui input
3403 # Pylab support: simple wrappers that activate pylab, load gui input
3418 # handling and modify slightly %run
3404 # handling and modify slightly %run
3419
3405
3420 @skip_doctest
3406 @skip_doctest
3421 def _pylab_magic_run(self, parameter_s=''):
3407 def _pylab_magic_run(self, parameter_s=''):
3422 Magic.magic_run(self, parameter_s,
3408 Magic.magic_run(self, parameter_s,
3423 runner=mpl_runner(self.shell.safe_execfile))
3409 runner=mpl_runner(self.shell.safe_execfile))
3424
3410
3425 _pylab_magic_run.__doc__ = magic_run.__doc__
3411 _pylab_magic_run.__doc__ = magic_run.__doc__
3426
3412
3427 @skip_doctest
3413 @skip_doctest
3428 def magic_pylab(self, s):
3414 def magic_pylab(self, s):
3429 """Load numpy and matplotlib to work interactively.
3415 """Load numpy and matplotlib to work interactively.
3430
3416
3431 %pylab [GUINAME]
3417 %pylab [GUINAME]
3432
3418
3433 This function lets you activate pylab (matplotlib, numpy and
3419 This function lets you activate pylab (matplotlib, numpy and
3434 interactive support) at any point during an IPython session.
3420 interactive support) at any point during an IPython session.
3435
3421
3436 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3422 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3437 pylab and mlab, as well as all names from numpy and pylab.
3423 pylab and mlab, as well as all names from numpy and pylab.
3438
3424
3439 Parameters
3425 Parameters
3440 ----------
3426 ----------
3441 guiname : optional
3427 guiname : optional
3442 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk', 'osx' or
3428 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk', 'osx' or
3443 'tk'). If given, the corresponding Matplotlib backend is used,
3429 'tk'). If given, the corresponding Matplotlib backend is used,
3444 otherwise matplotlib's default (which you can override in your
3430 otherwise matplotlib's default (which you can override in your
3445 matplotlib config file) is used.
3431 matplotlib config file) is used.
3446
3432
3447 Examples
3433 Examples
3448 --------
3434 --------
3449 In this case, where the MPL default is TkAgg:
3435 In this case, where the MPL default is TkAgg:
3450 In [2]: %pylab
3436 In [2]: %pylab
3451
3437
3452 Welcome to pylab, a matplotlib-based Python environment.
3438 Welcome to pylab, a matplotlib-based Python environment.
3453 Backend in use: TkAgg
3439 Backend in use: TkAgg
3454 For more information, type 'help(pylab)'.
3440 For more information, type 'help(pylab)'.
3455
3441
3456 But you can explicitly request a different backend:
3442 But you can explicitly request a different backend:
3457 In [3]: %pylab qt
3443 In [3]: %pylab qt
3458
3444
3459 Welcome to pylab, a matplotlib-based Python environment.
3445 Welcome to pylab, a matplotlib-based Python environment.
3460 Backend in use: Qt4Agg
3446 Backend in use: Qt4Agg
3461 For more information, type 'help(pylab)'.
3447 For more information, type 'help(pylab)'.
3462 """
3448 """
3463 self.shell.enable_pylab(s)
3449 self.shell.enable_pylab(s)
3464
3450
3465 def magic_tb(self, s):
3451 def magic_tb(self, s):
3466 """Print the last traceback with the currently active exception mode.
3452 """Print the last traceback with the currently active exception mode.
3467
3453
3468 See %xmode for changing exception reporting modes."""
3454 See %xmode for changing exception reporting modes."""
3469 self.shell.showtraceback()
3455 self.shell.showtraceback()
3470
3456
3471 @skip_doctest
3457 @skip_doctest
3472 def magic_precision(self, s=''):
3458 def magic_precision(self, s=''):
3473 """Set floating point precision for pretty printing.
3459 """Set floating point precision for pretty printing.
3474
3460
3475 Can set either integer precision or a format string.
3461 Can set either integer precision or a format string.
3476
3462
3477 If numpy has been imported and precision is an int,
3463 If numpy has been imported and precision is an int,
3478 numpy display precision will also be set, via ``numpy.set_printoptions``.
3464 numpy display precision will also be set, via ``numpy.set_printoptions``.
3479
3465
3480 If no argument is given, defaults will be restored.
3466 If no argument is given, defaults will be restored.
3481
3467
3482 Examples
3468 Examples
3483 --------
3469 --------
3484 ::
3470 ::
3485
3471
3486 In [1]: from math import pi
3472 In [1]: from math import pi
3487
3473
3488 In [2]: %precision 3
3474 In [2]: %precision 3
3489 Out[2]: '%.3f'
3475 Out[2]: '%.3f'
3490
3476
3491 In [3]: pi
3477 In [3]: pi
3492 Out[3]: 3.142
3478 Out[3]: 3.142
3493
3479
3494 In [4]: %precision %i
3480 In [4]: %precision %i
3495 Out[4]: '%i'
3481 Out[4]: '%i'
3496
3482
3497 In [5]: pi
3483 In [5]: pi
3498 Out[5]: 3
3484 Out[5]: 3
3499
3485
3500 In [6]: %precision %e
3486 In [6]: %precision %e
3501 Out[6]: '%e'
3487 Out[6]: '%e'
3502
3488
3503 In [7]: pi**10
3489 In [7]: pi**10
3504 Out[7]: 9.364805e+04
3490 Out[7]: 9.364805e+04
3505
3491
3506 In [8]: %precision
3492 In [8]: %precision
3507 Out[8]: '%r'
3493 Out[8]: '%r'
3508
3494
3509 In [9]: pi**10
3495 In [9]: pi**10
3510 Out[9]: 93648.047476082982
3496 Out[9]: 93648.047476082982
3511
3497
3512 """
3498 """
3513
3499
3514 ptformatter = self.shell.display_formatter.formatters['text/plain']
3500 ptformatter = self.shell.display_formatter.formatters['text/plain']
3515 ptformatter.float_precision = s
3501 ptformatter.float_precision = s
3516 return ptformatter.float_format
3502 return ptformatter.float_format
3517
3503
3518 # end Magic
3504 # end Magic
@@ -1,564 +1,590
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Subclass of InteractiveShell for terminal based frontends."""
2 """Subclass of InteractiveShell for terminal based frontends."""
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-2010 The IPython Development Team
7 # Copyright (C) 2008-2010 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 import __builtin__
17 import __builtin__
18 import bdb
18 import bdb
19 from contextlib import nested
19 from contextlib import nested
20 import os
20 import os
21 import re
21 import re
22 import sys
22 import sys
23
23
24 from IPython.core.error import TryNext
24 from IPython.core.error import TryNext
25 from IPython.core.usage import interactive_usage, default_banner
25 from IPython.core.usage import interactive_usage, default_banner
26 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
26 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
27 from IPython.lib.inputhook import enable_gui
27 from IPython.lib.inputhook import enable_gui
28 from IPython.lib.pylabtools import pylab_activate
28 from IPython.lib.pylabtools import pylab_activate
29 from IPython.testing.skipdoctest import skip_doctest
29 from IPython.testing.skipdoctest import skip_doctest
30 from IPython.utils.terminal import toggle_set_term_title, set_term_title
30 from IPython.utils.terminal import toggle_set_term_title, set_term_title
31 from IPython.utils.process import abbrev_cwd
31 from IPython.utils.process import abbrev_cwd
32 from IPython.utils.warn import warn
32 from IPython.utils.warn import warn
33 from IPython.utils.text import num_ini_spaces
33 from IPython.utils.text import num_ini_spaces
34 from IPython.utils.traitlets import Int, Str, CBool, Unicode
34 from IPython.utils.traitlets import Int, Str, CBool, Unicode
35
35
36 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
37 # Utilities
37 # Utilities
38 #-----------------------------------------------------------------------------
38 #-----------------------------------------------------------------------------
39
39
40 def get_default_editor():
40 def get_default_editor():
41 try:
41 try:
42 ed = os.environ['EDITOR']
42 ed = os.environ['EDITOR']
43 except KeyError:
43 except KeyError:
44 if os.name == 'posix':
44 if os.name == 'posix':
45 ed = 'vi' # the only one guaranteed to be there!
45 ed = 'vi' # the only one guaranteed to be there!
46 else:
46 else:
47 ed = 'notepad' # same in Windows!
47 ed = 'notepad' # same in Windows!
48 return ed
48 return ed
49
49
50
50
51 # store the builtin raw_input globally, and use this always, in case user code
51 # store the builtin raw_input globally, and use this always, in case user code
52 # overwrites it (like wx.py.PyShell does)
52 # overwrites it (like wx.py.PyShell does)
53 raw_input_original = raw_input
53 raw_input_original = raw_input
54
54
55 #-----------------------------------------------------------------------------
55 #-----------------------------------------------------------------------------
56 # Main class
56 # Main class
57 #-----------------------------------------------------------------------------
57 #-----------------------------------------------------------------------------
58
58
59 class TerminalInteractiveShell(InteractiveShell):
59 class TerminalInteractiveShell(InteractiveShell):
60
60
61 autoedit_syntax = CBool(False, config=True)
61 autoedit_syntax = CBool(False, config=True,
62 help="auto editing of files with syntax errors.")
62 banner = Unicode('')
63 banner = Unicode('')
63 banner1 = Unicode(default_banner, config=True)
64 banner1 = Unicode(default_banner, config=True,
64 banner2 = Unicode('', config=True)
65 help="""The part of the banner to be printed before the profile"""
65 confirm_exit = CBool(True, config=True)
66 )
67 banner2 = Unicode('', config=True,
68 help="""The part of the banner to be printed after the profile"""
69 )
70 confirm_exit = CBool(True, config=True,
71 help="""
72 Set to confirm when you try to exit IPython with an EOF (Control-D
73 in Unix, Control-Z/Enter in Windows). By typing 'exit', 'quit' or
74 '%%Exit', you can force a direct exit without any confirmation.""",
75 )
66 # This display_banner only controls whether or not self.show_banner()
76 # This display_banner only controls whether or not self.show_banner()
67 # is called when mainloop/interact are called. The default is False
77 # is called when mainloop/interact are called. The default is False
68 # because for the terminal based application, the banner behavior
78 # because for the terminal based application, the banner behavior
69 # is controlled by Global.display_banner, which IPythonApp looks at
79 # is controlled by Global.display_banner, which IPythonApp looks at
70 # to determine if *it* should call show_banner() by hand or not.
80 # to determine if *it* should call show_banner() by hand or not.
71 display_banner = CBool(False) # This isn't configurable!
81 display_banner = CBool(False) # This isn't configurable!
72 embedded = CBool(False)
82 embedded = CBool(False)
73 embedded_active = CBool(False)
83 embedded_active = CBool(False)
74 editor = Unicode(get_default_editor(), config=True)
84 editor = Unicode(get_default_editor(), config=True,
75 pager = Unicode('less', config=True)
85 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
76
86 )
77 screen_length = Int(0, config=True)
87 pager = Unicode('less', config=True,
78 term_title = CBool(False, config=True)
88 help="The shell program to be used for paging.")
79
89
80 def __init__(self, config=None, ipython_dir=None, user_ns=None,
90 screen_length = Int(0, config=True,
91 help=
92 """Number of lines of your screen, used to control printing of very
93 long strings. Strings longer than this number of lines will be sent
94 through a pager instead of directly printed. The default value for
95 this is 0, which means IPython will auto-detect your screen size every
96 time it needs to print certain potentially long strings (this doesn't
97 change the behavior of the 'print' keyword, it's only triggered
98 internally). If for some reason this isn't working well (it needs
99 curses support), specify it yourself. Otherwise don't change the
100 default.""",
101 )
102 term_title = CBool(False, config=True,
103 help="Enable auto setting the terminal title."
104 )
105
106 def __init__(self, config=None, ipython_dir=None, profile_dir=None, user_ns=None,
81 user_global_ns=None, custom_exceptions=((),None),
107 user_global_ns=None, custom_exceptions=((),None),
82 usage=None, banner1=None, banner2=None,
108 usage=None, banner1=None, banner2=None,
83 display_banner=None):
109 display_banner=None):
84
110
85 super(TerminalInteractiveShell, self).__init__(
111 super(TerminalInteractiveShell, self).__init__(
86 config=config, ipython_dir=ipython_dir, user_ns=user_ns,
112 config=config, profile_dir=profile_dir, user_ns=user_ns,
87 user_global_ns=user_global_ns, custom_exceptions=custom_exceptions
113 user_global_ns=user_global_ns, custom_exceptions=custom_exceptions
88 )
114 )
89 # use os.system instead of utils.process.system by default, except on Windows
115 # use os.system instead of utils.process.system by default, except on Windows
90 if os.name == 'nt':
116 if os.name == 'nt':
91 self.system = self.system_piped
117 self.system = self.system_piped
92 else:
118 else:
93 self.system = self.system_raw
119 self.system = self.system_raw
94
120
95 self.init_term_title()
121 self.init_term_title()
96 self.init_usage(usage)
122 self.init_usage(usage)
97 self.init_banner(banner1, banner2, display_banner)
123 self.init_banner(banner1, banner2, display_banner)
98
124
99 #-------------------------------------------------------------------------
125 #-------------------------------------------------------------------------
100 # Things related to the terminal
126 # Things related to the terminal
101 #-------------------------------------------------------------------------
127 #-------------------------------------------------------------------------
102
128
103 @property
129 @property
104 def usable_screen_length(self):
130 def usable_screen_length(self):
105 if self.screen_length == 0:
131 if self.screen_length == 0:
106 return 0
132 return 0
107 else:
133 else:
108 num_lines_bot = self.separate_in.count('\n')+1
134 num_lines_bot = self.separate_in.count('\n')+1
109 return self.screen_length - num_lines_bot
135 return self.screen_length - num_lines_bot
110
136
111 def init_term_title(self):
137 def init_term_title(self):
112 # Enable or disable the terminal title.
138 # Enable or disable the terminal title.
113 if self.term_title:
139 if self.term_title:
114 toggle_set_term_title(True)
140 toggle_set_term_title(True)
115 set_term_title('IPython: ' + abbrev_cwd())
141 set_term_title('IPython: ' + abbrev_cwd())
116 else:
142 else:
117 toggle_set_term_title(False)
143 toggle_set_term_title(False)
118
144
119 #-------------------------------------------------------------------------
145 #-------------------------------------------------------------------------
120 # Things related to aliases
146 # Things related to aliases
121 #-------------------------------------------------------------------------
147 #-------------------------------------------------------------------------
122
148
123 def init_alias(self):
149 def init_alias(self):
124 # The parent class defines aliases that can be safely used with any
150 # The parent class defines aliases that can be safely used with any
125 # frontend.
151 # frontend.
126 super(TerminalInteractiveShell, self).init_alias()
152 super(TerminalInteractiveShell, self).init_alias()
127
153
128 # Now define aliases that only make sense on the terminal, because they
154 # Now define aliases that only make sense on the terminal, because they
129 # need direct access to the console in a way that we can't emulate in
155 # need direct access to the console in a way that we can't emulate in
130 # GUI or web frontend
156 # GUI or web frontend
131 if os.name == 'posix':
157 if os.name == 'posix':
132 aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'),
158 aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'),
133 ('man', 'man')]
159 ('man', 'man')]
134 elif os.name == 'nt':
160 elif os.name == 'nt':
135 aliases = [('cls', 'cls')]
161 aliases = [('cls', 'cls')]
136
162
137
163
138 for name, cmd in aliases:
164 for name, cmd in aliases:
139 self.alias_manager.define_alias(name, cmd)
165 self.alias_manager.define_alias(name, cmd)
140
166
141 #-------------------------------------------------------------------------
167 #-------------------------------------------------------------------------
142 # Things related to the banner and usage
168 # Things related to the banner and usage
143 #-------------------------------------------------------------------------
169 #-------------------------------------------------------------------------
144
170
145 def _banner1_changed(self):
171 def _banner1_changed(self):
146 self.compute_banner()
172 self.compute_banner()
147
173
148 def _banner2_changed(self):
174 def _banner2_changed(self):
149 self.compute_banner()
175 self.compute_banner()
150
176
151 def _term_title_changed(self, name, new_value):
177 def _term_title_changed(self, name, new_value):
152 self.init_term_title()
178 self.init_term_title()
153
179
154 def init_banner(self, banner1, banner2, display_banner):
180 def init_banner(self, banner1, banner2, display_banner):
155 if banner1 is not None:
181 if banner1 is not None:
156 self.banner1 = banner1
182 self.banner1 = banner1
157 if banner2 is not None:
183 if banner2 is not None:
158 self.banner2 = banner2
184 self.banner2 = banner2
159 if display_banner is not None:
185 if display_banner is not None:
160 self.display_banner = display_banner
186 self.display_banner = display_banner
161 self.compute_banner()
187 self.compute_banner()
162
188
163 def show_banner(self, banner=None):
189 def show_banner(self, banner=None):
164 if banner is None:
190 if banner is None:
165 banner = self.banner
191 banner = self.banner
166 self.write(banner)
192 self.write(banner)
167
193
168 def compute_banner(self):
194 def compute_banner(self):
169 self.banner = self.banner1
195 self.banner = self.banner1
170 if self.profile:
196 if self.profile:
171 self.banner += '\nIPython profile: %s\n' % self.profile
197 self.banner += '\nIPython profile: %s\n' % self.profile
172 if self.banner2:
198 if self.banner2:
173 self.banner += '\n' + self.banner2
199 self.banner += '\n' + self.banner2
174
200
175 def init_usage(self, usage=None):
201 def init_usage(self, usage=None):
176 if usage is None:
202 if usage is None:
177 self.usage = interactive_usage
203 self.usage = interactive_usage
178 else:
204 else:
179 self.usage = usage
205 self.usage = usage
180
206
181 #-------------------------------------------------------------------------
207 #-------------------------------------------------------------------------
182 # Mainloop and code execution logic
208 # Mainloop and code execution logic
183 #-------------------------------------------------------------------------
209 #-------------------------------------------------------------------------
184
210
185 def mainloop(self, display_banner=None):
211 def mainloop(self, display_banner=None):
186 """Start the mainloop.
212 """Start the mainloop.
187
213
188 If an optional banner argument is given, it will override the
214 If an optional banner argument is given, it will override the
189 internally created default banner.
215 internally created default banner.
190 """
216 """
191
217
192 with nested(self.builtin_trap, self.display_trap):
218 with nested(self.builtin_trap, self.display_trap):
193
219
194 while 1:
220 while 1:
195 try:
221 try:
196 self.interact(display_banner=display_banner)
222 self.interact(display_banner=display_banner)
197 #self.interact_with_readline()
223 #self.interact_with_readline()
198 # XXX for testing of a readline-decoupled repl loop, call
224 # XXX for testing of a readline-decoupled repl loop, call
199 # interact_with_readline above
225 # interact_with_readline above
200 break
226 break
201 except KeyboardInterrupt:
227 except KeyboardInterrupt:
202 # this should not be necessary, but KeyboardInterrupt
228 # this should not be necessary, but KeyboardInterrupt
203 # handling seems rather unpredictable...
229 # handling seems rather unpredictable...
204 self.write("\nKeyboardInterrupt in interact()\n")
230 self.write("\nKeyboardInterrupt in interact()\n")
205
231
206 def interact(self, display_banner=None):
232 def interact(self, display_banner=None):
207 """Closely emulate the interactive Python console."""
233 """Closely emulate the interactive Python console."""
208
234
209 # batch run -> do not interact
235 # batch run -> do not interact
210 if self.exit_now:
236 if self.exit_now:
211 return
237 return
212
238
213 if display_banner is None:
239 if display_banner is None:
214 display_banner = self.display_banner
240 display_banner = self.display_banner
215 if display_banner:
241 if display_banner:
216 self.show_banner()
242 self.show_banner()
217
243
218 more = False
244 more = False
219
245
220 # Mark activity in the builtins
246 # Mark activity in the builtins
221 __builtin__.__dict__['__IPYTHON__active'] += 1
247 __builtin__.__dict__['__IPYTHON__active'] += 1
222
248
223 if self.has_readline:
249 if self.has_readline:
224 self.readline_startup_hook(self.pre_readline)
250 self.readline_startup_hook(self.pre_readline)
225 # exit_now is set by a call to %Exit or %Quit, through the
251 # exit_now is set by a call to %Exit or %Quit, through the
226 # ask_exit callback.
252 # ask_exit callback.
227
253
228 while not self.exit_now:
254 while not self.exit_now:
229 self.hooks.pre_prompt_hook()
255 self.hooks.pre_prompt_hook()
230 if more:
256 if more:
231 try:
257 try:
232 prompt = self.hooks.generate_prompt(True)
258 prompt = self.hooks.generate_prompt(True)
233 except:
259 except:
234 self.showtraceback()
260 self.showtraceback()
235 if self.autoindent:
261 if self.autoindent:
236 self.rl_do_indent = True
262 self.rl_do_indent = True
237
263
238 else:
264 else:
239 try:
265 try:
240 prompt = self.hooks.generate_prompt(False)
266 prompt = self.hooks.generate_prompt(False)
241 except:
267 except:
242 self.showtraceback()
268 self.showtraceback()
243 try:
269 try:
244 line = self.raw_input(prompt)
270 line = self.raw_input(prompt)
245 if self.exit_now:
271 if self.exit_now:
246 # quick exit on sys.std[in|out] close
272 # quick exit on sys.std[in|out] close
247 break
273 break
248 if self.autoindent:
274 if self.autoindent:
249 self.rl_do_indent = False
275 self.rl_do_indent = False
250
276
251 except KeyboardInterrupt:
277 except KeyboardInterrupt:
252 #double-guard against keyboardinterrupts during kbdint handling
278 #double-guard against keyboardinterrupts during kbdint handling
253 try:
279 try:
254 self.write('\nKeyboardInterrupt\n')
280 self.write('\nKeyboardInterrupt\n')
255 self.input_splitter.reset()
281 self.input_splitter.reset()
256 more = False
282 more = False
257 except KeyboardInterrupt:
283 except KeyboardInterrupt:
258 pass
284 pass
259 except EOFError:
285 except EOFError:
260 if self.autoindent:
286 if self.autoindent:
261 self.rl_do_indent = False
287 self.rl_do_indent = False
262 if self.has_readline:
288 if self.has_readline:
263 self.readline_startup_hook(None)
289 self.readline_startup_hook(None)
264 self.write('\n')
290 self.write('\n')
265 self.exit()
291 self.exit()
266 except bdb.BdbQuit:
292 except bdb.BdbQuit:
267 warn('The Python debugger has exited with a BdbQuit exception.\n'
293 warn('The Python debugger has exited with a BdbQuit exception.\n'
268 'Because of how pdb handles the stack, it is impossible\n'
294 'Because of how pdb handles the stack, it is impossible\n'
269 'for IPython to properly format this particular exception.\n'
295 'for IPython to properly format this particular exception.\n'
270 'IPython will resume normal operation.')
296 'IPython will resume normal operation.')
271 except:
297 except:
272 # exceptions here are VERY RARE, but they can be triggered
298 # exceptions here are VERY RARE, but they can be triggered
273 # asynchronously by signal handlers, for example.
299 # asynchronously by signal handlers, for example.
274 self.showtraceback()
300 self.showtraceback()
275 else:
301 else:
276 self.input_splitter.push(line)
302 self.input_splitter.push(line)
277 more = self.input_splitter.push_accepts_more()
303 more = self.input_splitter.push_accepts_more()
278 if (self.SyntaxTB.last_syntax_error and
304 if (self.SyntaxTB.last_syntax_error and
279 self.autoedit_syntax):
305 self.autoedit_syntax):
280 self.edit_syntax_error()
306 self.edit_syntax_error()
281 if not more:
307 if not more:
282 source_raw = self.input_splitter.source_raw_reset()[1]
308 source_raw = self.input_splitter.source_raw_reset()[1]
283 self.run_cell(source_raw)
309 self.run_cell(source_raw)
284
310
285 # We are off again...
311 # We are off again...
286 __builtin__.__dict__['__IPYTHON__active'] -= 1
312 __builtin__.__dict__['__IPYTHON__active'] -= 1
287
313
288 # Turn off the exit flag, so the mainloop can be restarted if desired
314 # Turn off the exit flag, so the mainloop can be restarted if desired
289 self.exit_now = False
315 self.exit_now = False
290
316
291 def raw_input(self, prompt=''):
317 def raw_input(self, prompt=''):
292 """Write a prompt and read a line.
318 """Write a prompt and read a line.
293
319
294 The returned line does not include the trailing newline.
320 The returned line does not include the trailing newline.
295 When the user enters the EOF key sequence, EOFError is raised.
321 When the user enters the EOF key sequence, EOFError is raised.
296
322
297 Optional inputs:
323 Optional inputs:
298
324
299 - prompt(''): a string to be printed to prompt the user.
325 - prompt(''): a string to be printed to prompt the user.
300
326
301 - continue_prompt(False): whether this line is the first one or a
327 - continue_prompt(False): whether this line is the first one or a
302 continuation in a sequence of inputs.
328 continuation in a sequence of inputs.
303 """
329 """
304 # Code run by the user may have modified the readline completer state.
330 # Code run by the user may have modified the readline completer state.
305 # We must ensure that our completer is back in place.
331 # We must ensure that our completer is back in place.
306
332
307 if self.has_readline:
333 if self.has_readline:
308 self.set_readline_completer()
334 self.set_readline_completer()
309
335
310 try:
336 try:
311 line = raw_input_original(prompt).decode(self.stdin_encoding)
337 line = raw_input_original(prompt).decode(self.stdin_encoding)
312 except ValueError:
338 except ValueError:
313 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
339 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
314 " or sys.stdout.close()!\nExiting IPython!")
340 " or sys.stdout.close()!\nExiting IPython!")
315 self.ask_exit()
341 self.ask_exit()
316 return ""
342 return ""
317
343
318 # Try to be reasonably smart about not re-indenting pasted input more
344 # Try to be reasonably smart about not re-indenting pasted input more
319 # than necessary. We do this by trimming out the auto-indent initial
345 # than necessary. We do this by trimming out the auto-indent initial
320 # spaces, if the user's actual input started itself with whitespace.
346 # spaces, if the user's actual input started itself with whitespace.
321 if self.autoindent:
347 if self.autoindent:
322 if num_ini_spaces(line) > self.indent_current_nsp:
348 if num_ini_spaces(line) > self.indent_current_nsp:
323 line = line[self.indent_current_nsp:]
349 line = line[self.indent_current_nsp:]
324 self.indent_current_nsp = 0
350 self.indent_current_nsp = 0
325
351
326 return line
352 return line
327
353
328 #-------------------------------------------------------------------------
354 #-------------------------------------------------------------------------
329 # Methods to support auto-editing of SyntaxErrors.
355 # Methods to support auto-editing of SyntaxErrors.
330 #-------------------------------------------------------------------------
356 #-------------------------------------------------------------------------
331
357
332 def edit_syntax_error(self):
358 def edit_syntax_error(self):
333 """The bottom half of the syntax error handler called in the main loop.
359 """The bottom half of the syntax error handler called in the main loop.
334
360
335 Loop until syntax error is fixed or user cancels.
361 Loop until syntax error is fixed or user cancels.
336 """
362 """
337
363
338 while self.SyntaxTB.last_syntax_error:
364 while self.SyntaxTB.last_syntax_error:
339 # copy and clear last_syntax_error
365 # copy and clear last_syntax_error
340 err = self.SyntaxTB.clear_err_state()
366 err = self.SyntaxTB.clear_err_state()
341 if not self._should_recompile(err):
367 if not self._should_recompile(err):
342 return
368 return
343 try:
369 try:
344 # may set last_syntax_error again if a SyntaxError is raised
370 # may set last_syntax_error again if a SyntaxError is raised
345 self.safe_execfile(err.filename,self.user_ns)
371 self.safe_execfile(err.filename,self.user_ns)
346 except:
372 except:
347 self.showtraceback()
373 self.showtraceback()
348 else:
374 else:
349 try:
375 try:
350 f = file(err.filename)
376 f = file(err.filename)
351 try:
377 try:
352 # This should be inside a display_trap block and I
378 # This should be inside a display_trap block and I
353 # think it is.
379 # think it is.
354 sys.displayhook(f.read())
380 sys.displayhook(f.read())
355 finally:
381 finally:
356 f.close()
382 f.close()
357 except:
383 except:
358 self.showtraceback()
384 self.showtraceback()
359
385
360 def _should_recompile(self,e):
386 def _should_recompile(self,e):
361 """Utility routine for edit_syntax_error"""
387 """Utility routine for edit_syntax_error"""
362
388
363 if e.filename in ('<ipython console>','<input>','<string>',
389 if e.filename in ('<ipython console>','<input>','<string>',
364 '<console>','<BackgroundJob compilation>',
390 '<console>','<BackgroundJob compilation>',
365 None):
391 None):
366
392
367 return False
393 return False
368 try:
394 try:
369 if (self.autoedit_syntax and
395 if (self.autoedit_syntax and
370 not self.ask_yes_no('Return to editor to correct syntax error? '
396 not self.ask_yes_no('Return to editor to correct syntax error? '
371 '[Y/n] ','y')):
397 '[Y/n] ','y')):
372 return False
398 return False
373 except EOFError:
399 except EOFError:
374 return False
400 return False
375
401
376 def int0(x):
402 def int0(x):
377 try:
403 try:
378 return int(x)
404 return int(x)
379 except TypeError:
405 except TypeError:
380 return 0
406 return 0
381 # always pass integer line and offset values to editor hook
407 # always pass integer line and offset values to editor hook
382 try:
408 try:
383 self.hooks.fix_error_editor(e.filename,
409 self.hooks.fix_error_editor(e.filename,
384 int0(e.lineno),int0(e.offset),e.msg)
410 int0(e.lineno),int0(e.offset),e.msg)
385 except TryNext:
411 except TryNext:
386 warn('Could not open editor')
412 warn('Could not open editor')
387 return False
413 return False
388 return True
414 return True
389
415
390 #-------------------------------------------------------------------------
416 #-------------------------------------------------------------------------
391 # Things related to GUI support and pylab
417 # Things related to GUI support and pylab
392 #-------------------------------------------------------------------------
418 #-------------------------------------------------------------------------
393
419
394 def enable_pylab(self, gui=None):
420 def enable_pylab(self, gui=None):
395 """Activate pylab support at runtime.
421 """Activate pylab support at runtime.
396
422
397 This turns on support for matplotlib, preloads into the interactive
423 This turns on support for matplotlib, preloads into the interactive
398 namespace all of numpy and pylab, and configures IPython to correcdtly
424 namespace all of numpy and pylab, and configures IPython to correcdtly
399 interact with the GUI event loop. The GUI backend to be used can be
425 interact with the GUI event loop. The GUI backend to be used can be
400 optionally selected with the optional :param:`gui` argument.
426 optionally selected with the optional :param:`gui` argument.
401
427
402 Parameters
428 Parameters
403 ----------
429 ----------
404 gui : optional, string
430 gui : optional, string
405
431
406 If given, dictates the choice of matplotlib GUI backend to use
432 If given, dictates the choice of matplotlib GUI backend to use
407 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
433 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
408 'gtk'), otherwise we use the default chosen by matplotlib (as
434 'gtk'), otherwise we use the default chosen by matplotlib (as
409 dictated by the matplotlib build-time options plus the user's
435 dictated by the matplotlib build-time options plus the user's
410 matplotlibrc configuration file).
436 matplotlibrc configuration file).
411 """
437 """
412 # We want to prevent the loading of pylab to pollute the user's
438 # We want to prevent the loading of pylab to pollute the user's
413 # namespace as shown by the %who* magics, so we execute the activation
439 # namespace as shown by the %who* magics, so we execute the activation
414 # code in an empty namespace, and we update *both* user_ns and
440 # code in an empty namespace, and we update *both* user_ns and
415 # user_ns_hidden with this information.
441 # user_ns_hidden with this information.
416 ns = {}
442 ns = {}
417 gui = pylab_activate(ns, gui)
443 gui = pylab_activate(ns, gui)
418 self.user_ns.update(ns)
444 self.user_ns.update(ns)
419 self.user_ns_hidden.update(ns)
445 self.user_ns_hidden.update(ns)
420 # Now we must activate the gui pylab wants to use, and fix %run to take
446 # Now we must activate the gui pylab wants to use, and fix %run to take
421 # plot updates into account
447 # plot updates into account
422 enable_gui(gui)
448 enable_gui(gui)
423 self.magic_run = self._pylab_magic_run
449 self.magic_run = self._pylab_magic_run
424
450
425 #-------------------------------------------------------------------------
451 #-------------------------------------------------------------------------
426 # Things related to exiting
452 # Things related to exiting
427 #-------------------------------------------------------------------------
453 #-------------------------------------------------------------------------
428
454
429 def ask_exit(self):
455 def ask_exit(self):
430 """ Ask the shell to exit. Can be overiden and used as a callback. """
456 """ Ask the shell to exit. Can be overiden and used as a callback. """
431 self.exit_now = True
457 self.exit_now = True
432
458
433 def exit(self):
459 def exit(self):
434 """Handle interactive exit.
460 """Handle interactive exit.
435
461
436 This method calls the ask_exit callback."""
462 This method calls the ask_exit callback."""
437 if self.confirm_exit:
463 if self.confirm_exit:
438 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
464 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
439 self.ask_exit()
465 self.ask_exit()
440 else:
466 else:
441 self.ask_exit()
467 self.ask_exit()
442
468
443 #------------------------------------------------------------------------
469 #------------------------------------------------------------------------
444 # Magic overrides
470 # Magic overrides
445 #------------------------------------------------------------------------
471 #------------------------------------------------------------------------
446 # Once the base class stops inheriting from magic, this code needs to be
472 # Once the base class stops inheriting from magic, this code needs to be
447 # moved into a separate machinery as well. For now, at least isolate here
473 # moved into a separate machinery as well. For now, at least isolate here
448 # the magics which this class needs to implement differently from the base
474 # the magics which this class needs to implement differently from the base
449 # class, or that are unique to it.
475 # class, or that are unique to it.
450
476
451 def magic_autoindent(self, parameter_s = ''):
477 def magic_autoindent(self, parameter_s = ''):
452 """Toggle autoindent on/off (if available)."""
478 """Toggle autoindent on/off (if available)."""
453
479
454 self.shell.set_autoindent()
480 self.shell.set_autoindent()
455 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
481 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
456
482
457 @skip_doctest
483 @skip_doctest
458 def magic_cpaste(self, parameter_s=''):
484 def magic_cpaste(self, parameter_s=''):
459 """Paste & execute a pre-formatted code block from clipboard.
485 """Paste & execute a pre-formatted code block from clipboard.
460
486
461 You must terminate the block with '--' (two minus-signs) alone on the
487 You must terminate the block with '--' (two minus-signs) alone on the
462 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
488 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
463 is the new sentinel for this operation)
489 is the new sentinel for this operation)
464
490
465 The block is dedented prior to execution to enable execution of method
491 The block is dedented prior to execution to enable execution of method
466 definitions. '>' and '+' characters at the beginning of a line are
492 definitions. '>' and '+' characters at the beginning of a line are
467 ignored, to allow pasting directly from e-mails, diff files and
493 ignored, to allow pasting directly from e-mails, diff files and
468 doctests (the '...' continuation prompt is also stripped). The
494 doctests (the '...' continuation prompt is also stripped). The
469 executed block is also assigned to variable named 'pasted_block' for
495 executed block is also assigned to variable named 'pasted_block' for
470 later editing with '%edit pasted_block'.
496 later editing with '%edit pasted_block'.
471
497
472 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
498 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
473 This assigns the pasted block to variable 'foo' as string, without
499 This assigns the pasted block to variable 'foo' as string, without
474 dedenting or executing it (preceding >>> and + is still stripped)
500 dedenting or executing it (preceding >>> and + is still stripped)
475
501
476 '%cpaste -r' re-executes the block previously entered by cpaste.
502 '%cpaste -r' re-executes the block previously entered by cpaste.
477
503
478 Do not be alarmed by garbled output on Windows (it's a readline bug).
504 Do not be alarmed by garbled output on Windows (it's a readline bug).
479 Just press enter and type -- (and press enter again) and the block
505 Just press enter and type -- (and press enter again) and the block
480 will be what was just pasted.
506 will be what was just pasted.
481
507
482 IPython statements (magics, shell escapes) are not supported (yet).
508 IPython statements (magics, shell escapes) are not supported (yet).
483
509
484 See also
510 See also
485 --------
511 --------
486 paste: automatically pull code from clipboard.
512 paste: automatically pull code from clipboard.
487
513
488 Examples
514 Examples
489 --------
515 --------
490 ::
516 ::
491
517
492 In [8]: %cpaste
518 In [8]: %cpaste
493 Pasting code; enter '--' alone on the line to stop.
519 Pasting code; enter '--' alone on the line to stop.
494 :>>> a = ["world!", "Hello"]
520 :>>> a = ["world!", "Hello"]
495 :>>> print " ".join(sorted(a))
521 :>>> print " ".join(sorted(a))
496 :--
522 :--
497 Hello world!
523 Hello world!
498 """
524 """
499
525
500 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
526 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
501 par = args.strip()
527 par = args.strip()
502 if opts.has_key('r'):
528 if opts.has_key('r'):
503 self._rerun_pasted()
529 self._rerun_pasted()
504 return
530 return
505
531
506 sentinel = opts.get('s','--')
532 sentinel = opts.get('s','--')
507
533
508 block = self._strip_pasted_lines_for_code(
534 block = self._strip_pasted_lines_for_code(
509 self._get_pasted_lines(sentinel))
535 self._get_pasted_lines(sentinel))
510
536
511 self._execute_block(block, par)
537 self._execute_block(block, par)
512
538
513 def magic_paste(self, parameter_s=''):
539 def magic_paste(self, parameter_s=''):
514 """Paste & execute a pre-formatted code block from clipboard.
540 """Paste & execute a pre-formatted code block from clipboard.
515
541
516 The text is pulled directly from the clipboard without user
542 The text is pulled directly from the clipboard without user
517 intervention and printed back on the screen before execution (unless
543 intervention and printed back on the screen before execution (unless
518 the -q flag is given to force quiet mode).
544 the -q flag is given to force quiet mode).
519
545
520 The block is dedented prior to execution to enable execution of method
546 The block is dedented prior to execution to enable execution of method
521 definitions. '>' and '+' characters at the beginning of a line are
547 definitions. '>' and '+' characters at the beginning of a line are
522 ignored, to allow pasting directly from e-mails, diff files and
548 ignored, to allow pasting directly from e-mails, diff files and
523 doctests (the '...' continuation prompt is also stripped). The
549 doctests (the '...' continuation prompt is also stripped). The
524 executed block is also assigned to variable named 'pasted_block' for
550 executed block is also assigned to variable named 'pasted_block' for
525 later editing with '%edit pasted_block'.
551 later editing with '%edit pasted_block'.
526
552
527 You can also pass a variable name as an argument, e.g. '%paste foo'.
553 You can also pass a variable name as an argument, e.g. '%paste foo'.
528 This assigns the pasted block to variable 'foo' as string, without
554 This assigns the pasted block to variable 'foo' as string, without
529 dedenting or executing it (preceding >>> and + is still stripped)
555 dedenting or executing it (preceding >>> and + is still stripped)
530
556
531 Options
557 Options
532 -------
558 -------
533
559
534 -r: re-executes the block previously entered by cpaste.
560 -r: re-executes the block previously entered by cpaste.
535
561
536 -q: quiet mode: do not echo the pasted text back to the terminal.
562 -q: quiet mode: do not echo the pasted text back to the terminal.
537
563
538 IPython statements (magics, shell escapes) are not supported (yet).
564 IPython statements (magics, shell escapes) are not supported (yet).
539
565
540 See also
566 See also
541 --------
567 --------
542 cpaste: manually paste code into terminal until you mark its end.
568 cpaste: manually paste code into terminal until you mark its end.
543 """
569 """
544 opts,args = self.parse_options(parameter_s,'rq',mode='string')
570 opts,args = self.parse_options(parameter_s,'rq',mode='string')
545 par = args.strip()
571 par = args.strip()
546 if opts.has_key('r'):
572 if opts.has_key('r'):
547 self._rerun_pasted()
573 self._rerun_pasted()
548 return
574 return
549
575
550 text = self.shell.hooks.clipboard_get()
576 text = self.shell.hooks.clipboard_get()
551 block = self._strip_pasted_lines_for_code(text.splitlines())
577 block = self._strip_pasted_lines_for_code(text.splitlines())
552
578
553 # By default, echo back to terminal unless quiet mode is requested
579 # By default, echo back to terminal unless quiet mode is requested
554 if not opts.has_key('q'):
580 if not opts.has_key('q'):
555 write = self.shell.write
581 write = self.shell.write
556 write(self.shell.pycolorize(block))
582 write(self.shell.pycolorize(block))
557 if not block.endswith('\n'):
583 if not block.endswith('\n'):
558 write('\n')
584 write('\n')
559 write("## -- End pasted text --\n")
585 write("## -- End pasted text --\n")
560
586
561 self._execute_block(block, par)
587 self._execute_block(block, par)
562
588
563
589
564 InteractiveShellABC.register(TerminalInteractiveShell)
590 InteractiveShellABC.register(TerminalInteractiveShell)
This diff has been collapsed as it changes many lines, (768 lines changed) Show them Hide them
@@ -1,666 +1,540
1 #!/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.newapplication.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 """
13 """
13
14
14 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
15 # Copyright (C) 2008-2010 The IPython Development Team
16 # Copyright (C) 2008-2010 The IPython Development Team
16 #
17 #
17 # 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
18 # the file COPYING, distributed as part of this software.
19 # the file COPYING, distributed as part of this software.
19 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
20
21
21 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
22 # Imports
23 # Imports
23 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
24
25
25 from __future__ import absolute_import
26 from __future__ import absolute_import
26
27
27 import logging
28 import logging
28 import os
29 import os
29 import sys
30 import sys
30
31
32 from IPython.config.loader import (
33 Config, PyFileConfigLoader
34 )
35 from IPython.config.application import boolean_flag
31 from IPython.core import release
36 from IPython.core import release
37 from IPython.core import usage
32 from IPython.core.crashhandler import CrashHandler
38 from IPython.core.crashhandler import CrashHandler
33 from IPython.core.application import Application, BaseAppConfigLoader
39 from IPython.core.formatters import PlainTextFormatter
34 from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
40 from IPython.core.newapplication import (
35 from IPython.config.loader import (
41 ProfileDir, BaseIPythonApplication, base_flags, base_aliases
36 Config,
37 PyFileConfigLoader
38 )
42 )
43 from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
39 from IPython.lib import inputhook
44 from IPython.lib import inputhook
40 from IPython.utils.path import filefind, get_ipython_dir, check_for_old_config
45 from IPython.utils.path import filefind, get_ipython_dir, check_for_old_config
41 from IPython.core import usage
46 from IPython.utils.traitlets import (
47 Bool, Unicode, Dict, Instance, List,CaselessStrEnum
48 )
42
49
43 #-----------------------------------------------------------------------------
50 #-----------------------------------------------------------------------------
44 # Globals, utilities and helpers
51 # Globals, utilities and helpers
45 #-----------------------------------------------------------------------------
52 #-----------------------------------------------------------------------------
46
53
47 #: The default config file name for this application.
54 #: The default config file name for this application.
48 default_config_file_name = u'ipython_config.py'
55 default_config_file_name = u'ipython_config.py'
49
56
50
57
51 class IPAppConfigLoader(BaseAppConfigLoader):
52
53 def _add_arguments(self):
54 super(IPAppConfigLoader, self)._add_arguments()
55 paa = self.parser.add_argument
56 paa('-p',
57 '--profile', dest='Global.profile', type=unicode,
58 help=
59 """The string name of the ipython profile to be used. Assume that your
60 config file is ipython_config-<name>.py (looks in current dir first,
61 then in IPYTHON_DIR). This is a quick way to keep and load multiple
62 config files for different tasks, especially if include your basic one
63 in your more specialized ones. You can keep a basic
64 IPYTHON_DIR/ipython_config.py file and then have other 'profiles' which
65 include this one and load extra things for particular tasks.""",
66 metavar='Global.profile')
67 paa('--config-file',
68 dest='Global.config_file', type=unicode,
69 help=
70 """Set the config file name to override default. Normally IPython
71 loads ipython_config.py (from current directory) or
72 IPYTHON_DIR/ipython_config.py. If the loading of your config file
73 fails, IPython starts with a bare bones configuration (no modules
74 loaded at all).""",
75 metavar='Global.config_file')
76 paa('--autocall',
77 dest='InteractiveShell.autocall', type=int,
78 help=
79 """Make IPython automatically call any callable object even if you
80 didn't type explicit parentheses. For example, 'str 43' becomes
81 'str(43)' automatically. The value can be '0' to disable the feature,
82 '1' for 'smart' autocall, where it is not applied if there are no more
83 arguments on the line, and '2' for 'full' autocall, where all callable
84 objects are automatically called (even if no arguments are present).
85 The default is '1'.""",
86 metavar='InteractiveShell.autocall')
87 paa('--autoindent',
88 action='store_true', dest='InteractiveShell.autoindent',
89 help='Turn on autoindenting.')
90 paa('--no-autoindent',
91 action='store_false', dest='InteractiveShell.autoindent',
92 help='Turn off autoindenting.')
93 paa('--automagic',
94 action='store_true', dest='InteractiveShell.automagic',
95 help=
96 """Turn on the auto calling of magic commands. Type %%magic at the
97 IPython prompt for more information.""")
98 paa('--no-automagic',
99 action='store_false', dest='InteractiveShell.automagic',
100 help='Turn off the auto calling of magic commands.')
101 paa('--autoedit-syntax',
102 action='store_true', dest='TerminalInteractiveShell.autoedit_syntax',
103 help='Turn on auto editing of files with syntax errors.')
104 paa('--no-autoedit-syntax',
105 action='store_false', dest='TerminalInteractiveShell.autoedit_syntax',
106 help='Turn off auto editing of files with syntax errors.')
107 paa('--banner',
108 action='store_true', dest='Global.display_banner',
109 help='Display a banner upon starting IPython.')
110 paa('--no-banner',
111 action='store_false', dest='Global.display_banner',
112 help="Don't display a banner upon starting IPython.")
113 paa('--cache-size',
114 type=int, dest='InteractiveShell.cache_size',
115 help=
116 """Set the size of the output cache. The default is 1000, you can
117 change it permanently in your config file. Setting it to 0 completely
118 disables the caching system, and the minimum value accepted is 20 (if
119 you provide a value less than 20, it is reset to 0 and a warning is
120 issued). This limit is defined because otherwise you'll spend more
121 time re-flushing a too small cache than working""",
122 metavar='InteractiveShell.cache_size')
123 paa('--classic',
124 action='store_true', dest='Global.classic',
125 help="Gives IPython a similar feel to the classic Python prompt.")
126 paa('--colors',
127 type=str, dest='InteractiveShell.colors',
128 help="Set the color scheme (NoColor, Linux, and LightBG).",
129 metavar='InteractiveShell.colors')
130 paa('--color-info',
131 action='store_true', dest='InteractiveShell.color_info',
132 help=
133 """IPython can display information about objects via a set of func-
134 tions, and optionally can use colors for this, syntax highlighting
135 source code and various other elements. However, because this
136 information is passed through a pager (like 'less') and many pagers get
137 confused with color codes, this option is off by default. You can test
138 it and turn it on permanently in your ipython_config.py file if it
139 works for you. Test it and turn it on permanently if it works with
140 your system. The magic function %%color_info allows you to toggle this
141 inter- actively for testing.""")
142 paa('--no-color-info',
143 action='store_false', dest='InteractiveShell.color_info',
144 help="Disable using colors for info related things.")
145 paa('--confirm-exit',
146 action='store_true', dest='TerminalInteractiveShell.confirm_exit',
147 help=
148 """Set to confirm when you try to exit IPython with an EOF (Control-D
149 in Unix, Control-Z/Enter in Windows). By typing 'exit', 'quit' or
150 '%%Exit', you can force a direct exit without any confirmation.""")
151 paa('--no-confirm-exit',
152 action='store_false', dest='TerminalInteractiveShell.confirm_exit',
153 help="Don't prompt the user when exiting.")
154 paa('--deep-reload',
155 action='store_true', dest='InteractiveShell.deep_reload',
156 help=
157 """Enable deep (recursive) reloading by default. IPython can use the
158 deep_reload module which reloads changes in modules recursively (it
159 replaces the reload() function, so you don't need to change anything to
160 use it). deep_reload() forces a full reload of modules whose code may
161 have changed, which the default reload() function does not. When
162 deep_reload is off, IPython will use the normal reload(), but
163 deep_reload will still be available as dreload(). This fea- ture is off
164 by default [which means that you have both normal reload() and
165 dreload()].""")
166 paa('--no-deep-reload',
167 action='store_false', dest='InteractiveShell.deep_reload',
168 help="Disable deep (recursive) reloading by default.")
169 paa('--editor',
170 type=str, dest='TerminalInteractiveShell.editor',
171 help="Set the editor used by IPython (default to $EDITOR/vi/notepad).",
172 metavar='TerminalInteractiveShell.editor')
173 paa('--log','-l',
174 action='store_true', dest='InteractiveShell.logstart',
175 help="Start logging to the default log file (./ipython_log.py).")
176 paa('--logfile','-lf',
177 type=unicode, dest='InteractiveShell.logfile',
178 help="Start logging to logfile with this name.",
179 metavar='InteractiveShell.logfile')
180 paa('--log-append','-la',
181 type=unicode, dest='InteractiveShell.logappend',
182 help="Start logging to the given file in append mode.",
183 metavar='InteractiveShell.logfile')
184 paa('--pdb',
185 action='store_true', dest='InteractiveShell.pdb',
186 help="Enable auto calling the pdb debugger after every exception.")
187 paa('--no-pdb',
188 action='store_false', dest='InteractiveShell.pdb',
189 help="Disable auto calling the pdb debugger after every exception.")
190 paa('--pprint',
191 action='store_true', dest='PlainTextFormatter.pprint',
192 help="Enable auto pretty printing of results.")
193 paa('--no-pprint',
194 action='store_false', dest='PlainTextFormatter.pprint',
195 help="Disable auto auto pretty printing of results.")
196 paa('--prompt-in1','-pi1',
197 type=str, dest='InteractiveShell.prompt_in1',
198 help=
199 """Set the main input prompt ('In [\#]: '). Note that if you are using
200 numbered prompts, the number is represented with a '\#' in the string.
201 Don't forget to quote strings with spaces embedded in them. Most
202 bash-like escapes can be used to customize IPython's prompts, as well
203 as a few additional ones which are IPython-spe- cific. All valid
204 prompt escapes are described in detail in the Customization section of
205 the IPython manual.""",
206 metavar='InteractiveShell.prompt_in1')
207 paa('--prompt-in2','-pi2',
208 type=str, dest='InteractiveShell.prompt_in2',
209 help=
210 """Set the secondary input prompt (' .\D.: '). Similar to the previous
211 option, but used for the continuation prompts. The special sequence
212 '\D' is similar to '\#', but with all digits replaced by dots (so you
213 can have your continuation prompt aligned with your input prompt).
214 Default: ' .\D.: ' (note three spaces at the start for alignment with
215 'In [\#]')""",
216 metavar='InteractiveShell.prompt_in2')
217 paa('--prompt-out','-po',
218 type=str, dest='InteractiveShell.prompt_out',
219 help="Set the output prompt ('Out[\#]:')",
220 metavar='InteractiveShell.prompt_out')
221 paa('--quick',
222 action='store_true', dest='Global.quick',
223 help="Enable quick startup with no config files.")
224 paa('--readline',
225 action='store_true', dest='InteractiveShell.readline_use',
226 help="Enable readline for command line usage.")
227 paa('--no-readline',
228 action='store_false', dest='InteractiveShell.readline_use',
229 help="Disable readline for command line usage.")
230 paa('--screen-length','-sl',
231 type=int, dest='TerminalInteractiveShell.screen_length',
232 help=
233 """Number of lines of your screen, used to control printing of very
234 long strings. Strings longer than this number of lines will be sent
235 through a pager instead of directly printed. The default value for
236 this is 0, which means IPython will auto-detect your screen size every
237 time it needs to print certain potentially long strings (this doesn't
238 change the behavior of the 'print' keyword, it's only triggered
239 internally). If for some reason this isn't working well (it needs
240 curses support), specify it yourself. Otherwise don't change the
241 default.""",
242 metavar='TerminalInteractiveShell.screen_length')
243 paa('--separate-in','-si',
244 type=str, dest='InteractiveShell.separate_in',
245 help="Separator before input prompts. Default '\\n'.",
246 metavar='InteractiveShell.separate_in')
247 paa('--separate-out','-so',
248 type=str, dest='InteractiveShell.separate_out',
249 help="Separator before output prompts. Default 0 (nothing).",
250 metavar='InteractiveShell.separate_out')
251 paa('--separate-out2','-so2',
252 type=str, dest='InteractiveShell.separate_out2',
253 help="Separator after output prompts. Default 0 (nonight).",
254 metavar='InteractiveShell.separate_out2')
255 paa('--no-sep',
256 action='store_true', dest='Global.nosep',
257 help="Eliminate all spacing between prompts.")
258 paa('--term-title',
259 action='store_true', dest='TerminalInteractiveShell.term_title',
260 help="Enable auto setting the terminal title.")
261 paa('--no-term-title',
262 action='store_false', dest='TerminalInteractiveShell.term_title',
263 help="Disable auto setting the terminal title.")
264 paa('--xmode',
265 type=str, dest='InteractiveShell.xmode',
266 help=
267 """Exception reporting mode ('Plain','Context','Verbose'). Plain:
268 similar to python's normal traceback printing. Context: prints 5 lines
269 of context source code around each line in the traceback. Verbose:
270 similar to Context, but additionally prints the variables currently
271 visible where the exception happened (shortening their strings if too
272 long). This can potentially be very slow, if you happen to have a huge
273 data structure whose string representation is complex to compute.
274 Your computer may appear to freeze for a while with cpu usage at 100%%.
275 If this occurs, you can cancel the traceback with Ctrl-C (maybe hitting
276 it more than once).
277 """,
278 metavar='InteractiveShell.xmode')
279 paa('--ext',
280 type=str, dest='Global.extra_extension',
281 help="The dotted module name of an IPython extension to load.",
282 metavar='Global.extra_extension')
283 paa('-c',
284 type=str, dest='Global.code_to_run',
285 help="Execute the given command string.",
286 metavar='Global.code_to_run')
287 paa('-i',
288 action='store_true', dest='Global.force_interact',
289 help=
290 "If running code from the command line, become interactive afterwards.")
291
292 # Options to start with GUI control enabled from the beginning
293 paa('--gui',
294 type=str, dest='Global.gui',
295 help="Enable GUI event loop integration ('qt', 'wx', 'gtk').",
296 metavar='gui-mode')
297 paa('--pylab','-pylab',
298 type=str, dest='Global.pylab',
299 nargs='?', const='auto', metavar='gui-mode',
300 help="Pre-load matplotlib and numpy for interactive use. "+
301 "If no value is given, the gui backend is matplotlib's, else use "+
302 "one of: ['tk', 'qt', 'wx', 'gtk', 'osx'].")
303
304 # Legacy GUI options. Leave them in for backwards compatibility, but the
305 # 'thread' names are really a misnomer now.
306 paa('--wthread', '-wthread',
307 action='store_true', dest='Global.wthread',
308 help=
309 """Enable wxPython event loop integration. (DEPRECATED, use --gui wx)""")
310 paa('--q4thread', '--qthread', '-q4thread', '-qthread',
311 action='store_true', dest='Global.q4thread',
312 help=
313 """Enable Qt4 event loop integration. Qt3 is no longer supported.
314 (DEPRECATED, use --gui qt)""")
315 paa('--gthread', '-gthread',
316 action='store_true', dest='Global.gthread',
317 help=
318 """Enable GTK event loop integration. (DEPRECATED, use --gui gtk)""")
319
320
58
321 #-----------------------------------------------------------------------------
59 #-----------------------------------------------------------------------------
322 # Crash handler for this application
60 # Crash handler for this application
323 #-----------------------------------------------------------------------------
61 #-----------------------------------------------------------------------------
324
62
325 _message_template = """\
63 _message_template = """\
326 Oops, $self.app_name crashed. We do our best to make it stable, but...
64 Oops, $self.app_name crashed. We do our best to make it stable, but...
327
65
328 A crash report was automatically generated with the following information:
66 A crash report was automatically generated with the following information:
329 - A verbatim copy of the crash traceback.
67 - A verbatim copy of the crash traceback.
330 - A copy of your input history during this session.
68 - A copy of your input history during this session.
331 - Data on your current $self.app_name configuration.
69 - Data on your current $self.app_name configuration.
332
70
333 It was left in the file named:
71 It was left in the file named:
334 \t'$self.crash_report_fname'
72 \t'$self.crash_report_fname'
335 If you can email this file to the developers, the information in it will help
73 If you can email this file to the developers, the information in it will help
336 them in understanding and correcting the problem.
74 them in understanding and correcting the problem.
337
75
338 You can mail it to: $self.contact_name at $self.contact_email
76 You can mail it to: $self.contact_name at $self.contact_email
339 with the subject '$self.app_name Crash Report'.
77 with the subject '$self.app_name Crash Report'.
340
78
341 If you want to do it now, the following command will work (under Unix):
79 If you want to do it now, the following command will work (under Unix):
342 mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname
80 mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname
343
81
344 To ensure accurate tracking of this issue, please file a report about it at:
82 To ensure accurate tracking of this issue, please file a report about it at:
345 $self.bug_tracker
83 $self.bug_tracker
346 """
84 """
347
85
348 class IPAppCrashHandler(CrashHandler):
86 class IPAppCrashHandler(CrashHandler):
349 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
87 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
350
88
351 message_template = _message_template
89 message_template = _message_template
352
90
353 def __init__(self, app):
91 def __init__(self, app):
354 contact_name = release.authors['Fernando'][0]
92 contact_name = release.authors['Fernando'][0]
355 contact_email = release.authors['Fernando'][1]
93 contact_email = release.authors['Fernando'][1]
356 bug_tracker = 'http://github.com/ipython/ipython/issues'
94 bug_tracker = 'http://github.com/ipython/ipython/issues'
357 super(IPAppCrashHandler,self).__init__(
95 super(IPAppCrashHandler,self).__init__(
358 app, contact_name, contact_email, bug_tracker
96 app, contact_name, contact_email, bug_tracker
359 )
97 )
360
98
361 def make_report(self,traceback):
99 def make_report(self,traceback):
362 """Return a string containing a crash report."""
100 """Return a string containing a crash report."""
363
101
364 sec_sep = self.section_sep
102 sec_sep = self.section_sep
365 # Start with parent report
103 # Start with parent report
366 report = [super(IPAppCrashHandler, self).make_report(traceback)]
104 report = [super(IPAppCrashHandler, self).make_report(traceback)]
367 # Add interactive-specific info we may have
105 # Add interactive-specific info we may have
368 rpt_add = report.append
106 rpt_add = report.append
369 try:
107 try:
370 rpt_add(sec_sep+"History of session input:")
108 rpt_add(sec_sep+"History of session input:")
371 for line in self.app.shell.user_ns['_ih']:
109 for line in self.app.shell.user_ns['_ih']:
372 rpt_add(line)
110 rpt_add(line)
373 rpt_add('\n*** Last line of input (may not be in above history):\n')
111 rpt_add('\n*** Last line of input (may not be in above history):\n')
374 rpt_add(self.app.shell._last_input_line+'\n')
112 rpt_add(self.app.shell._last_input_line+'\n')
375 except:
113 except:
376 pass
114 pass
377
115
378 return ''.join(report)
116 return ''.join(report)
379
117
118 #-----------------------------------------------------------------------------
119 # Aliases and Flags
120 #-----------------------------------------------------------------------------
121 flags = dict(base_flags)
122 flags.update({
123
124
125 })
126 addflag = lambda *args: flags.update(boolean_flag(*args))
127 addflag('autoindent', 'InteractiveShell.autoindent',
128 'Turn on autoindenting.', 'Turn off autoindenting.'
129 )
130 addflag('automagic', 'InteractiveShell.automagic',
131 """Turn on the auto calling of magic commands. Type %%magic at the
132 IPython prompt for more information.""",
133 'Turn off the auto calling of magic commands.'
134 )
135 addflag('autoedit-syntax', 'TerminalInteractiveShell.autoedit_syntax',
136 'Turn on auto editing of files with syntax errors.',
137 'Turn off auto editing of files with syntax errors.'
138 )
139 addflag('banner', 'IPythonApp.display_banner',
140 "Display a banner upon starting IPython.",
141 "Don't display a banner upon starting IPython."
142 )
143 addflag('pdb', 'InteractiveShell.pdb',
144 "Enable auto calling the pdb debugger after every exception.",
145 "Disable auto calling the pdb debugger after every exception."
146 )
147 addflag('pprint', 'PlainTextFormatter.pprint',
148 "Enable auto pretty printing of results.",
149 "Disable auto auto pretty printing of results."
150 )
151 addflag('color-info', 'InteractiveShell.color_info',
152 """IPython can display information about objects via a set of func-
153 tions, and optionally can use colors for this, syntax highlighting
154 source code and various other elements. However, because this
155 information is passed through a pager (like 'less') and many pagers get
156 confused with color codes, this option is off by default. You can test
157 it and turn it on permanently in your ipython_config.py file if it
158 works for you. Test it and turn it on permanently if it works with
159 your system. The magic function %%color_info allows you to toggle this
160 inter- actively for testing.""",
161 "Disable using colors for info related things."
162 )
163 addflag('confirm-exit', 'TerminalInteractiveShell.confirm_exit',
164 """Set to confirm when you try to exit IPython with an EOF (Control-D
165 in Unix, Control-Z/Enter in Windows). By typing 'exit', 'quit' or
166 '%%Exit', you can force a direct exit without any confirmation.""",
167 "Don't prompt the user when exiting."
168 )
169 addflag('deep-reload', 'InteractiveShell.deep_reload',
170 """Enable deep (recursive) reloading by default. IPython can use the
171 deep_reload module which reloads changes in modules recursively (it
172 replaces the reload() function, so you don't need to change anything to
173 use it). deep_reload() forces a full reload of modules whose code may
174 have changed, which the default reload() function does not. When
175 deep_reload is off, IPython will use the normal reload(), but
176 deep_reload will still be available as dreload(). This fea- ture is off
177 by default [which means that you have both normal reload() and
178 dreload()].""",
179 "Disable deep (recursive) reloading by default."
180 )
181 addflag('readline', 'InteractiveShell.readline_use',
182 "Enable readline for command line usage.",
183 "Disable readline for command line usage."
184 )
185 addflag('term-title', 'TerminalInteractiveShell.term_title',
186 "Enable auto setting the terminal title.",
187 "Disable auto setting the terminal title."
188 )
189 classic_config = Config()
190 classic_config.InteractiveShell.cache_size = 0
191 classic_config.PlainTextFormatter.pprint = False
192 classic_config.InteractiveShell.prompt_in1 = '>>> '
193 classic_config.InteractiveShell.prompt_in2 = '... '
194 classic_config.InteractiveShell.prompt_out = ''
195 classic_config.InteractiveShell.separate_in = ''
196 classic_config.InteractiveShell.separate_out = ''
197 classic_config.InteractiveShell.separate_out2 = ''
198 classic_config.InteractiveShell.colors = 'NoColor'
199 classic_config.InteractiveShell.xmode = 'Plain'
200
201 flags['classic']=(
202 classic_config,
203 "Gives IPython a similar feel to the classic Python prompt."
204 )
205 # # log doesn't make so much sense this way anymore
206 # paa('--log','-l',
207 # action='store_true', dest='InteractiveShell.logstart',
208 # help="Start logging to the default log file (./ipython_log.py).")
209 #
210 # # quick is harder to implement
211 flags['quick']=(
212 {'IPythonApp' : {'quick' : True}},
213 "Enable quick startup with no config files."
214 )
215
216 nosep_config = Config()
217 nosep_config.InteractiveShell.separate_in = ''
218 nosep_config.InteractiveShell.separate_out = ''
219 nosep_config.InteractiveShell.separate_out2 = ''
220
221 flags['nosep']=(nosep_config, "Eliminate all spacing between prompts.")
222
223 flags['i'] = (
224 {'IPythonApp' : {'force_interact' : True}},
225 "If running code from the command line, become interactive afterwards."
226 )
227 flags['pylab'] = (
228 {'IPythonApp' : {'pylab' : 'auto'}},
229 """Pre-load matplotlib and numpy for interactive use with
230 the default matplotlib backend."""
231 )
232
233 aliases = dict(base_aliases)
234
235 # it's possible we don't want short aliases for *all* of these:
236 aliases.update(dict(
237 autocall='InteractiveShell.autocall',
238 cache_size='InteractiveShell.cache_size',
239 colors='InteractiveShell.colors',
240 editor='TerminalInteractiveShell.editor',
241 logfile='InteractiveShell.logfile',
242 log_append='InteractiveShell.logappend',
243 pi1='InteractiveShell.prompt_in1',
244 pi2='InteractiveShell.prompt_in1',
245 po='InteractiveShell.prompt_out',
246 sl='TerminalInteractiveShell.screen_length',
247 si='InteractiveShell.separate_in',
248 so='InteractiveShell.separate_out',
249 so2='InteractiveShell.separate_out2',
250 xmode='InteractiveShell.xmode',
251 c='IPythonApp.code_to_run',
252 ext='IPythonApp.extra_extension',
253 gui='IPythonApp.gui',
254 pylab='IPythonApp.pylab',
255 ))
380
256
381 #-----------------------------------------------------------------------------
257 #-----------------------------------------------------------------------------
382 # Main classes and functions
258 # Main classes and functions
383 #-----------------------------------------------------------------------------
259 #-----------------------------------------------------------------------------
384
260
385 class IPythonApp(Application):
261 class IPythonApp(BaseIPythonApplication):
386 name = u'ipython'
262 name = u'ipython'
387 #: argparse formats better the 'usage' than the 'description' field
263 description = usage.cl_usage
388 description = None
264 # command_line_loader = IPAppConfigLoader
389 usage = usage.cl_usage
390 command_line_loader = IPAppConfigLoader
391 default_config_file_name = default_config_file_name
265 default_config_file_name = default_config_file_name
392 crash_handler_class = IPAppCrashHandler
266 crash_handler_class = IPAppCrashHandler
393
267 flags = Dict(flags)
394 def create_default_config(self):
268 aliases = Dict(aliases)
395 super(IPythonApp, self).create_default_config()
269 classes = [TerminalInteractiveShell, ProfileDir, PlainTextFormatter]
396 # Eliminate multiple lookups
270 # *do* autocreate requested profile
397 Global = self.default_config.Global
271 auto_create=Bool(True)
398
272 copy_config_files=Bool(True)
399 # Set all default values
273 # configurables
400 Global.display_banner = True
274 ignore_old_config=Bool(False, config=True,
275 help="Suppress warning messages about legacy config files"
276 )
277 quick = Bool(False, config=True,
278 help="""Start IPython quickly by skipping the loading of config files."""
279 )
280 def _quick_changed(self, name, old, new):
281 if new:
282 self.load_config_file = lambda *a, **kw: None
283 self.ignore_old_config=True
284
285 gui = CaselessStrEnum(('qt','wx','gtk'), config=True,
286 help="Enable GUI event loop integration ('qt', 'wx', 'gtk')."
287 )
288 pylab = CaselessStrEnum(['tk', 'qt', 'wx', 'gtk', 'osx', 'auto'],
289 config=True,
290 help="""Pre-load matplotlib and numpy for interactive use,
291 selecting a particular matplotlib backend and loop integration.
292 """
293 )
294 display_banner = Bool(True, config=True,
295 help="Whether to display a banner upon starting IPython."
296 )
297 extensions = List(Unicode, config=True,
298 help="A list of dotted module names of IPython extensions to load."
299 )
300 extra_extension = Unicode('', config=True,
301 help="dotted module name of an IPython extension to load."
302 )
303 def _extra_extension_changed(self, name, old, new):
304 if new:
305 # add to self.extensions
306 self.extensions.append(new)
307
308 # if there is code of files to run from the cmd line, don't interact
309 # unless the --i flag (App.force_interact) is true.
310 force_interact = Bool(False, config=True,
311 help="""If a command or file is given via the command-line,
312 e.g. 'ipython foo.py"""
313 )
314 def _force_interact_changed(self, name, old, new):
315 if new:
316 self.interact = True
317
318 exec_files = List(Unicode, config=True,
319 help="""List of files to run at IPython startup."""
320 )
321 file_to_run = Unicode('', config=True,
322 help="""A file to be run""")
323 def _file_to_run_changed(self, name, old, new):
324 if new and not self.force_interact:
325 self.interact = False
326
327 exec_lines = List(Unicode, config=True,
328 help="""lines of code to run at IPython startup."""
329 )
330 code_to_run = Unicode('', config=True,
331 help="Execute the given command string."
332 )
333 _code_to_run_changed = _file_to_run_changed
334
335 # internal, not-configurable
336 interact=Bool(True)
337
338
339 def initialize(self, argv=None):
340 """Do actions after construct, but before starting the app."""
341 super(IPythonApp, self).initialize(argv)
342 if not self.ignore_old_config:
343 check_for_old_config(self.ipython_dir)
401
344
402 # If the -c flag is given or a file is given to run at the cmd line
345 # print self.extra_args
403 # like "ipython foo.py", normally we exit without starting the main
346 if self.extra_args:
404 # loop. The force_interact config variable allows a user to override
347 self.file_to_run = self.extra_args[0]
405 # this and interact. It is also set by the -i cmd line flag, just
348 # create the shell
406 # like Python.
349 self.init_shell()
407 Global.force_interact = False
350 # and draw the banner
408
351 self.init_banner()
409 # By default always interact by starting the IPython mainloop.
352 # Now a variety of things that happen after the banner is printed.
410 Global.interact = True
353 self.init_gui_pylab()
411
354 self.init_extensions()
412 # No GUI integration by default
355 self.init_code()
413 Global.gui = False
356
414 # Pylab off by default
357 def init_shell(self):
415 Global.pylab = False
358 """initialize the InteractiveShell instance"""
416
417 # Deprecated versions of gui support that used threading, we support
418 # them just for bacwards compatibility as an alternate spelling for
419 # '--gui X'
420 Global.qthread = False
421 Global.q4thread = False
422 Global.wthread = False
423 Global.gthread = False
424
425 def load_file_config(self):
426 if hasattr(self.command_line_config.Global, 'quick'):
427 if self.command_line_config.Global.quick:
428 self.file_config = Config()
429 return
430 super(IPythonApp, self).load_file_config()
431
432 def post_load_file_config(self):
433 if hasattr(self.command_line_config.Global, 'extra_extension'):
434 if not hasattr(self.file_config.Global, 'extensions'):
435 self.file_config.Global.extensions = []
436 self.file_config.Global.extensions.append(
437 self.command_line_config.Global.extra_extension)
438 del self.command_line_config.Global.extra_extension
439
440 def pre_construct(self):
441 config = self.master_config
442
443 if hasattr(config.Global, 'classic'):
444 if config.Global.classic:
445 config.InteractiveShell.cache_size = 0
446 config.PlainTextFormatter.pprint = False
447 config.InteractiveShell.prompt_in1 = '>>> '
448 config.InteractiveShell.prompt_in2 = '... '
449 config.InteractiveShell.prompt_out = ''
450 config.InteractiveShell.separate_in = \
451 config.InteractiveShell.separate_out = \
452 config.InteractiveShell.separate_out2 = ''
453 config.InteractiveShell.colors = 'NoColor'
454 config.InteractiveShell.xmode = 'Plain'
455
456 if hasattr(config.Global, 'nosep'):
457 if config.Global.nosep:
458 config.InteractiveShell.separate_in = \
459 config.InteractiveShell.separate_out = \
460 config.InteractiveShell.separate_out2 = ''
461
462 # if there is code of files to run from the cmd line, don't interact
463 # unless the -i flag (Global.force_interact) is true.
464 code_to_run = config.Global.get('code_to_run','')
465 file_to_run = False
466 if self.extra_args and self.extra_args[0]:
467 file_to_run = True
468 if file_to_run or code_to_run:
469 if not config.Global.force_interact:
470 config.Global.interact = False
471
472 def construct(self):
473 # I am a little hesitant to put these into InteractiveShell itself.
359 # I am a little hesitant to put these into InteractiveShell itself.
474 # But that might be the place for them
360 # But that might be the place for them
475 sys.path.insert(0, '')
361 sys.path.insert(0, '')
476
362
477 # Create an InteractiveShell instance.
363 # Create an InteractiveShell instance.
478 self.shell = TerminalInteractiveShell.instance(config=self.master_config)
479
480 def post_construct(self):
481 """Do actions after construct, but before starting the app."""
482 config = self.master_config
483
484 # shell.display_banner should always be False for the terminal
364 # shell.display_banner should always be False for the terminal
485 # based app, because we call shell.show_banner() by hand below
365 # based app, because we call shell.show_banner() by hand below
486 # so the banner shows *before* all extension loading stuff.
366 # so the banner shows *before* all extension loading stuff.
487 self.shell.display_banner = False
367 self.shell = TerminalInteractiveShell.instance(config=self.config,
488 if config.Global.display_banner and \
368 display_banner=False, profile_dir=self.profile_dir,
489 config.Global.interact:
369 ipython_dir=self.ipython_dir)
490 self.shell.show_banner()
491
370
371 def init_banner(self):
372 """optionally display the banner"""
373 if self.display_banner and self.interact:
374 self.shell.show_banner()
492 # Make sure there is a space below the banner.
375 # Make sure there is a space below the banner.
493 if self.log_level <= logging.INFO: print
376 if self.log_level <= logging.INFO: print
494
377
495 # Now a variety of things that happen after the banner is printed.
496 self._enable_gui_pylab()
497 self._load_extensions()
498 self._run_exec_lines()
499 self._run_exec_files()
500 self._run_cmd_line_code()
501
378
502 def _enable_gui_pylab(self):
379 def init_gui_pylab(self):
503 """Enable GUI event loop integration, taking pylab into account."""
380 """Enable GUI event loop integration, taking pylab into account."""
504 Global = self.master_config.Global
381 gui = self.gui
505
506 # Select which gui to use
507 if Global.gui:
508 gui = Global.gui
509 # The following are deprecated, but there's likely to be a lot of use
510 # of this form out there, so we might as well support it for now. But
511 # the --gui option above takes precedence.
512 elif Global.wthread:
513 gui = inputhook.GUI_WX
514 elif Global.qthread:
515 gui = inputhook.GUI_QT
516 elif Global.gthread:
517 gui = inputhook.GUI_GTK
518 else:
519 gui = None
520
382
521 # Using --pylab will also require gui activation, though which toolkit
383 # Using `pylab` will also require gui activation, though which toolkit
522 # to use may be chosen automatically based on mpl configuration.
384 # to use may be chosen automatically based on mpl configuration.
523 if Global.pylab:
385 if self.pylab:
524 activate = self.shell.enable_pylab
386 activate = self.shell.enable_pylab
525 if Global.pylab == 'auto':
387 if self.pylab == 'auto':
526 gui = None
388 gui = None
527 else:
389 else:
528 gui = Global.pylab
390 gui = self.pylab
529 else:
391 else:
530 # Enable only GUI integration, no pylab
392 # Enable only GUI integration, no pylab
531 activate = inputhook.enable_gui
393 activate = inputhook.enable_gui
532
394
533 if gui or Global.pylab:
395 if gui or self.pylab:
534 try:
396 try:
535 self.log.info("Enabling GUI event loop integration, "
397 self.log.info("Enabling GUI event loop integration, "
536 "toolkit=%s, pylab=%s" % (gui, Global.pylab) )
398 "toolkit=%s, pylab=%s" % (gui, self.pylab) )
537 activate(gui)
399 activate(gui)
538 except:
400 except:
539 self.log.warn("Error in enabling GUI event loop integration:")
401 self.log.warn("Error in enabling GUI event loop integration:")
540 self.shell.showtraceback()
402 self.shell.showtraceback()
541
403
542 def _load_extensions(self):
404 def init_extensions(self):
543 """Load all IPython extensions in Global.extensions.
405 """Load all IPython extensions in IPythonApp.extensions.
544
406
545 This uses the :meth:`ExtensionManager.load_extensions` to load all
407 This uses the :meth:`ExtensionManager.load_extensions` to load all
546 the extensions listed in ``self.master_config.Global.extensions``.
408 the extensions listed in ``self.extensions``.
547 """
409 """
410 if not self.extensions:
411 return
548 try:
412 try:
549 if hasattr(self.master_config.Global, 'extensions'):
413 self.log.debug("Loading IPython extensions...")
550 self.log.debug("Loading IPython extensions...")
414 extensions = self.extensions
551 extensions = self.master_config.Global.extensions
415 for ext in extensions:
552 for ext in extensions:
416 try:
553 try:
417 self.log.info("Loading IPython extension: %s" % ext)
554 self.log.info("Loading IPython extension: %s" % ext)
418 self.shell.extension_manager.load_extension(ext)
555 self.shell.extension_manager.load_extension(ext)
419 except:
556 except:
420 self.log.warn("Error in loading extension: %s" % ext)
557 self.log.warn("Error in loading extension: %s" % ext)
421 self.shell.showtraceback()
558 self.shell.showtraceback()
559 except:
422 except:
560 self.log.warn("Unknown error in loading extensions:")
423 self.log.warn("Unknown error in loading extensions:")
561 self.shell.showtraceback()
424 self.shell.showtraceback()
562
425
426 def init_code(self):
427 """run the pre-flight code, specified via exec_lines"""
428 self._run_exec_lines()
429 self._run_exec_files()
430 self._run_cmd_line_code()
431
563 def _run_exec_lines(self):
432 def _run_exec_lines(self):
564 """Run lines of code in Global.exec_lines in the user's namespace."""
433 """Run lines of code in IPythonApp.exec_lines in the user's namespace."""
434 if not self.exec_lines:
435 return
565 try:
436 try:
566 if hasattr(self.master_config.Global, 'exec_lines'):
437 self.log.debug("Running code from IPythonApp.exec_lines...")
567 self.log.debug("Running code from Global.exec_lines...")
438 for line in self.exec_lines:
568 exec_lines = self.master_config.Global.exec_lines
439 try:
569 for line in exec_lines:
440 self.log.info("Running code in user namespace: %s" %
570 try:
441 line)
571 self.log.info("Running code in user namespace: %s" %
442 self.shell.run_cell(line, store_history=False)
572 line)
443 except:
573 self.shell.run_cell(line, store_history=False)
444 self.log.warn("Error in executing line in user "
574 except:
445 "namespace: %s" % line)
575 self.log.warn("Error in executing line in user "
446 self.shell.showtraceback()
576 "namespace: %s" % line)
577 self.shell.showtraceback()
578 except:
447 except:
579 self.log.warn("Unknown error in handling Global.exec_lines:")
448 self.log.warn("Unknown error in handling IPythonApp.exec_lines:")
580 self.shell.showtraceback()
449 self.shell.showtraceback()
581
450
582 def _exec_file(self, fname):
451 def _exec_file(self, fname):
583 full_filename = filefind(fname, [u'.', self.ipython_dir])
452 full_filename = filefind(fname, [u'.', self.ipython_dir])
584 if os.path.isfile(full_filename):
453 if os.path.isfile(full_filename):
585 if full_filename.endswith(u'.py'):
454 if full_filename.endswith(u'.py'):
586 self.log.info("Running file in user namespace: %s" %
455 self.log.info("Running file in user namespace: %s" %
587 full_filename)
456 full_filename)
588 # Ensure that __file__ is always defined to match Python behavior
457 # Ensure that __file__ is always defined to match Python behavior
589 self.shell.user_ns['__file__'] = fname
458 self.shell.user_ns['__file__'] = fname
590 try:
459 try:
591 self.shell.safe_execfile(full_filename, self.shell.user_ns)
460 self.shell.safe_execfile(full_filename, self.shell.user_ns)
592 finally:
461 finally:
593 del self.shell.user_ns['__file__']
462 del self.shell.user_ns['__file__']
594 elif full_filename.endswith('.ipy'):
463 elif full_filename.endswith('.ipy'):
595 self.log.info("Running file in user namespace: %s" %
464 self.log.info("Running file in user namespace: %s" %
596 full_filename)
465 full_filename)
597 self.shell.safe_execfile_ipy(full_filename)
466 self.shell.safe_execfile_ipy(full_filename)
598 else:
467 else:
599 self.log.warn("File does not have a .py or .ipy extension: <%s>"
468 self.log.warn("File does not have a .py or .ipy extension: <%s>"
600 % full_filename)
469 % full_filename)
470
601 def _run_exec_files(self):
471 def _run_exec_files(self):
472 """Run files from IPythonApp.exec_files"""
473 if not self.exec_files:
474 return
475
476 self.log.debug("Running files in IPythonApp.exec_files...")
602 try:
477 try:
603 if hasattr(self.master_config.Global, 'exec_files'):
478 for fname in self.exec_files:
604 self.log.debug("Running files in Global.exec_files...")
479 self._exec_file(fname)
605 exec_files = self.master_config.Global.exec_files
606 for fname in exec_files:
607 self._exec_file(fname)
608 except:
480 except:
609 self.log.warn("Unknown error in handling Global.exec_files:")
481 self.log.warn("Unknown error in handling IPythonApp.exec_files:")
610 self.shell.showtraceback()
482 self.shell.showtraceback()
611
483
612 def _run_cmd_line_code(self):
484 def _run_cmd_line_code(self):
613 if hasattr(self.master_config.Global, 'code_to_run'):
485 """Run code or file specified at the command-line"""
614 line = self.master_config.Global.code_to_run
486 if self.code_to_run:
487 line = self.code_to_run
615 try:
488 try:
616 self.log.info("Running code given at command line (-c): %s" %
489 self.log.info("Running code given at command line (c=): %s" %
617 line)
490 line)
618 self.shell.run_cell(line, store_history=False)
491 self.shell.run_cell(line, store_history=False)
619 except:
492 except:
620 self.log.warn("Error in executing line in user namespace: %s" %
493 self.log.warn("Error in executing line in user namespace: %s" %
621 line)
494 line)
622 self.shell.showtraceback()
495 self.shell.showtraceback()
623 return
496
624 # Like Python itself, ignore the second if the first of these is present
497 # Like Python itself, ignore the second if the first of these is present
625 try:
498 elif self.file_to_run:
626 fname = self.extra_args[0]
499 fname = self.file_to_run
627 except:
628 pass
629 else:
630 try:
500 try:
631 self._exec_file(fname)
501 self._exec_file(fname)
632 except:
502 except:
633 self.log.warn("Error in executing file in user namespace: %s" %
503 self.log.warn("Error in executing file in user namespace: %s" %
634 fname)
504 fname)
635 self.shell.showtraceback()
505 self.shell.showtraceback()
636
506
637 def start_app(self):
507
638 if not getattr(self.master_config.Global, 'ignore_old_config', False):
508 def start(self):
639 check_for_old_config(self.ipython_dir)
509 # perform any prexec steps:
640 if self.master_config.Global.interact:
510 if self.interact:
641 self.log.debug("Starting IPython's mainloop...")
511 self.log.debug("Starting IPython's mainloop...")
642 self.shell.mainloop()
512 self.shell.mainloop()
643 else:
513 else:
644 self.log.debug("IPython not interactive, start_app is no-op...")
514 self.log.debug("IPython not interactive...")
645
515
646
516
647 def load_default_config(ipython_dir=None):
517 def load_default_config(ipython_dir=None):
648 """Load the default config file from the default ipython_dir.
518 """Load the default config file from the default ipython_dir.
649
519
650 This is useful for embedded shells.
520 This is useful for embedded shells.
651 """
521 """
652 if ipython_dir is None:
522 if ipython_dir is None:
653 ipython_dir = get_ipython_dir()
523 ipython_dir = get_ipython_dir()
654 cl = PyFileConfigLoader(default_config_file_name, ipython_dir)
524 profile_dir = os.path.join(ipython_dir, 'profile_default')
525 cl = PyFileConfigLoader(default_config_file_name, profile_dir)
655 config = cl.load_config()
526 config = cl.load_config()
656 return config
527 return config
657
528
658
529
659 def launch_new_instance():
530 def launch_new_instance():
660 """Create and run a full blown IPython instance"""
531 """Create and run a full blown IPython instance"""
661 app = IPythonApp()
532 app = IPythonApp()
533 app.initialize()
534 # print app.config
535 # print app.profile_dir.location
662 app.start()
536 app.start()
663
537
664
538
665 if __name__ == '__main__':
539 if __name__ == '__main__':
666 launch_new_instance()
540 launch_new_instance()
@@ -1,442 +1,440
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 """Module for interactively running scripts.
2 """Module for interactively running scripts.
3
3
4 This module implements classes for interactively running scripts written for
4 This module implements classes for interactively running scripts written for
5 any system with a prompt which can be matched by a regexp suitable for
5 any system with a prompt which can be matched by a regexp suitable for
6 pexpect. It can be used to run as if they had been typed up interactively, an
6 pexpect. It can be used to run as if they had been typed up interactively, an
7 arbitrary series of commands for the target system.
7 arbitrary series of commands for the target system.
8
8
9 The module includes classes ready for IPython (with the default prompts),
9 The module includes classes ready for IPython (with the default prompts),
10 plain Python and SAGE, but making a new one is trivial. To see how to use it,
10 plain Python and SAGE, but making a new one is trivial. To see how to use it,
11 simply run the module as a script:
11 simply run the module as a script:
12
12
13 ./irunner.py --help
13 ./irunner.py --help
14
14
15
15
16 This is an extension of Ken Schutte <kschutte-AT-csail.mit.edu>'s script
16 This is an extension of Ken Schutte <kschutte-AT-csail.mit.edu>'s script
17 contributed on the ipython-user list:
17 contributed on the ipython-user list:
18
18
19 http://scipy.net/pipermail/ipython-user/2006-May/001705.html
19 http://scipy.net/pipermail/ipython-user/2006-May/001705.html
20
20
21
21
22 NOTES:
22 NOTES:
23
23
24 - This module requires pexpect, available in most linux distros, or which can
24 - This module requires pexpect, available in most linux distros, or which can
25 be downloaded from
25 be downloaded from
26
26
27 http://pexpect.sourceforge.net
27 http://pexpect.sourceforge.net
28
28
29 - Because pexpect only works under Unix or Windows-Cygwin, this has the same
29 - Because pexpect only works under Unix or Windows-Cygwin, this has the same
30 limitations. This means that it will NOT work under native windows Python.
30 limitations. This means that it will NOT work under native windows Python.
31 """
31 """
32
32
33 # Stdlib imports
33 # Stdlib imports
34 import optparse
34 import optparse
35 import os
35 import os
36 import sys
36 import sys
37
37
38 # Third-party modules.
38 # Third-party modules.
39 import pexpect
39 import pexpect
40
40
41 # Global usage strings, to avoid indentation issues when typing it below.
41 # Global usage strings, to avoid indentation issues when typing it below.
42 USAGE = """
42 USAGE = """
43 Interactive script runner, type: %s
43 Interactive script runner, type: %s
44
44
45 runner [opts] script_name
45 runner [opts] script_name
46 """
46 """
47
47
48 def pexpect_monkeypatch():
48 def pexpect_monkeypatch():
49 """Patch pexpect to prevent unhandled exceptions at VM teardown.
49 """Patch pexpect to prevent unhandled exceptions at VM teardown.
50
50
51 Calling this function will monkeypatch the pexpect.spawn class and modify
51 Calling this function will monkeypatch the pexpect.spawn class and modify
52 its __del__ method to make it more robust in the face of failures that can
52 its __del__ method to make it more robust in the face of failures that can
53 occur if it is called when the Python VM is shutting down.
53 occur if it is called when the Python VM is shutting down.
54
54
55 Since Python may fire __del__ methods arbitrarily late, it's possible for
55 Since Python may fire __del__ methods arbitrarily late, it's possible for
56 them to execute during the teardown of the Python VM itself. At this
56 them to execute during the teardown of the Python VM itself. At this
57 point, various builtin modules have been reset to None. Thus, the call to
57 point, various builtin modules have been reset to None. Thus, the call to
58 self.close() will trigger an exception because it tries to call os.close(),
58 self.close() will trigger an exception because it tries to call os.close(),
59 and os is now None.
59 and os is now None.
60 """
60 """
61
61
62 if pexpect.__version__[:3] >= '2.2':
62 if pexpect.__version__[:3] >= '2.2':
63 # No need to patch, fix is already the upstream version.
63 # No need to patch, fix is already the upstream version.
64 return
64 return
65
65
66 def __del__(self):
66 def __del__(self):
67 """This makes sure that no system resources are left open.
67 """This makes sure that no system resources are left open.
68 Python only garbage collects Python objects. OS file descriptors
68 Python only garbage collects Python objects. OS file descriptors
69 are not Python objects, so they must be handled explicitly.
69 are not Python objects, so they must be handled explicitly.
70 If the child file descriptor was opened outside of this class
70 If the child file descriptor was opened outside of this class
71 (passed to the constructor) then this does not close it.
71 (passed to the constructor) then this does not close it.
72 """
72 """
73 if not self.closed:
73 if not self.closed:
74 try:
74 try:
75 self.close()
75 self.close()
76 except AttributeError:
76 except AttributeError:
77 pass
77 pass
78
78
79 pexpect.spawn.__del__ = __del__
79 pexpect.spawn.__del__ = __del__
80
80
81 pexpect_monkeypatch()
81 pexpect_monkeypatch()
82
82
83 # The generic runner class
83 # The generic runner class
84 class InteractiveRunner(object):
84 class InteractiveRunner(object):
85 """Class to run a sequence of commands through an interactive program."""
85 """Class to run a sequence of commands through an interactive program."""
86
86
87 def __init__(self,program,prompts,args=None,out=sys.stdout,echo=True):
87 def __init__(self,program,prompts,args=None,out=sys.stdout,echo=True):
88 """Construct a runner.
88 """Construct a runner.
89
89
90 Inputs:
90 Inputs:
91
91
92 - program: command to execute the given program.
92 - program: command to execute the given program.
93
93
94 - prompts: a list of patterns to match as valid prompts, in the
94 - prompts: a list of patterns to match as valid prompts, in the
95 format used by pexpect. This basically means that it can be either
95 format used by pexpect. This basically means that it can be either
96 a string (to be compiled as a regular expression) or a list of such
96 a string (to be compiled as a regular expression) or a list of such
97 (it must be a true list, as pexpect does type checks).
97 (it must be a true list, as pexpect does type checks).
98
98
99 If more than one prompt is given, the first is treated as the main
99 If more than one prompt is given, the first is treated as the main
100 program prompt and the others as 'continuation' prompts, like
100 program prompt and the others as 'continuation' prompts, like
101 python's. This means that blank lines in the input source are
101 python's. This means that blank lines in the input source are
102 ommitted when the first prompt is matched, but are NOT ommitted when
102 ommitted when the first prompt is matched, but are NOT ommitted when
103 the continuation one matches, since this is how python signals the
103 the continuation one matches, since this is how python signals the
104 end of multiline input interactively.
104 end of multiline input interactively.
105
105
106 Optional inputs:
106 Optional inputs:
107
107
108 - args(None): optional list of strings to pass as arguments to the
108 - args(None): optional list of strings to pass as arguments to the
109 child program.
109 child program.
110
110
111 - out(sys.stdout): if given, an output stream to be used when writing
111 - out(sys.stdout): if given, an output stream to be used when writing
112 output. The only requirement is that it must have a .write() method.
112 output. The only requirement is that it must have a .write() method.
113
113
114 Public members not parameterized in the constructor:
114 Public members not parameterized in the constructor:
115
115
116 - delaybeforesend(0): Newer versions of pexpect have a delay before
116 - delaybeforesend(0): Newer versions of pexpect have a delay before
117 sending each new input. For our purposes here, it's typically best
117 sending each new input. For our purposes here, it's typically best
118 to just set this to zero, but if you encounter reliability problems
118 to just set this to zero, but if you encounter reliability problems
119 or want an interactive run to pause briefly at each prompt, just
119 or want an interactive run to pause briefly at each prompt, just
120 increase this value (it is measured in seconds). Note that this
120 increase this value (it is measured in seconds). Note that this
121 variable is not honored at all by older versions of pexpect.
121 variable is not honored at all by older versions of pexpect.
122 """
122 """
123
123
124 self.program = program
124 self.program = program
125 self.prompts = prompts
125 self.prompts = prompts
126 if args is None: args = []
126 if args is None: args = []
127 self.args = args
127 self.args = args
128 self.out = out
128 self.out = out
129 self.echo = echo
129 self.echo = echo
130 # Other public members which we don't make as parameters, but which
130 # Other public members which we don't make as parameters, but which
131 # users may occasionally want to tweak
131 # users may occasionally want to tweak
132 self.delaybeforesend = 0
132 self.delaybeforesend = 0
133
133
134 # Create child process and hold on to it so we don't have to re-create
134 # Create child process and hold on to it so we don't have to re-create
135 # for every single execution call
135 # for every single execution call
136 c = self.child = pexpect.spawn(self.program,self.args,timeout=None)
136 c = self.child = pexpect.spawn(self.program,self.args,timeout=None)
137 c.delaybeforesend = self.delaybeforesend
137 c.delaybeforesend = self.delaybeforesend
138 # pexpect hard-codes the terminal size as (24,80) (rows,columns).
138 # pexpect hard-codes the terminal size as (24,80) (rows,columns).
139 # This causes problems because any line longer than 80 characters gets
139 # This causes problems because any line longer than 80 characters gets
140 # completely overwrapped on the printed outptut (even though
140 # completely overwrapped on the printed outptut (even though
141 # internally the code runs fine). We reset this to 99 rows X 200
141 # internally the code runs fine). We reset this to 99 rows X 200
142 # columns (arbitrarily chosen), which should avoid problems in all
142 # columns (arbitrarily chosen), which should avoid problems in all
143 # reasonable cases.
143 # reasonable cases.
144 c.setwinsize(99,200)
144 c.setwinsize(99,200)
145
145
146 def close(self):
146 def close(self):
147 """close child process"""
147 """close child process"""
148
148
149 self.child.close()
149 self.child.close()
150
150
151 def run_file(self,fname,interact=False,get_output=False):
151 def run_file(self,fname,interact=False,get_output=False):
152 """Run the given file interactively.
152 """Run the given file interactively.
153
153
154 Inputs:
154 Inputs:
155
155
156 -fname: name of the file to execute.
156 -fname: name of the file to execute.
157
157
158 See the run_source docstring for the meaning of the optional
158 See the run_source docstring for the meaning of the optional
159 arguments."""
159 arguments."""
160
160
161 fobj = open(fname,'r')
161 fobj = open(fname,'r')
162 try:
162 try:
163 out = self.run_source(fobj,interact,get_output)
163 out = self.run_source(fobj,interact,get_output)
164 finally:
164 finally:
165 fobj.close()
165 fobj.close()
166 if get_output:
166 if get_output:
167 return out
167 return out
168
168
169 def run_source(self,source,interact=False,get_output=False):
169 def run_source(self,source,interact=False,get_output=False):
170 """Run the given source code interactively.
170 """Run the given source code interactively.
171
171
172 Inputs:
172 Inputs:
173
173
174 - source: a string of code to be executed, or an open file object we
174 - source: a string of code to be executed, or an open file object we
175 can iterate over.
175 can iterate over.
176
176
177 Optional inputs:
177 Optional inputs:
178
178
179 - interact(False): if true, start to interact with the running
179 - interact(False): if true, start to interact with the running
180 program at the end of the script. Otherwise, just exit.
180 program at the end of the script. Otherwise, just exit.
181
181
182 - get_output(False): if true, capture the output of the child process
182 - get_output(False): if true, capture the output of the child process
183 (filtering the input commands out) and return it as a string.
183 (filtering the input commands out) and return it as a string.
184
184
185 Returns:
185 Returns:
186 A string containing the process output, but only if requested.
186 A string containing the process output, but only if requested.
187 """
187 """
188
188
189 # if the source is a string, chop it up in lines so we can iterate
189 # if the source is a string, chop it up in lines so we can iterate
190 # over it just as if it were an open file.
190 # over it just as if it were an open file.
191 if not isinstance(source,file):
191 if not isinstance(source,file):
192 source = source.splitlines(True)
192 source = source.splitlines(True)
193
193
194 if self.echo:
194 if self.echo:
195 # normalize all strings we write to use the native OS line
195 # normalize all strings we write to use the native OS line
196 # separators.
196 # separators.
197 linesep = os.linesep
197 linesep = os.linesep
198 stdwrite = self.out.write
198 stdwrite = self.out.write
199 write = lambda s: stdwrite(s.replace('\r\n',linesep))
199 write = lambda s: stdwrite(s.replace('\r\n',linesep))
200 else:
200 else:
201 # Quiet mode, all writes are no-ops
201 # Quiet mode, all writes are no-ops
202 write = lambda s: None
202 write = lambda s: None
203
203
204 c = self.child
204 c = self.child
205 prompts = c.compile_pattern_list(self.prompts)
205 prompts = c.compile_pattern_list(self.prompts)
206 prompt_idx = c.expect_list(prompts)
206 prompt_idx = c.expect_list(prompts)
207
207
208 # Flag whether the script ends normally or not, to know whether we can
208 # Flag whether the script ends normally or not, to know whether we can
209 # do anything further with the underlying process.
209 # do anything further with the underlying process.
210 end_normal = True
210 end_normal = True
211
211
212 # If the output was requested, store it in a list for return at the end
212 # If the output was requested, store it in a list for return at the end
213 if get_output:
213 if get_output:
214 output = []
214 output = []
215 store_output = output.append
215 store_output = output.append
216
216
217 for cmd in source:
217 for cmd in source:
218 # skip blank lines for all matches to the 'main' prompt, while the
218 # skip blank lines for all matches to the 'main' prompt, while the
219 # secondary prompts do not
219 # secondary prompts do not
220 if prompt_idx==0 and \
220 if prompt_idx==0 and \
221 (cmd.isspace() or cmd.lstrip().startswith('#')):
221 (cmd.isspace() or cmd.lstrip().startswith('#')):
222 write(cmd)
222 write(cmd)
223 continue
223 continue
224
224
225 # write('AFTER: '+c.after) # dbg
225 # write('AFTER: '+c.after) # dbg
226 write(c.after)
226 write(c.after)
227 c.send(cmd)
227 c.send(cmd)
228 try:
228 try:
229 prompt_idx = c.expect_list(prompts)
229 prompt_idx = c.expect_list(prompts)
230 except pexpect.EOF:
230 except pexpect.EOF:
231 # this will happen if the child dies unexpectedly
231 # this will happen if the child dies unexpectedly
232 write(c.before)
232 write(c.before)
233 end_normal = False
233 end_normal = False
234 break
234 break
235
235
236 write(c.before)
236 write(c.before)
237
237
238 # With an echoing process, the output we get in c.before contains
238 # With an echoing process, the output we get in c.before contains
239 # the command sent, a newline, and then the actual process output
239 # the command sent, a newline, and then the actual process output
240 if get_output:
240 if get_output:
241 store_output(c.before[len(cmd+'\n'):])
241 store_output(c.before[len(cmd+'\n'):])
242 #write('CMD: <<%s>>' % cmd) # dbg
242 #write('CMD: <<%s>>' % cmd) # dbg
243 #write('OUTPUT: <<%s>>' % output[-1]) # dbg
243 #write('OUTPUT: <<%s>>' % output[-1]) # dbg
244
244
245 self.out.flush()
245 self.out.flush()
246 if end_normal:
246 if end_normal:
247 if interact:
247 if interact:
248 c.send('\n')
248 c.send('\n')
249 print '<< Starting interactive mode >>',
249 print '<< Starting interactive mode >>',
250 try:
250 try:
251 c.interact()
251 c.interact()
252 except OSError:
252 except OSError:
253 # This is what fires when the child stops. Simply print a
253 # This is what fires when the child stops. Simply print a
254 # newline so the system prompt is aligned. The extra
254 # newline so the system prompt is aligned. The extra
255 # space is there to make sure it gets printed, otherwise
255 # space is there to make sure it gets printed, otherwise
256 # OS buffering sometimes just suppresses it.
256 # OS buffering sometimes just suppresses it.
257 write(' \n')
257 write(' \n')
258 self.out.flush()
258 self.out.flush()
259 else:
259 else:
260 if interact:
260 if interact:
261 e="Further interaction is not possible: child process is dead."
261 e="Further interaction is not possible: child process is dead."
262 print >> sys.stderr, e
262 print >> sys.stderr, e
263
263
264 # Leave the child ready for more input later on, otherwise select just
264 # Leave the child ready for more input later on, otherwise select just
265 # hangs on the second invocation.
265 # hangs on the second invocation.
266 if c.isalive():
266 if c.isalive():
267 c.send('\n')
267 c.send('\n')
268
268
269 # Return any requested output
269 # Return any requested output
270 if get_output:
270 if get_output:
271 return ''.join(output)
271 return ''.join(output)
272
272
273 def main(self,argv=None):
273 def main(self,argv=None):
274 """Run as a command-line script."""
274 """Run as a command-line script."""
275
275
276 parser = optparse.OptionParser(usage=USAGE % self.__class__.__name__)
276 parser = optparse.OptionParser(usage=USAGE % self.__class__.__name__)
277 newopt = parser.add_option
277 newopt = parser.add_option
278 newopt('-i','--interact',action='store_true',default=False,
278 newopt('-i','--interact',action='store_true',default=False,
279 help='Interact with the program after the script is run.')
279 help='Interact with the program after the script is run.')
280
280
281 opts,args = parser.parse_args(argv)
281 opts,args = parser.parse_args(argv)
282
282
283 if len(args) != 1:
283 if len(args) != 1:
284 print >> sys.stderr,"You must supply exactly one file to run."
284 print >> sys.stderr,"You must supply exactly one file to run."
285 sys.exit(1)
285 sys.exit(1)
286
286
287 self.run_file(args[0],opts.interact)
287 self.run_file(args[0],opts.interact)
288
288
289
289
290 # Specific runners for particular programs
290 # Specific runners for particular programs
291 class IPythonRunner(InteractiveRunner):
291 class IPythonRunner(InteractiveRunner):
292 """Interactive IPython runner.
292 """Interactive IPython runner.
293
293
294 This initalizes IPython in 'nocolor' mode for simplicity. This lets us
294 This initalizes IPython in 'nocolor' mode for simplicity. This lets us
295 avoid having to write a regexp that matches ANSI sequences, though pexpect
295 avoid having to write a regexp that matches ANSI sequences, though pexpect
296 does support them. If anyone contributes patches for ANSI color support,
296 does support them. If anyone contributes patches for ANSI color support,
297 they will be welcome.
297 they will be welcome.
298
298
299 It also sets the prompts manually, since the prompt regexps for
299 It also sets the prompts manually, since the prompt regexps for
300 pexpect need to be matched to the actual prompts, so user-customized
300 pexpect need to be matched to the actual prompts, so user-customized
301 prompts would break this.
301 prompts would break this.
302 """
302 """
303
303
304 def __init__(self,program = 'ipython',args=None,out=sys.stdout,echo=True):
304 def __init__(self,program = 'ipython',args=None,out=sys.stdout,echo=True):
305 """New runner, optionally passing the ipython command to use."""
305 """New runner, optionally passing the ipython command to use."""
306
306
307 args0 = ['--colors','NoColor',
307 args0 = ['colors=NoColor',
308 '-pi1','In [\\#]: ',
309 '-pi2',' .\\D.: ',
310 '--no-term-title',
308 '--no-term-title',
311 '--no-autoindent']
309 '--no-autoindent']
312 if args is None: args = args0
310 if args is None: args = args0
313 else: args = args0 + args
311 else: args = args0 + args
314 prompts = [r'In \[\d+\]: ',r' \.*: ']
312 prompts = [r'In \[\d+\]: ',r' \.*: ']
315 InteractiveRunner.__init__(self,program,prompts,args,out,echo)
313 InteractiveRunner.__init__(self,program,prompts,args,out,echo)
316
314
317
315
318 class PythonRunner(InteractiveRunner):
316 class PythonRunner(InteractiveRunner):
319 """Interactive Python runner."""
317 """Interactive Python runner."""
320
318
321 def __init__(self,program='python',args=None,out=sys.stdout,echo=True):
319 def __init__(self,program='python',args=None,out=sys.stdout,echo=True):
322 """New runner, optionally passing the python command to use."""
320 """New runner, optionally passing the python command to use."""
323
321
324 prompts = [r'>>> ',r'\.\.\. ']
322 prompts = [r'>>> ',r'\.\.\. ']
325 InteractiveRunner.__init__(self,program,prompts,args,out,echo)
323 InteractiveRunner.__init__(self,program,prompts,args,out,echo)
326
324
327
325
328 class SAGERunner(InteractiveRunner):
326 class SAGERunner(InteractiveRunner):
329 """Interactive SAGE runner.
327 """Interactive SAGE runner.
330
328
331 WARNING: this runner only works if you manually configure your SAGE copy
329 WARNING: this runner only works if you manually configure your SAGE copy
332 to use 'colors NoColor' in the ipythonrc config file, since currently the
330 to use 'colors NoColor' in the ipythonrc config file, since currently the
333 prompt matching regexp does not identify color sequences."""
331 prompt matching regexp does not identify color sequences."""
334
332
335 def __init__(self,program='sage',args=None,out=sys.stdout,echo=True):
333 def __init__(self,program='sage',args=None,out=sys.stdout,echo=True):
336 """New runner, optionally passing the sage command to use."""
334 """New runner, optionally passing the sage command to use."""
337
335
338 prompts = ['sage: ',r'\s*\.\.\. ']
336 prompts = ['sage: ',r'\s*\.\.\. ']
339 InteractiveRunner.__init__(self,program,prompts,args,out,echo)
337 InteractiveRunner.__init__(self,program,prompts,args,out,echo)
340
338
341
339
342 class RunnerFactory(object):
340 class RunnerFactory(object):
343 """Code runner factory.
341 """Code runner factory.
344
342
345 This class provides an IPython code runner, but enforces that only one
343 This class provides an IPython code runner, but enforces that only one
346 runner is ever instantiated. The runner is created based on the extension
344 runner is ever instantiated. The runner is created based on the extension
347 of the first file to run, and it raises an exception if a runner is later
345 of the first file to run, and it raises an exception if a runner is later
348 requested for a different extension type.
346 requested for a different extension type.
349
347
350 This ensures that we don't generate example files for doctest with a mix of
348 This ensures that we don't generate example files for doctest with a mix of
351 python and ipython syntax.
349 python and ipython syntax.
352 """
350 """
353
351
354 def __init__(self,out=sys.stdout):
352 def __init__(self,out=sys.stdout):
355 """Instantiate a code runner."""
353 """Instantiate a code runner."""
356
354
357 self.out = out
355 self.out = out
358 self.runner = None
356 self.runner = None
359 self.runnerClass = None
357 self.runnerClass = None
360
358
361 def _makeRunner(self,runnerClass):
359 def _makeRunner(self,runnerClass):
362 self.runnerClass = runnerClass
360 self.runnerClass = runnerClass
363 self.runner = runnerClass(out=self.out)
361 self.runner = runnerClass(out=self.out)
364 return self.runner
362 return self.runner
365
363
366 def __call__(self,fname):
364 def __call__(self,fname):
367 """Return a runner for the given filename."""
365 """Return a runner for the given filename."""
368
366
369 if fname.endswith('.py'):
367 if fname.endswith('.py'):
370 runnerClass = PythonRunner
368 runnerClass = PythonRunner
371 elif fname.endswith('.ipy'):
369 elif fname.endswith('.ipy'):
372 runnerClass = IPythonRunner
370 runnerClass = IPythonRunner
373 else:
371 else:
374 raise ValueError('Unknown file type for Runner: %r' % fname)
372 raise ValueError('Unknown file type for Runner: %r' % fname)
375
373
376 if self.runner is None:
374 if self.runner is None:
377 return self._makeRunner(runnerClass)
375 return self._makeRunner(runnerClass)
378 else:
376 else:
379 if runnerClass==self.runnerClass:
377 if runnerClass==self.runnerClass:
380 return self.runner
378 return self.runner
381 else:
379 else:
382 e='A runner of type %r can not run file %r' % \
380 e='A runner of type %r can not run file %r' % \
383 (self.runnerClass,fname)
381 (self.runnerClass,fname)
384 raise ValueError(e)
382 raise ValueError(e)
385
383
386
384
387 # Global usage string, to avoid indentation issues if typed in a function def.
385 # Global usage string, to avoid indentation issues if typed in a function def.
388 MAIN_USAGE = """
386 MAIN_USAGE = """
389 %prog [options] file_to_run
387 %prog [options] file_to_run
390
388
391 This is an interface to the various interactive runners available in this
389 This is an interface to the various interactive runners available in this
392 module. If you want to pass specific options to one of the runners, you need
390 module. If you want to pass specific options to one of the runners, you need
393 to first terminate the main options with a '--', and then provide the runner's
391 to first terminate the main options with a '--', and then provide the runner's
394 options. For example:
392 options. For example:
395
393
396 irunner.py --python -- --help
394 irunner.py --python -- --help
397
395
398 will pass --help to the python runner. Similarly,
396 will pass --help to the python runner. Similarly,
399
397
400 irunner.py --ipython -- --interact script.ipy
398 irunner.py --ipython -- --interact script.ipy
401
399
402 will run the script.ipy file under the IPython runner, and then will start to
400 will run the script.ipy file under the IPython runner, and then will start to
403 interact with IPython at the end of the script (instead of exiting).
401 interact with IPython at the end of the script (instead of exiting).
404
402
405 The already implemented runners are listed below; adding one for a new program
403 The already implemented runners are listed below; adding one for a new program
406 is a trivial task, see the source for examples.
404 is a trivial task, see the source for examples.
407
405
408 WARNING: the SAGE runner only works if you manually configure your SAGE copy
406 WARNING: the SAGE runner only works if you manually configure your SAGE copy
409 to use 'colors NoColor' in the ipythonrc config file, since currently the
407 to use 'colors NoColor' in the ipythonrc config file, since currently the
410 prompt matching regexp does not identify color sequences.
408 prompt matching regexp does not identify color sequences.
411 """
409 """
412
410
413 def main():
411 def main():
414 """Run as a command-line script."""
412 """Run as a command-line script."""
415
413
416 parser = optparse.OptionParser(usage=MAIN_USAGE)
414 parser = optparse.OptionParser(usage=MAIN_USAGE)
417 newopt = parser.add_option
415 newopt = parser.add_option
418 parser.set_defaults(mode='ipython')
416 parser.set_defaults(mode='ipython')
419 newopt('--ipython',action='store_const',dest='mode',const='ipython',
417 newopt('--ipython',action='store_const',dest='mode',const='ipython',
420 help='IPython interactive runner (default).')
418 help='IPython interactive runner (default).')
421 newopt('--python',action='store_const',dest='mode',const='python',
419 newopt('--python',action='store_const',dest='mode',const='python',
422 help='Python interactive runner.')
420 help='Python interactive runner.')
423 newopt('--sage',action='store_const',dest='mode',const='sage',
421 newopt('--sage',action='store_const',dest='mode',const='sage',
424 help='SAGE interactive runner.')
422 help='SAGE interactive runner.')
425
423
426 opts,args = parser.parse_args()
424 opts,args = parser.parse_args()
427 runners = dict(ipython=IPythonRunner,
425 runners = dict(ipython=IPythonRunner,
428 python=PythonRunner,
426 python=PythonRunner,
429 sage=SAGERunner)
427 sage=SAGERunner)
430
428
431 try:
429 try:
432 ext = os.path.splitext(args[0])[-1]
430 ext = os.path.splitext(args[0])[-1]
433 except IndexError:
431 except IndexError:
434 ext = ''
432 ext = ''
435 modes = {'.ipy':'ipython',
433 modes = {'.ipy':'ipython',
436 '.py':'python',
434 '.py':'python',
437 '.sage':'sage'}
435 '.sage':'sage'}
438 mode = modes.get(ext,opts.mode)
436 mode = modes.get(ext,opts.mode)
439 runners[mode]().main(args)
437 runners[mode]().main(args)
440
438
441 if __name__ == '__main__':
439 if __name__ == '__main__':
442 main()
440 main()
@@ -1,280 +1,280
1 """Generic testing tools that do NOT depend on Twisted.
1 """Generic testing tools that do NOT depend on Twisted.
2
2
3 In particular, this module exposes a set of top-level assert* functions that
3 In particular, this module exposes a set of top-level assert* functions that
4 can be used in place of nose.tools.assert* in method generators (the ones in
4 can be used in place of nose.tools.assert* in method generators (the ones in
5 nose can not, at least as of nose 0.10.4).
5 nose can not, at least as of nose 0.10.4).
6
6
7 Note: our testing package contains testing.util, which does depend on Twisted
7 Note: our testing package contains testing.util, which does depend on Twisted
8 and provides utilities for tests that manage Deferreds. All testing support
8 and provides utilities for tests that manage Deferreds. All testing support
9 tools that only depend on nose, IPython or the standard library should go here
9 tools that only depend on nose, IPython or the standard library should go here
10 instead.
10 instead.
11
11
12
12
13 Authors
13 Authors
14 -------
14 -------
15 - Fernando Perez <Fernando.Perez@berkeley.edu>
15 - Fernando Perez <Fernando.Perez@berkeley.edu>
16 """
16 """
17
17
18 from __future__ import absolute_import
18 from __future__ import absolute_import
19
19
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21 # Copyright (C) 2009 The IPython Development Team
21 # Copyright (C) 2009 The IPython Development Team
22 #
22 #
23 # Distributed under the terms of the BSD License. The full license is in
23 # Distributed under the terms of the BSD License. The full license is in
24 # the file COPYING, distributed as part of this software.
24 # the file COPYING, distributed as part of this software.
25 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
26
26
27 #-----------------------------------------------------------------------------
27 #-----------------------------------------------------------------------------
28 # Imports
28 # Imports
29 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
30
30
31 import os
31 import os
32 import re
32 import re
33 import sys
33 import sys
34
34
35 try:
35 try:
36 # These tools are used by parts of the runtime, so we make the nose
36 # These tools are used by parts of the runtime, so we make the nose
37 # dependency optional at this point. Nose is a hard dependency to run the
37 # dependency optional at this point. Nose is a hard dependency to run the
38 # test suite, but NOT to use ipython itself.
38 # test suite, but NOT to use ipython itself.
39 import nose.tools as nt
39 import nose.tools as nt
40 has_nose = True
40 has_nose = True
41 except ImportError:
41 except ImportError:
42 has_nose = False
42 has_nose = False
43
43
44 from IPython.config.loader import Config
44 from IPython.config.loader import Config
45 from IPython.utils.process import find_cmd, getoutputerror
45 from IPython.utils.process import find_cmd, getoutputerror
46 from IPython.utils.text import list_strings
46 from IPython.utils.text import list_strings
47 from IPython.utils.io import temp_pyfile
47 from IPython.utils.io import temp_pyfile
48
48
49 from . import decorators as dec
49 from . import decorators as dec
50 from . import skipdoctest
50 from . import skipdoctest
51
51
52 #-----------------------------------------------------------------------------
52 #-----------------------------------------------------------------------------
53 # Globals
53 # Globals
54 #-----------------------------------------------------------------------------
54 #-----------------------------------------------------------------------------
55
55
56 # Make a bunch of nose.tools assert wrappers that can be used in test
56 # Make a bunch of nose.tools assert wrappers that can be used in test
57 # generators. This will expose an assert* function for each one in nose.tools.
57 # generators. This will expose an assert* function for each one in nose.tools.
58
58
59 _tpl = """
59 _tpl = """
60 def %(name)s(*a,**kw):
60 def %(name)s(*a,**kw):
61 return nt.%(name)s(*a,**kw)
61 return nt.%(name)s(*a,**kw)
62 """
62 """
63
63
64 if has_nose:
64 if has_nose:
65 for _x in [a for a in dir(nt) if a.startswith('assert')]:
65 for _x in [a for a in dir(nt) if a.startswith('assert')]:
66 exec _tpl % dict(name=_x)
66 exec _tpl % dict(name=_x)
67
67
68 #-----------------------------------------------------------------------------
68 #-----------------------------------------------------------------------------
69 # Functions and classes
69 # Functions and classes
70 #-----------------------------------------------------------------------------
70 #-----------------------------------------------------------------------------
71
71
72 # The docstring for full_path doctests differently on win32 (different path
72 # The docstring for full_path doctests differently on win32 (different path
73 # separator) so just skip the doctest there. The example remains informative.
73 # separator) so just skip the doctest there. The example remains informative.
74 doctest_deco = skipdoctest.skip_doctest if sys.platform == 'win32' else dec.null_deco
74 doctest_deco = skipdoctest.skip_doctest if sys.platform == 'win32' else dec.null_deco
75
75
76 @doctest_deco
76 @doctest_deco
77 def full_path(startPath,files):
77 def full_path(startPath,files):
78 """Make full paths for all the listed files, based on startPath.
78 """Make full paths for all the listed files, based on startPath.
79
79
80 Only the base part of startPath is kept, since this routine is typically
80 Only the base part of startPath is kept, since this routine is typically
81 used with a script's __file__ variable as startPath. The base of startPath
81 used with a script's __file__ variable as startPath. The base of startPath
82 is then prepended to all the listed files, forming the output list.
82 is then prepended to all the listed files, forming the output list.
83
83
84 Parameters
84 Parameters
85 ----------
85 ----------
86 startPath : string
86 startPath : string
87 Initial path to use as the base for the results. This path is split
87 Initial path to use as the base for the results. This path is split
88 using os.path.split() and only its first component is kept.
88 using os.path.split() and only its first component is kept.
89
89
90 files : string or list
90 files : string or list
91 One or more files.
91 One or more files.
92
92
93 Examples
93 Examples
94 --------
94 --------
95
95
96 >>> full_path('/foo/bar.py',['a.txt','b.txt'])
96 >>> full_path('/foo/bar.py',['a.txt','b.txt'])
97 ['/foo/a.txt', '/foo/b.txt']
97 ['/foo/a.txt', '/foo/b.txt']
98
98
99 >>> full_path('/foo',['a.txt','b.txt'])
99 >>> full_path('/foo',['a.txt','b.txt'])
100 ['/a.txt', '/b.txt']
100 ['/a.txt', '/b.txt']
101
101
102 If a single file is given, the output is still a list:
102 If a single file is given, the output is still a list:
103 >>> full_path('/foo','a.txt')
103 >>> full_path('/foo','a.txt')
104 ['/a.txt']
104 ['/a.txt']
105 """
105 """
106
106
107 files = list_strings(files)
107 files = list_strings(files)
108 base = os.path.split(startPath)[0]
108 base = os.path.split(startPath)[0]
109 return [ os.path.join(base,f) for f in files ]
109 return [ os.path.join(base,f) for f in files ]
110
110
111
111
112 def parse_test_output(txt):
112 def parse_test_output(txt):
113 """Parse the output of a test run and return errors, failures.
113 """Parse the output of a test run and return errors, failures.
114
114
115 Parameters
115 Parameters
116 ----------
116 ----------
117 txt : str
117 txt : str
118 Text output of a test run, assumed to contain a line of one of the
118 Text output of a test run, assumed to contain a line of one of the
119 following forms::
119 following forms::
120 'FAILED (errors=1)'
120 'FAILED (errors=1)'
121 'FAILED (failures=1)'
121 'FAILED (failures=1)'
122 'FAILED (errors=1, failures=1)'
122 'FAILED (errors=1, failures=1)'
123
123
124 Returns
124 Returns
125 -------
125 -------
126 nerr, nfail: number of errors and failures.
126 nerr, nfail: number of errors and failures.
127 """
127 """
128
128
129 err_m = re.search(r'^FAILED \(errors=(\d+)\)', txt, re.MULTILINE)
129 err_m = re.search(r'^FAILED \(errors=(\d+)\)', txt, re.MULTILINE)
130 if err_m:
130 if err_m:
131 nerr = int(err_m.group(1))
131 nerr = int(err_m.group(1))
132 nfail = 0
132 nfail = 0
133 return nerr, nfail
133 return nerr, nfail
134
134
135 fail_m = re.search(r'^FAILED \(failures=(\d+)\)', txt, re.MULTILINE)
135 fail_m = re.search(r'^FAILED \(failures=(\d+)\)', txt, re.MULTILINE)
136 if fail_m:
136 if fail_m:
137 nerr = 0
137 nerr = 0
138 nfail = int(fail_m.group(1))
138 nfail = int(fail_m.group(1))
139 return nerr, nfail
139 return nerr, nfail
140
140
141 both_m = re.search(r'^FAILED \(errors=(\d+), failures=(\d+)\)', txt,
141 both_m = re.search(r'^FAILED \(errors=(\d+), failures=(\d+)\)', txt,
142 re.MULTILINE)
142 re.MULTILINE)
143 if both_m:
143 if both_m:
144 nerr = int(both_m.group(1))
144 nerr = int(both_m.group(1))
145 nfail = int(both_m.group(2))
145 nfail = int(both_m.group(2))
146 return nerr, nfail
146 return nerr, nfail
147
147
148 # If the input didn't match any of these forms, assume no error/failures
148 # If the input didn't match any of these forms, assume no error/failures
149 return 0, 0
149 return 0, 0
150
150
151
151
152 # So nose doesn't think this is a test
152 # So nose doesn't think this is a test
153 parse_test_output.__test__ = False
153 parse_test_output.__test__ = False
154
154
155
155
156 def default_argv():
156 def default_argv():
157 """Return a valid default argv for creating testing instances of ipython"""
157 """Return a valid default argv for creating testing instances of ipython"""
158
158
159 return ['--quick', # so no config file is loaded
159 return ['--quick', # so no config file is loaded
160 # Other defaults to minimize side effects on stdout
160 # Other defaults to minimize side effects on stdout
161 '--colors=NoColor', '--no-term-title','--no-banner',
161 'colors=NoColor', '--no-term-title','--no-banner',
162 '--autocall=0']
162 'autocall=0']
163
163
164
164
165 def default_config():
165 def default_config():
166 """Return a config object with good defaults for testing."""
166 """Return a config object with good defaults for testing."""
167 config = Config()
167 config = Config()
168 config.TerminalInteractiveShell.colors = 'NoColor'
168 config.TerminalInteractiveShell.colors = 'NoColor'
169 config.TerminalTerminalInteractiveShell.term_title = False,
169 config.TerminalTerminalInteractiveShell.term_title = False,
170 config.TerminalInteractiveShell.autocall = 0
170 config.TerminalInteractiveShell.autocall = 0
171 config.HistoryManager.hist_file = u'test_hist.sqlite'
171 config.HistoryManager.hist_file = u'test_hist.sqlite'
172 config.HistoryManager.db_cache_size = 10000
172 config.HistoryManager.db_cache_size = 10000
173 return config
173 return config
174
174
175
175
176 def ipexec(fname, options=None):
176 def ipexec(fname, options=None):
177 """Utility to call 'ipython filename'.
177 """Utility to call 'ipython filename'.
178
178
179 Starts IPython witha minimal and safe configuration to make startup as fast
179 Starts IPython witha minimal and safe configuration to make startup as fast
180 as possible.
180 as possible.
181
181
182 Note that this starts IPython in a subprocess!
182 Note that this starts IPython in a subprocess!
183
183
184 Parameters
184 Parameters
185 ----------
185 ----------
186 fname : str
186 fname : str
187 Name of file to be executed (should have .py or .ipy extension).
187 Name of file to be executed (should have .py or .ipy extension).
188
188
189 options : optional, list
189 options : optional, list
190 Extra command-line flags to be passed to IPython.
190 Extra command-line flags to be passed to IPython.
191
191
192 Returns
192 Returns
193 -------
193 -------
194 (stdout, stderr) of ipython subprocess.
194 (stdout, stderr) of ipython subprocess.
195 """
195 """
196 if options is None: options = []
196 if options is None: options = []
197
197
198 # For these subprocess calls, eliminate all prompt printing so we only see
198 # For these subprocess calls, eliminate all prompt printing so we only see
199 # output from script execution
199 # output from script execution
200 prompt_opts = ['--prompt-in1=""', '--prompt-in2=""', '--prompt-out=""']
200 prompt_opts = ['pi1=""', 'pi2=""', 'po=""']
201 cmdargs = ' '.join(default_argv() + prompt_opts + options)
201 cmdargs = ' '.join(default_argv() + prompt_opts + options)
202
202
203 _ip = get_ipython()
203 _ip = get_ipython()
204 test_dir = os.path.dirname(__file__)
204 test_dir = os.path.dirname(__file__)
205
205
206 ipython_cmd = find_cmd('ipython')
206 ipython_cmd = find_cmd('ipython')
207 # Absolute path for filename
207 # Absolute path for filename
208 full_fname = os.path.join(test_dir, fname)
208 full_fname = os.path.join(test_dir, fname)
209 full_cmd = '%s %s %s' % (ipython_cmd, cmdargs, full_fname)
209 full_cmd = '%s %s %s' % (ipython_cmd, cmdargs, full_fname)
210 #print >> sys.stderr, 'FULL CMD:', full_cmd # dbg
210 #print >> sys.stderr, 'FULL CMD:', full_cmd # dbg
211 return getoutputerror(full_cmd)
211 return getoutputerror(full_cmd)
212
212
213
213
214 def ipexec_validate(fname, expected_out, expected_err='',
214 def ipexec_validate(fname, expected_out, expected_err='',
215 options=None):
215 options=None):
216 """Utility to call 'ipython filename' and validate output/error.
216 """Utility to call 'ipython filename' and validate output/error.
217
217
218 This function raises an AssertionError if the validation fails.
218 This function raises an AssertionError if the validation fails.
219
219
220 Note that this starts IPython in a subprocess!
220 Note that this starts IPython in a subprocess!
221
221
222 Parameters
222 Parameters
223 ----------
223 ----------
224 fname : str
224 fname : str
225 Name of the file to be executed (should have .py or .ipy extension).
225 Name of the file to be executed (should have .py or .ipy extension).
226
226
227 expected_out : str
227 expected_out : str
228 Expected stdout of the process.
228 Expected stdout of the process.
229
229
230 expected_err : optional, str
230 expected_err : optional, str
231 Expected stderr of the process.
231 Expected stderr of the process.
232
232
233 options : optional, list
233 options : optional, list
234 Extra command-line flags to be passed to IPython.
234 Extra command-line flags to be passed to IPython.
235
235
236 Returns
236 Returns
237 -------
237 -------
238 None
238 None
239 """
239 """
240
240
241 import nose.tools as nt
241 import nose.tools as nt
242
242
243 out, err = ipexec(fname)
243 out, err = ipexec(fname)
244 #print 'OUT', out # dbg
244 #print 'OUT', out # dbg
245 #print 'ERR', err # dbg
245 #print 'ERR', err # dbg
246 # If there are any errors, we must check those befor stdout, as they may be
246 # If there are any errors, we must check those befor stdout, as they may be
247 # more informative than simply having an empty stdout.
247 # more informative than simply having an empty stdout.
248 if err:
248 if err:
249 if expected_err:
249 if expected_err:
250 nt.assert_equals(err.strip(), expected_err.strip())
250 nt.assert_equals(err.strip(), expected_err.strip())
251 else:
251 else:
252 raise ValueError('Running file %r produced error: %r' %
252 raise ValueError('Running file %r produced error: %r' %
253 (fname, err))
253 (fname, err))
254 # If no errors or output on stderr was expected, match stdout
254 # If no errors or output on stderr was expected, match stdout
255 nt.assert_equals(out.strip(), expected_out.strip())
255 nt.assert_equals(out.strip(), expected_out.strip())
256
256
257
257
258 class TempFileMixin(object):
258 class TempFileMixin(object):
259 """Utility class to create temporary Python/IPython files.
259 """Utility class to create temporary Python/IPython files.
260
260
261 Meant as a mixin class for test cases."""
261 Meant as a mixin class for test cases."""
262
262
263 def mktmp(self, src, ext='.py'):
263 def mktmp(self, src, ext='.py'):
264 """Make a valid python temp file."""
264 """Make a valid python temp file."""
265 fname, f = temp_pyfile(src, ext)
265 fname, f = temp_pyfile(src, ext)
266 self.tmpfile = f
266 self.tmpfile = f
267 self.fname = fname
267 self.fname = fname
268
268
269 def tearDown(self):
269 def tearDown(self):
270 if hasattr(self, 'tmpfile'):
270 if hasattr(self, 'tmpfile'):
271 # If the tmpfile wasn't made because of skipped tests, like in
271 # If the tmpfile wasn't made because of skipped tests, like in
272 # win32, there's nothing to cleanup.
272 # win32, there's nothing to cleanup.
273 self.tmpfile.close()
273 self.tmpfile.close()
274 try:
274 try:
275 os.unlink(self.fname)
275 os.unlink(self.fname)
276 except:
276 except:
277 # On Windows, even though we close the file, we still can't
277 # On Windows, even though we close the file, we still can't
278 # delete it. I have no clue why
278 # delete it. I have no clue why
279 pass
279 pass
280
280
General Comments 0
You need to be logged in to leave comments. Login now