##// END OF EJS Templates
Merge branch 'single-output' into takluyver-single-output
Thomas Kluyver -
r3751:bb384816 merge
parent child Browse files
Show More
@@ -1,331 +1,330 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Displayhook for IPython.
3 3
4 4 This defines a callable class that IPython uses for `sys.displayhook`.
5 5
6 6 Authors:
7 7
8 8 * Fernando Perez
9 9 * Brian Granger
10 10 * Robert Kern
11 11 """
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Copyright (C) 2008-2010 The IPython Development Team
15 15 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
16 16 #
17 17 # Distributed under the terms of the BSD License. The full license is in
18 18 # the file COPYING, distributed as part of this software.
19 19 #-----------------------------------------------------------------------------
20 20
21 21 #-----------------------------------------------------------------------------
22 22 # Imports
23 23 #-----------------------------------------------------------------------------
24 24
25 25 import __builtin__
26 26
27 27 from IPython.config.configurable import Configurable
28 28 from IPython.core import prompts
29 29 import IPython.utils.generics
30 30 import IPython.utils.io
31 31 from IPython.utils.traitlets import Instance, List
32 32 from IPython.utils.warn import warn
33 33
34 34 #-----------------------------------------------------------------------------
35 35 # Main displayhook class
36 36 #-----------------------------------------------------------------------------
37 37
38 38 # TODO: The DisplayHook class should be split into two classes, one that
39 39 # manages the prompts and their synchronization and another that just does the
40 40 # displayhook logic and calls into the prompt manager.
41 41
42 42 # TODO: Move the various attributes (cache_size, colors, input_sep,
43 43 # output_sep, output_sep2, ps1, ps2, ps_out, pad_left). Some of these are also
44 44 # attributes of InteractiveShell. They should be on ONE object only and the
45 45 # other objects should ask that one object for their values.
46 46
47 47 class DisplayHook(Configurable):
48 48 """The custom IPython displayhook to replace sys.displayhook.
49 49
50 50 This class does many things, but the basic idea is that it is a callable
51 51 that gets called anytime user code returns a value.
52 52
53 53 Currently this class does more than just the displayhook logic and that
54 54 extra logic should eventually be moved out of here.
55 55 """
56 56
57 57 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
58 58
59 59 def __init__(self, shell=None, cache_size=1000,
60 60 colors='NoColor', input_sep='\n',
61 61 output_sep='\n', output_sep2='',
62 62 ps1 = None, ps2 = None, ps_out = None, pad_left=True,
63 63 config=None):
64 64 super(DisplayHook, self).__init__(shell=shell, config=config)
65 65
66 66 cache_size_min = 3
67 67 if cache_size <= 0:
68 68 self.do_full_cache = 0
69 69 cache_size = 0
70 70 elif cache_size < cache_size_min:
71 71 self.do_full_cache = 0
72 72 cache_size = 0
73 73 warn('caching was disabled (min value for cache size is %s).' %
74 74 cache_size_min,level=3)
75 75 else:
76 76 self.do_full_cache = 1
77 77
78 78 self.cache_size = cache_size
79 79 self.input_sep = input_sep
80 80
81 81 # we need a reference to the user-level namespace
82 82 self.shell = shell
83 83
84 84 # Set input prompt strings and colors
85 85 if cache_size == 0:
86 86 if ps1.find('%n') > -1 or ps1.find(r'\#') > -1 \
87 87 or ps1.find(r'\N') > -1:
88 88 ps1 = '>>> '
89 89 if ps2.find('%n') > -1 or ps2.find(r'\#') > -1 \
90 90 or ps2.find(r'\N') > -1:
91 91 ps2 = '... '
92 92 self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
93 93 self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
94 94 self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
95 95
96 96 self.color_table = prompts.PromptColors
97 97 self.prompt1 = prompts.Prompt1(self,sep=input_sep,prompt=self.ps1_str,
98 98 pad_left=pad_left)
99 99 self.prompt2 = prompts.Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
100 100 self.prompt_out = prompts.PromptOut(self,sep='',prompt=self.ps_out_str,
101 101 pad_left=pad_left)
102 102 self.set_colors(colors)
103 103
104 104 # Store the last prompt string each time, we need it for aligning
105 105 # continuation and auto-rewrite prompts
106 106 self.last_prompt = ''
107 107 self.output_sep = output_sep
108 108 self.output_sep2 = output_sep2
109 109 self._,self.__,self.___ = '','',''
110 110
111 111 # these are deliberately global:
112 112 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
113 113 self.shell.user_ns.update(to_user_ns)
114 114
115 115 @property
116 116 def prompt_count(self):
117 117 return self.shell.execution_count
118 118
119 119 def _set_prompt_str(self,p_str,cache_def,no_cache_def):
120 120 if p_str is None:
121 121 if self.do_full_cache:
122 122 return cache_def
123 123 else:
124 124 return no_cache_def
125 125 else:
126 126 return p_str
127 127
128 128 def set_colors(self, colors):
129 129 """Set the active color scheme and configure colors for the three
130 130 prompt subsystems."""
131 131
132 132 # FIXME: This modifying of the global prompts.prompt_specials needs
133 133 # to be fixed. We need to refactor all of the prompts stuff to use
134 134 # proper configuration and traits notifications.
135 135 if colors.lower()=='nocolor':
136 136 prompts.prompt_specials = prompts.prompt_specials_nocolor
137 137 else:
138 138 prompts.prompt_specials = prompts.prompt_specials_color
139 139
140 140 self.color_table.set_active_scheme(colors)
141 141 self.prompt1.set_colors()
142 142 self.prompt2.set_colors()
143 143 self.prompt_out.set_colors()
144 144
145 145 #-------------------------------------------------------------------------
146 146 # Methods used in __call__. Override these methods to modify the behavior
147 147 # of the displayhook.
148 148 #-------------------------------------------------------------------------
149 149
150 150 def check_for_underscore(self):
151 151 """Check if the user has set the '_' variable by hand."""
152 152 # If something injected a '_' variable in __builtin__, delete
153 153 # ipython's automatic one so we don't clobber that. gettext() in
154 154 # particular uses _, so we need to stay away from it.
155 155 if '_' in __builtin__.__dict__:
156 156 try:
157 157 del self.shell.user_ns['_']
158 158 except KeyError:
159 159 pass
160 160
161 161 def quiet(self):
162 162 """Should we silence the display hook because of ';'?"""
163 163 # do not print output if input ends in ';'
164 164 try:
165 165 cell = self.shell.history_manager.input_hist_parsed[self.prompt_count]
166 166 if cell.rstrip().endswith(';'):
167 167 return True
168 168 except IndexError:
169 169 # some uses of ipshellembed may fail here
170 170 pass
171 171 return False
172 172
173 173 def start_displayhook(self):
174 174 """Start the displayhook, initializing resources."""
175 175 pass
176 176
177 177 def write_output_prompt(self):
178 178 """Write the output prompt.
179 179
180 180 The default implementation simply writes the prompt to
181 181 ``io.Term.cout``.
182 182 """
183 183 # Use write, not print which adds an extra space.
184 184 IPython.utils.io.Term.cout.write(self.output_sep)
185 185 outprompt = str(self.prompt_out)
186 186 if self.do_full_cache:
187 187 IPython.utils.io.Term.cout.write(outprompt)
188 188
189 189 def compute_format_data(self, result):
190 190 """Compute format data of the object to be displayed.
191 191
192 192 The format data is a generalization of the :func:`repr` of an object.
193 193 In the default implementation the format data is a :class:`dict` of
194 194 key value pair where the keys are valid MIME types and the values
195 195 are JSON'able data structure containing the raw data for that MIME
196 196 type. It is up to frontends to determine pick a MIME to to use and
197 197 display that data in an appropriate manner.
198 198
199 199 This method only computes the format data for the object and should
200 200 NOT actually print or write that to a stream.
201 201
202 202 Parameters
203 203 ----------
204 204 result : object
205 205 The Python object passed to the display hook, whose format will be
206 206 computed.
207 207
208 208 Returns
209 209 -------
210 210 format_data : dict
211 211 A :class:`dict` whose keys are valid MIME types and values are
212 212 JSON'able raw data for that MIME type. It is recommended that
213 213 all return values of this should always include the "text/plain"
214 214 MIME type representation of the object.
215 215 """
216 216 return self.shell.display_formatter.format(result)
217 217
218 218 def write_format_data(self, format_dict):
219 219 """Write the format data dict to the frontend.
220 220
221 221 This default version of this method simply writes the plain text
222 222 representation of the object to ``io.Term.cout``. Subclasses should
223 223 override this method to send the entire `format_dict` to the
224 224 frontends.
225 225
226 226 Parameters
227 227 ----------
228 228 format_dict : dict
229 229 The format dict for the object passed to `sys.displayhook`.
230 230 """
231 231 # We want to print because we want to always make sure we have a
232 232 # newline, even if all the prompt separators are ''. This is the
233 233 # standard IPython behavior.
234 234 result_repr = format_dict['text/plain']
235 235 if '\n' in result_repr:
236 236 # So that multi-line strings line up with the left column of
237 237 # the screen, instead of having the output prompt mess up
238 238 # their first line.
239 239 # We use the ps_out_str template instead of the expanded prompt
240 240 # because the expansion may add ANSI escapes that will interfere
241 241 # with our ability to determine whether or not we should add
242 242 # a newline.
243 243 if self.ps_out_str and not self.ps_out_str.endswith('\n'):
244 244 # But avoid extraneous empty lines.
245 245 result_repr = '\n' + result_repr
246 246
247 247 print >>IPython.utils.io.Term.cout, result_repr
248 248
249 249 def update_user_ns(self, result):
250 250 """Update user_ns with various things like _, __, _1, etc."""
251 251
252 252 # Avoid recursive reference when displaying _oh/Out
253 253 if result is not self.shell.user_ns['_oh']:
254 254 if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
255 255 warn('Output cache limit (currently '+
256 256 `self.cache_size`+' entries) hit.\n'
257 257 'Flushing cache and resetting history counter...\n'
258 258 'The only history variables available will be _,__,___ and _1\n'
259 259 'with the current result.')
260 260
261 261 self.flush()
262 262 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
263 263 # we cause buggy behavior for things like gettext).
264 264
265 265 if '_' not in __builtin__.__dict__:
266 266 self.___ = self.__
267 267 self.__ = self._
268 268 self._ = result
269 269 self.shell.user_ns.update({'_':self._,
270 270 '__':self.__,
271 271 '___':self.___})
272 272
273 273 # hackish access to top-level namespace to create _1,_2... dynamically
274 274 to_main = {}
275 275 if self.do_full_cache:
276 276 new_result = '_'+`self.prompt_count`
277 277 to_main[new_result] = result
278 278 self.shell.user_ns.update(to_main)
279 279 self.shell.user_ns['_oh'][self.prompt_count] = result
280 280
281 281 def log_output(self, format_dict):
282 282 """Log the output."""
283 283 if self.shell.logger.log_output:
284 284 self.shell.logger.log_write(format_dict['text/plain'], 'output')
285 # This is a defaultdict of lists, so we can always append
286 self.shell.history_manager.output_hist_reprs[self.prompt_count]\
287 .append(format_dict['text/plain'])
285 self.shell.history_manager.output_hist_reprs[self.prompt_count] = \
286 format_dict['text/plain']
288 287
289 288 def finish_displayhook(self):
290 289 """Finish up all displayhook activities."""
291 290 IPython.utils.io.Term.cout.write(self.output_sep2)
292 291 IPython.utils.io.Term.cout.flush()
293 292
294 293 def __call__(self, result=None):
295 294 """Printing with history cache management.
296 295
297 296 This is invoked everytime the interpreter needs to print, and is
298 297 activated by setting the variable sys.displayhook to it.
299 298 """
300 299 self.check_for_underscore()
301 300 if result is not None and not self.quiet():
302 301 self.start_displayhook()
303 302 self.write_output_prompt()
304 303 format_dict = self.compute_format_data(result)
305 304 self.write_format_data(format_dict)
306 305 self.update_user_ns(result)
307 306 self.log_output(format_dict)
308 307 self.finish_displayhook()
309 308
310 309 def flush(self):
311 310 if not self.do_full_cache:
312 311 raise ValueError,"You shouldn't have reached the cache flush "\
313 312 "if full caching is not enabled!"
314 313 # delete auto-generated vars from global namespace
315 314
316 315 for n in range(1,self.prompt_count + 1):
317 316 key = '_'+`n`
318 317 try:
319 318 del self.shell.user_ns[key]
320 319 except: pass
321 320 self.shell.user_ns['_oh'].clear()
322 321
323 322 # Release our own references to objects:
324 323 self._, self.__, self.___ = '', '', ''
325 324
326 325 if '_' not in __builtin__.__dict__:
327 326 self.shell.user_ns.update({'_':None,'__':None, '___':None})
328 327 import gc
329 328 # TODO: Is this really needed?
330 329 gc.collect()
331 330
@@ -1,810 +1,803 b''
1 1 """ History related magics and functionality """
2 2 #-----------------------------------------------------------------------------
3 3 # Copyright (C) 2010 The IPython Development Team.
4 4 #
5 5 # Distributed under the terms of the BSD License.
6 6 #
7 7 # The full license is in the file COPYING.txt, distributed with this software.
8 8 #-----------------------------------------------------------------------------
9 9
10 10 #-----------------------------------------------------------------------------
11 11 # Imports
12 12 #-----------------------------------------------------------------------------
13 13 from __future__ import print_function
14 14
15 15 # Stdlib imports
16 16 import atexit
17 17 import datetime
18 import json
19 18 import os
20 19 import re
21 20 import sqlite3
22 21 import threading
23 22
24 from collections import defaultdict
25
26 23 # Our own packages
27 24 from IPython.config.configurable import Configurable
28 25 import IPython.utils.io
29 26
30 27 from IPython.testing import decorators as testdec
31 28 from IPython.utils.io import ask_yes_no
32 29 from IPython.utils.traitlets import Bool, Dict, Instance, Int, List, Unicode
33 30 from IPython.utils.warn import warn
34 31
35 32 #-----------------------------------------------------------------------------
36 33 # Classes and functions
37 34 #-----------------------------------------------------------------------------
38 35
39 36 class HistoryManager(Configurable):
40 37 """A class to organize all history-related functionality in one place.
41 38 """
42 39 # Public interface
43 40
44 41 # An instance of the IPython shell we are attached to
45 42 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
46 43 # Lists to hold processed and raw history. These start with a blank entry
47 44 # so that we can index them starting from 1
48 45 input_hist_parsed = List([""])
49 46 input_hist_raw = List([""])
50 47 # A list of directories visited during session
51 48 dir_hist = List()
52 49 def _dir_hist_default(self):
53 50 try:
54 51 return [os.getcwd()]
55 52 except OSError:
56 53 return []
57 54
58 55 # A dict of output history, keyed with ints from the shell's
59 # execution count. If there are several outputs from one command,
60 # only the last one is stored.
56 # execution count.
61 57 output_hist = Dict()
62 # Contains all outputs, in lists of reprs.
63 output_hist_reprs = Instance(defaultdict, args=(list,))
58 # The text/plain repr of outputs.
59 output_hist_reprs = Dict()
64 60
65 61 # String holding the path to the history file
66 62 hist_file = Unicode(config=True)
67 63
68 64 # The SQLite database
69 65 db = Instance(sqlite3.Connection)
70 66 # The number of the current session in the history database
71 67 session_number = Int()
72 68 # Should we log output to the database? (default no)
73 69 db_log_output = Bool(False, config=True)
74 70 # Write to database every x commands (higher values save disk access & power)
75 71 # Values of 1 or less effectively disable caching.
76 72 db_cache_size = Int(0, config=True)
77 73 # The input and output caches
78 74 db_input_cache = List()
79 75 db_output_cache = List()
80 76
81 77 # History saving in separate thread
82 78 save_thread = Instance('IPython.core.history.HistorySavingThread')
83 79 # N.B. Event is a function returning an instance of _Event.
84 80 save_flag = Instance(threading._Event)
85 81
86 82 # Private interface
87 83 # Variables used to store the three last inputs from the user. On each new
88 84 # history update, we populate the user's namespace with these, shifted as
89 85 # necessary.
90 86 _i00 = Unicode(u'')
91 87 _i = Unicode(u'')
92 88 _ii = Unicode(u'')
93 89 _iii = Unicode(u'')
94 90
95 # A set with all forms of the exit command, so that we don't store them in
96 # the history (it's annoying to rewind the first entry and land on an exit
97 # call).
98 _exit_commands = Instance(set, args=(['Quit', 'quit', 'Exit', 'exit',
99 '%Quit', '%quit', '%Exit', '%exit'],))
91 # A regex matching all forms of the exit command, so that we don't store
92 # them in the history (it's annoying to rewind the first entry and land on
93 # an exit call).
94 _exit_re = re.compile(r"(exit|quit)(\s*\(.*\))?$")
100 95
101 96 def __init__(self, shell, config=None, **traits):
102 97 """Create a new history manager associated with a shell instance.
103 98 """
104 99 # We need a pointer back to the shell for various tasks.
105 100 super(HistoryManager, self).__init__(shell=shell, config=config,
106 101 **traits)
107 102
108 103 if self.hist_file == u'':
109 104 # No one has set the hist_file, yet.
110 105 if shell.profile:
111 106 histfname = 'history-%s' % shell.profile
112 107 else:
113 108 histfname = 'history'
114 109 self.hist_file = os.path.join(shell.ipython_dir, histfname + '.sqlite')
115 110
116 111 try:
117 112 self.init_db()
118 113 except sqlite3.DatabaseError:
119 114 if os.path.isfile(self.hist_file):
120 115 # Try to move the file out of the way.
121 116 newpath = os.path.join(self.shell.ipython_dir, "hist-corrupt.sqlite")
122 117 os.rename(self.hist_file, newpath)
123 118 print("ERROR! History file wasn't a valid SQLite database.",
124 119 "It was moved to %s" % newpath, "and a new file created.")
125 120 self.init_db()
126 121 else:
127 122 # The hist_file is probably :memory: or something else.
128 123 raise
129 124
130 125 self.save_flag = threading.Event()
131 126 self.db_input_cache_lock = threading.Lock()
132 127 self.db_output_cache_lock = threading.Lock()
133 128 self.save_thread = HistorySavingThread(self)
134 129 self.save_thread.start()
135 130
136 131 self.new_session()
137 132
138 133
139 134 def init_db(self):
140 135 """Connect to the database, and create tables if necessary."""
141 136 self.db = sqlite3.connect(self.hist_file)
142 137 self.db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer
143 138 primary key autoincrement, start timestamp,
144 139 end timestamp, num_cmds integer, remark text)""")
145 140 self.db.execute("""CREATE TABLE IF NOT EXISTS history
146 141 (session integer, line integer, source text, source_raw text,
147 142 PRIMARY KEY (session, line))""")
148 143 # Output history is optional, but ensure the table's there so it can be
149 144 # enabled later.
150 145 self.db.execute("""CREATE TABLE IF NOT EXISTS output_history
151 146 (session integer, line integer, output text,
152 147 PRIMARY KEY (session, line))""")
153 148 self.db.commit()
154 149
155 150 def new_session(self, conn=None):
156 151 """Get a new session number."""
157 152 if conn is None:
158 153 conn = self.db
159 154
160 155 with conn:
161 156 cur = conn.execute("""INSERT INTO sessions VALUES (NULL, ?, NULL,
162 157 NULL, "") """, (datetime.datetime.now(),))
163 158 self.session_number = cur.lastrowid
164 159
165 160 def end_session(self):
166 161 """Close the database session, filling in the end time and line count."""
167 162 self.writeout_cache()
168 163 with self.db:
169 164 self.db.execute("""UPDATE sessions SET end=?, num_cmds=? WHERE
170 165 session==?""", (datetime.datetime.now(),
171 166 len(self.input_hist_parsed)-1, self.session_number))
172 167 self.session_number = 0
173 168
174 169 def name_session(self, name):
175 170 """Give the current session a name in the history database."""
176 171 with self.db:
177 172 self.db.execute("UPDATE sessions SET remark=? WHERE session==?",
178 173 (name, self.session_number))
179 174
180 175 def reset(self, new_session=True):
181 176 """Clear the session history, releasing all object references, and
182 177 optionally open a new session."""
183 178 self.output_hist.clear()
184 179 # The directory history can't be completely empty
185 180 self.dir_hist[:] = [os.getcwd()]
186 181
187 182 if new_session:
188 183 if self.session_number:
189 184 self.end_session()
190 185 self.input_hist_parsed[:] = [""]
191 186 self.input_hist_raw[:] = [""]
192 187 self.new_session()
193 188
194 189 ## -------------------------------
195 190 ## Methods for retrieving history:
196 191 ## -------------------------------
197 192 def _run_sql(self, sql, params, raw=True, output=False):
198 193 """Prepares and runs an SQL query for the history database.
199 194
200 195 Parameters
201 196 ----------
202 197 sql : str
203 198 Any filtering expressions to go after SELECT ... FROM ...
204 199 params : tuple
205 200 Parameters passed to the SQL query (to replace "?")
206 201 raw, output : bool
207 202 See :meth:`get_range`
208 203
209 204 Returns
210 205 -------
211 206 Tuples as :meth:`get_range`
212 207 """
213 208 toget = 'source_raw' if raw else 'source'
214 209 sqlfrom = "history"
215 210 if output:
216 211 sqlfrom = "history LEFT JOIN output_history USING (session, line)"
217 212 toget = "history.%s, output_history.output" % toget
218 213 cur = self.db.execute("SELECT session, line, %s FROM %s " %\
219 214 (toget, sqlfrom) + sql, params)
220 215 if output: # Regroup into 3-tuples, and parse JSON
221 loads = lambda out: json.loads(out) if out else None
222 return ((ses, lin, (inp, loads(out))) \
223 for ses, lin, inp, out in cur)
216 return ((ses, lin, (inp, out)) for ses, lin, inp, out in cur)
224 217 return cur
225 218
226 219
227 220 def get_tail(self, n=10, raw=True, output=False, include_latest=False):
228 221 """Get the last n lines from the history database.
229 222
230 223 Parameters
231 224 ----------
232 225 n : int
233 226 The number of lines to get
234 227 raw, output : bool
235 228 See :meth:`get_range`
236 229 include_latest : bool
237 230 If False (default), n+1 lines are fetched, and the latest one
238 231 is discarded. This is intended to be used where the function
239 232 is called by a user command, which it should not return.
240 233
241 234 Returns
242 235 -------
243 236 Tuples as :meth:`get_range`
244 237 """
245 238 self.writeout_cache()
246 239 if not include_latest:
247 240 n += 1
248 241 cur = self._run_sql("ORDER BY session DESC, line DESC LIMIT ?",
249 242 (n,), raw=raw, output=output)
250 243 if not include_latest:
251 244 return reversed(list(cur)[1:])
252 245 return reversed(list(cur))
253 246
254 247 def search(self, pattern="*", raw=True, search_raw=True,
255 248 output=False):
256 249 """Search the database using unix glob-style matching (wildcards
257 250 * and ?).
258 251
259 252 Parameters
260 253 ----------
261 254 pattern : str
262 255 The wildcarded pattern to match when searching
263 256 search_raw : bool
264 257 If True, search the raw input, otherwise, the parsed input
265 258 raw, output : bool
266 259 See :meth:`get_range`
267 260
268 261 Returns
269 262 -------
270 263 Tuples as :meth:`get_range`
271 264 """
272 265 tosearch = "source_raw" if search_raw else "source"
273 266 if output:
274 267 tosearch = "history." + tosearch
275 268 self.writeout_cache()
276 269 return self._run_sql("WHERE %s GLOB ?" % tosearch, (pattern,),
277 270 raw=raw, output=output)
278 271
279 272 def _get_range_session(self, start=1, stop=None, raw=True, output=False):
280 273 """Get input and output history from the current session. Called by
281 274 get_range, and takes similar parameters."""
282 275 input_hist = self.input_hist_raw if raw else self.input_hist_parsed
283 276
284 277 n = len(input_hist)
285 278 if start < 0:
286 279 start += n
287 280 if not stop:
288 281 stop = n
289 282 elif stop < 0:
290 283 stop += n
291 284
292 285 for i in range(start, stop):
293 286 if output:
294 287 line = (input_hist[i], self.output_hist_reprs.get(i))
295 288 else:
296 289 line = input_hist[i]
297 290 yield (0, i, line)
298 291
299 292 def get_range(self, session=0, start=1, stop=None, raw=True,output=False):
300 293 """Retrieve input by session.
301 294
302 295 Parameters
303 296 ----------
304 297 session : int
305 298 Session number to retrieve. The current session is 0, and negative
306 299 numbers count back from current session, so -1 is previous session.
307 300 start : int
308 301 First line to retrieve.
309 302 stop : int
310 303 End of line range (excluded from output itself). If None, retrieve
311 304 to the end of the session.
312 305 raw : bool
313 306 If True, return untranslated input
314 307 output : bool
315 308 If True, attempt to include output. This will be 'real' Python
316 309 objects for the current session, or text reprs from previous
317 310 sessions if db_log_output was enabled at the time. Where no output
318 311 is found, None is used.
319 312
320 313 Returns
321 314 -------
322 315 An iterator over the desired lines. Each line is a 3-tuple, either
323 316 (session, line, input) if output is False, or
324 317 (session, line, (input, output)) if output is True.
325 318 """
326 319 if session == 0 or session==self.session_number: # Current session
327 320 return self._get_range_session(start, stop, raw, output)
328 321 if session < 0:
329 322 session += self.session_number
330 323
331 324 if stop:
332 325 lineclause = "line >= ? AND line < ?"
333 326 params = (session, start, stop)
334 327 else:
335 328 lineclause = "line>=?"
336 329 params = (session, start)
337 330
338 331 return self._run_sql("WHERE session==? AND %s""" % lineclause,
339 332 params, raw=raw, output=output)
340 333
341 334 def get_range_by_str(self, rangestr, raw=True, output=False):
342 335 """Get lines of history from a string of ranges, as used by magic
343 336 commands %hist, %save, %macro, etc.
344 337
345 338 Parameters
346 339 ----------
347 340 rangestr : str
348 341 A string specifying ranges, e.g. "5 ~2/1-4". See
349 342 :func:`magic_history` for full details.
350 343 raw, output : bool
351 344 As :meth:`get_range`
352 345
353 346 Returns
354 347 -------
355 348 Tuples as :meth:`get_range`
356 349 """
357 350 for sess, s, e in extract_hist_ranges(rangestr):
358 351 for line in self.get_range(sess, s, e, raw=raw, output=output):
359 352 yield line
360 353
361 354 ## ----------------------------
362 355 ## Methods for storing history:
363 356 ## ----------------------------
364 357 def store_inputs(self, line_num, source, source_raw=None):
365 358 """Store source and raw input in history and create input cache
366 359 variables _i*.
367 360
368 361 Parameters
369 362 ----------
370 363 line_num : int
371 364 The prompt number of this input.
372 365
373 366 source : str
374 367 Python input.
375 368
376 369 source_raw : str, optional
377 370 If given, this is the raw input without any IPython transformations
378 371 applied to it. If not given, ``source`` is used.
379 372 """
380 373 if source_raw is None:
381 374 source_raw = source
382 375 source = source.rstrip('\n')
383 376 source_raw = source_raw.rstrip('\n')
384 377
385 378 # do not store exit/quit commands
386 if source_raw.strip() in self._exit_commands:
379 if self._exit_re.match(source_raw.strip()):
387 380 return
388 381
389 382 self.input_hist_parsed.append(source)
390 383 self.input_hist_raw.append(source_raw)
391 384
392 385 with self.db_input_cache_lock:
393 386 self.db_input_cache.append((line_num, source, source_raw))
394 387 # Trigger to flush cache and write to DB.
395 388 if len(self.db_input_cache) >= self.db_cache_size:
396 389 self.save_flag.set()
397 390
398 391 # update the auto _i variables
399 392 self._iii = self._ii
400 393 self._ii = self._i
401 394 self._i = self._i00
402 395 self._i00 = source_raw
403 396
404 397 # hackish access to user namespace to create _i1,_i2... dynamically
405 398 new_i = '_i%s' % line_num
406 399 to_main = {'_i': self._i,
407 400 '_ii': self._ii,
408 401 '_iii': self._iii,
409 402 new_i : self._i00 }
410 403 self.shell.user_ns.update(to_main)
411 404
412 405 def store_output(self, line_num):
413 406 """If database output logging is enabled, this saves all the
414 407 outputs from the indicated prompt number to the database. It's
415 408 called by run_cell after code has been executed.
416 409
417 410 Parameters
418 411 ----------
419 412 line_num : int
420 413 The line number from which to save outputs
421 414 """
422 if (not self.db_log_output) or not self.output_hist_reprs[line_num]:
415 if (not self.db_log_output) or (line_num not in self.output_hist_reprs):
423 416 return
424 output = json.dumps(self.output_hist_reprs[line_num])
417 output = self.output_hist_reprs[line_num]
425 418
426 419 with self.db_output_cache_lock:
427 420 self.db_output_cache.append((line_num, output))
428 421 if self.db_cache_size <= 1:
429 422 self.save_flag.set()
430 423
431 424 def _writeout_input_cache(self, conn):
432 425 with conn:
433 426 for line in self.db_input_cache:
434 427 conn.execute("INSERT INTO history VALUES (?, ?, ?, ?)",
435 428 (self.session_number,)+line)
436 429
437 430 def _writeout_output_cache(self, conn):
438 431 with conn:
439 432 for line in self.db_output_cache:
440 433 conn.execute("INSERT INTO output_history VALUES (?, ?, ?)",
441 434 (self.session_number,)+line)
442 435
443 436 def writeout_cache(self, conn=None):
444 437 """Write any entries in the cache to the database."""
445 438 if conn is None:
446 439 conn = self.db
447 440
448 441 with self.db_input_cache_lock:
449 442 try:
450 443 self._writeout_input_cache(conn)
451 444 except sqlite3.IntegrityError:
452 445 self.new_session(conn)
453 446 print("ERROR! Session/line number was not unique in",
454 447 "database. History logging moved to new session",
455 448 self.session_number)
456 449 try: # Try writing to the new session. If this fails, don't recurse
457 450 self._writeout_input_cache(conn)
458 451 except sqlite3.IntegrityError:
459 452 pass
460 453 finally:
461 454 self.db_input_cache = []
462 455
463 456 with self.db_output_cache_lock:
464 457 try:
465 458 self._writeout_output_cache(conn)
466 459 except sqlite3.IntegrityError:
467 460 print("!! Session/line number for output was not unique",
468 461 "in database. Output will not be stored.")
469 462 finally:
470 463 self.db_output_cache = []
471 464
472 465
473 466 class HistorySavingThread(threading.Thread):
474 467 """This thread takes care of writing history to the database, so that
475 468 the UI isn't held up while that happens.
476 469
477 470 It waits for the HistoryManager's save_flag to be set, then writes out
478 471 the history cache. The main thread is responsible for setting the flag when
479 472 the cache size reaches a defined threshold."""
480 473 daemon = True
481 474 stop_now = False
482 475 def __init__(self, history_manager):
483 476 super(HistorySavingThread, self).__init__()
484 477 self.history_manager = history_manager
485 478 atexit.register(self.stop)
486 479
487 480 def run(self):
488 481 # We need a separate db connection per thread:
489 482 try:
490 483 self.db = sqlite3.connect(self.history_manager.hist_file)
491 484 while True:
492 485 self.history_manager.save_flag.wait()
493 486 if self.stop_now:
494 487 return
495 488 self.history_manager.save_flag.clear()
496 489 self.history_manager.writeout_cache(self.db)
497 490 except Exception as e:
498 491 print(("The history saving thread hit an unexpected error (%s)."
499 492 "History will not be written to the database.") % repr(e))
500 493
501 494 def stop(self):
502 495 """This can be called from the main thread to safely stop this thread.
503 496
504 497 Note that it does not attempt to write out remaining history before
505 498 exiting. That should be done by calling the HistoryManager's
506 499 end_session method."""
507 500 self.stop_now = True
508 501 self.history_manager.save_flag.set()
509 502 self.join()
510 503
511 504
512 505 # To match, e.g. ~5/8-~2/3
513 506 range_re = re.compile(r"""
514 507 ((?P<startsess>~?\d+)/)?
515 508 (?P<start>\d+) # Only the start line num is compulsory
516 509 ((?P<sep>[\-:])
517 510 ((?P<endsess>~?\d+)/)?
518 511 (?P<end>\d+))?
519 512 $""", re.VERBOSE)
520 513
521 514 def extract_hist_ranges(ranges_str):
522 515 """Turn a string of history ranges into 3-tuples of (session, start, stop).
523 516
524 517 Examples
525 518 --------
526 519 list(extract_input_ranges("~8/5-~7/4 2"))
527 520 [(-8, 5, None), (-7, 1, 4), (0, 2, 3)]
528 521 """
529 522 for range_str in ranges_str.split():
530 523 rmatch = range_re.match(range_str)
531 524 if not rmatch:
532 525 continue
533 526 start = int(rmatch.group("start"))
534 527 end = rmatch.group("end")
535 528 end = int(end) if end else start+1 # If no end specified, get (a, a+1)
536 529 if rmatch.group("sep") == "-": # 1-3 == 1:4 --> [1, 2, 3]
537 530 end += 1
538 531 startsess = rmatch.group("startsess") or "0"
539 532 endsess = rmatch.group("endsess") or startsess
540 533 startsess = int(startsess.replace("~","-"))
541 534 endsess = int(endsess.replace("~","-"))
542 535 assert endsess >= startsess
543 536
544 537 if endsess == startsess:
545 538 yield (startsess, start, end)
546 539 continue
547 540 # Multiple sessions in one range:
548 541 yield (startsess, start, None)
549 542 for sess in range(startsess+1, endsess):
550 543 yield (sess, 1, None)
551 544 yield (endsess, 1, end)
552 545
553 546 def _format_lineno(session, line):
554 547 """Helper function to format line numbers properly."""
555 548 if session == 0:
556 549 return str(line)
557 550 return "%s#%s" % (session, line)
558 551
559 552 @testdec.skip_doctest
560 553 def magic_history(self, parameter_s = ''):
561 554 """Print input history (_i<n> variables), with most recent last.
562 555
563 556 %history -> print at most 40 inputs (some may be multi-line)\\
564 557 %history n -> print at most n inputs\\
565 558 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
566 559
567 560 By default, input history is printed without line numbers so it can be
568 561 directly pasted into an editor. Use -n to show them.
569 562
570 563 Ranges of history can be indicated using the syntax:
571 564 4 : Line 4, current session
572 565 4-6 : Lines 4-6, current session
573 566 243/1-5: Lines 1-5, session 243
574 567 ~2/7 : Line 7, session 2 before current
575 568 ~8/1-~6/5 : From the first line of 8 sessions ago, to the fifth line
576 569 of 6 sessions ago.
577 570 Multiple ranges can be entered, separated by spaces
578 571
579 572 The same syntax is used by %macro, %save, %edit, %rerun
580 573
581 574 Options:
582 575
583 576 -n: print line numbers for each input.
584 577 This feature is only available if numbered prompts are in use.
585 578
586 579 -o: also print outputs for each input.
587 580
588 581 -p: print classic '>>>' python prompts before each input. This is useful
589 582 for making documentation, and in conjunction with -o, for producing
590 583 doctest-ready output.
591 584
592 585 -r: (default) print the 'raw' history, i.e. the actual commands you typed.
593 586
594 587 -t: print the 'translated' history, as IPython understands it. IPython
595 588 filters your input and converts it all into valid Python source before
596 589 executing it (things like magics or aliases are turned into function
597 590 calls, for example). With this option, you'll see the native history
598 591 instead of the user-entered version: '%cd /' will be seen as
599 592 'get_ipython().magic("%cd /")' instead of '%cd /'.
600 593
601 594 -g: treat the arg as a pattern to grep for in (full) history.
602 595 This includes the saved history (almost all commands ever written).
603 596 Use '%hist -g' to show full saved history (may be very long).
604 597
605 598 -l: get the last n lines from all sessions. Specify n as a single arg, or
606 599 the default is the last 10 lines.
607 600
608 601 -f FILENAME: instead of printing the output to the screen, redirect it to
609 602 the given file. The file is always overwritten, though IPython asks for
610 603 confirmation first if it already exists.
611 604
612 605 Examples
613 606 --------
614 607 ::
615 608
616 609 In [6]: %hist -n 4 6
617 610 4:a = 12
618 611 5:print a**2
619 612
620 613 """
621 614
622 615 if not self.shell.displayhook.do_full_cache:
623 616 print('This feature is only available if numbered prompts are in use.')
624 617 return
625 618 opts,args = self.parse_options(parameter_s,'noprtglf:',mode='string')
626 619
627 620 # For brevity
628 621 history_manager = self.shell.history_manager
629 622
630 623 def _format_lineno(session, line):
631 624 """Helper function to format line numbers properly."""
632 625 if session in (0, history_manager.session_number):
633 626 return str(line)
634 627 return "%s/%s" % (session, line)
635 628
636 629 # Check if output to specific file was requested.
637 630 try:
638 631 outfname = opts['f']
639 632 except KeyError:
640 633 outfile = IPython.utils.io.Term.cout # default
641 634 # We don't want to close stdout at the end!
642 635 close_at_end = False
643 636 else:
644 637 if os.path.exists(outfname):
645 638 if not ask_yes_no("File %r exists. Overwrite?" % outfname):
646 639 print('Aborting.')
647 640 return
648 641
649 642 outfile = open(outfname,'w')
650 643 close_at_end = True
651 644
652 645 print_nums = 'n' in opts
653 646 get_output = 'o' in opts
654 647 pyprompts = 'p' in opts
655 648 # Raw history is the default
656 649 raw = not('t' in opts)
657 650
658 651 default_length = 40
659 652 pattern = None
660 653
661 654 if 'g' in opts: # Glob search
662 655 pattern = "*" + args + "*" if args else "*"
663 656 hist = history_manager.search(pattern, raw=raw, output=get_output)
664 657 elif 'l' in opts: # Get 'tail'
665 658 try:
666 659 n = int(args)
667 660 except ValueError, IndexError:
668 661 n = 10
669 662 hist = history_manager.get_tail(n, raw=raw, output=get_output)
670 663 else:
671 664 if args: # Get history by ranges
672 665 hist = history_manager.get_range_by_str(args, raw, get_output)
673 666 else: # Just get history for the current session
674 667 hist = history_manager.get_range(raw=raw, output=get_output)
675 668
676 669 # We could be displaying the entire history, so let's not try to pull it
677 670 # into a list in memory. Anything that needs more space will just misalign.
678 671 width = 4
679 672
680 673 for session, lineno, inline in hist:
681 674 # Print user history with tabs expanded to 4 spaces. The GUI clients
682 675 # use hard tabs for easier usability in auto-indented code, but we want
683 676 # to produce PEP-8 compliant history for safe pasting into an editor.
684 677 if get_output:
685 678 inline, output = inline
686 679 inline = inline.expandtabs(4).rstrip()
687 680
688 681 multiline = "\n" in inline
689 682 line_sep = '\n' if multiline else ' '
690 683 if print_nums:
691 684 print('%s:%s' % (_format_lineno(session, lineno).rjust(width),
692 685 line_sep), file=outfile, end='')
693 686 if pyprompts:
694 687 print(">>> ", end="", file=outfile)
695 688 if multiline:
696 689 inline = "\n... ".join(inline.splitlines()) + "\n..."
697 690 print(inline, file=outfile)
698 691 if get_output and output:
699 print("\n".join(output), file=outfile)
692 print(output, file=outfile)
700 693
701 694 if close_at_end:
702 695 outfile.close()
703 696
704 697
705 698 def magic_rep(self, arg):
706 699 r""" Repeat a command, or get command to input line for editing
707 700
708 701 - %rep (no arguments):
709 702
710 703 Place a string version of last computation result (stored in the special '_'
711 704 variable) to the next input prompt. Allows you to create elaborate command
712 705 lines without using copy-paste::
713 706
714 707 In[1]: l = ["hei", "vaan"]
715 708 In[2]: "".join(l)
716 709 Out[2]: heivaan
717 710 In[3]: %rep
718 711 In[4]: heivaan_ <== cursor blinking
719 712
720 713 %rep 45
721 714
722 715 Place history line 45 on the next input prompt. Use %hist to find
723 716 out the number.
724 717
725 718 %rep 1-4
726 719
727 720 Combine the specified lines into one cell, and place it on the next
728 721 input prompt. See %history for the slice syntax.
729 722
730 723 %rep foo+bar
731 724
732 725 If foo+bar can be evaluated in the user namespace, the result is
733 726 placed at the next input prompt. Otherwise, the history is searched
734 727 for lines which contain that substring, and the most recent one is
735 728 placed at the next input prompt.
736 729 """
737 730 if not arg: # Last output
738 731 self.set_next_input(str(self.shell.user_ns["_"]))
739 732 return
740 733 # Get history range
741 734 histlines = self.history_manager.get_range_by_str(arg)
742 735 cmd = "\n".join(x[2] for x in histlines)
743 736 if cmd:
744 737 self.set_next_input(cmd.rstrip())
745 738 return
746 739
747 740 try: # Variable in user namespace
748 741 cmd = str(eval(arg, self.shell.user_ns))
749 742 except Exception: # Search for term in history
750 743 histlines = self.history_manager.search("*"+arg+"*")
751 744 for h in reversed([x[2] for x in histlines]):
752 745 if 'rep' in h:
753 746 continue
754 747 self.set_next_input(h.rstrip())
755 748 return
756 749 else:
757 750 self.set_next_input(cmd.rstrip())
758 751 print("Couldn't evaluate or find in history:", arg)
759 752
760 753 def magic_rerun(self, parameter_s=''):
761 754 """Re-run previous input
762 755
763 756 By default, you can specify ranges of input history to be repeated
764 757 (as with %history). With no arguments, it will repeat the last line.
765 758
766 759 Options:
767 760
768 761 -l <n> : Repeat the last n lines of input, not including the
769 762 current command.
770 763
771 764 -g foo : Repeat the most recent line which contains foo
772 765 """
773 766 opts, args = self.parse_options(parameter_s, 'l:g:', mode='string')
774 767 if "l" in opts: # Last n lines
775 768 n = int(opts['l'])
776 769 hist = self.history_manager.get_tail(n)
777 770 elif "g" in opts: # Search
778 771 p = "*"+opts['g']+"*"
779 772 hist = list(self.history_manager.search(p))
780 773 for l in reversed(hist):
781 774 if "rerun" not in l[2]:
782 775 hist = [l] # The last match which isn't a %rerun
783 776 break
784 777 else:
785 778 hist = [] # No matches except %rerun
786 779 elif args: # Specify history ranges
787 780 hist = self.history_manager.get_range_by_str(args)
788 781 else: # Last line
789 782 hist = self.history_manager.get_tail(1)
790 783 hist = [x[2] for x in hist]
791 784 if not hist:
792 785 print("No lines in history match specification")
793 786 return
794 787 histlines = "\n".join(hist)
795 788 print("=== Executing: ===")
796 789 print(histlines)
797 790 print("=== Output: ===")
798 791 self.run_cell("\n".join(hist), store_history=False)
799 792
800 793
801 794 def init_ipython(ip):
802 795 ip.define_magic("rep", magic_rep)
803 796 ip.define_magic("recall", magic_rep)
804 797 ip.define_magic("rerun", magic_rerun)
805 798 ip.define_magic("hist",magic_history) # Alternative name
806 799 ip.define_magic("history",magic_history)
807 800
808 801 # XXX - ipy_completers are in quarantine, need to be updated to new apis
809 802 #import ipy_completers
810 803 #ipy_completers.quick_completer('%hist' ,'-g -t -r -n')
@@ -1,2603 +1,2608 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Main IPython class."""
3 3
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 7 # Copyright (C) 2008-2011 The IPython Development Team
8 8 #
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16
17 17 from __future__ import with_statement
18 18 from __future__ import absolute_import
19 19
20 20 import __builtin__
21 21 import __future__
22 22 import abc
23 23 import ast
24 24 import atexit
25 25 import codeop
26 26 import inspect
27 27 import os
28 28 import re
29 29 import sys
30 30 import tempfile
31 31 import types
32 32 from contextlib import nested
33 33
34 34 from IPython.config.configurable import Configurable
35 35 from IPython.core import debugger, oinspect
36 36 from IPython.core import history as ipcorehist
37 37 from IPython.core import page
38 38 from IPython.core import prefilter
39 39 from IPython.core import shadowns
40 40 from IPython.core import ultratb
41 41 from IPython.core.alias import AliasManager
42 42 from IPython.core.autocall import ExitAutocall
43 43 from IPython.core.builtin_trap import BuiltinTrap
44 44 from IPython.core.compilerop import CachingCompiler
45 45 from IPython.core.display_trap import DisplayTrap
46 46 from IPython.core.displayhook import DisplayHook
47 47 from IPython.core.displaypub import DisplayPublisher
48 48 from IPython.core.error import TryNext, UsageError
49 49 from IPython.core.extensions import ExtensionManager
50 50 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
51 51 from IPython.core.formatters import DisplayFormatter
52 52 from IPython.core.history import HistoryManager
53 53 from IPython.core.inputsplitter import IPythonInputSplitter
54 54 from IPython.core.logger import Logger
55 55 from IPython.core.macro import Macro
56 56 from IPython.core.magic import Magic
57 57 from IPython.core.payload import PayloadManager
58 58 from IPython.core.plugin import PluginManager
59 59 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
60 60 from IPython.external.Itpl import ItplNS
61 61 from IPython.utils import PyColorize
62 62 from IPython.utils import io
63 63 from IPython.utils.doctestreload import doctest_reload
64 64 from IPython.utils.io import ask_yes_no, rprint
65 65 from IPython.utils.ipstruct import Struct
66 66 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
67 67 from IPython.utils.pickleshare import PickleShareDB
68 68 from IPython.utils.process import system, getoutput
69 69 from IPython.utils.strdispatch import StrDispatch
70 70 from IPython.utils.syspathcontext import prepended_to_syspath
71 71 from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList
72 72 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
73 73 List, Unicode, Instance, Type)
74 74 from IPython.utils.warn import warn, error, fatal
75 75 import IPython.core.hooks
76 76
77 77 #-----------------------------------------------------------------------------
78 78 # Globals
79 79 #-----------------------------------------------------------------------------
80 80
81 81 # compiled regexps for autoindent management
82 82 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
83 83
84 84 #-----------------------------------------------------------------------------
85 85 # Utilities
86 86 #-----------------------------------------------------------------------------
87 87
88 88 # store the builtin raw_input globally, and use this always, in case user code
89 89 # overwrites it (like wx.py.PyShell does)
90 90 raw_input_original = raw_input
91 91
92 92 def softspace(file, newvalue):
93 93 """Copied from code.py, to remove the dependency"""
94 94
95 95 oldvalue = 0
96 96 try:
97 97 oldvalue = file.softspace
98 98 except AttributeError:
99 99 pass
100 100 try:
101 101 file.softspace = newvalue
102 102 except (AttributeError, TypeError):
103 103 # "attribute-less object" or "read-only attributes"
104 104 pass
105 105 return oldvalue
106 106
107 107
108 108 def no_op(*a, **kw): pass
109 109
110 110 class SpaceInInput(Exception): pass
111 111
112 112 class Bunch: pass
113 113
114 114
115 115 def get_default_colors():
116 116 if sys.platform=='darwin':
117 117 return "LightBG"
118 118 elif os.name=='nt':
119 119 return 'Linux'
120 120 else:
121 121 return 'Linux'
122 122
123 123
124 124 class SeparateStr(Str):
125 125 """A Str subclass to validate separate_in, separate_out, etc.
126 126
127 127 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
128 128 """
129 129
130 130 def validate(self, obj, value):
131 131 if value == '0': value = ''
132 132 value = value.replace('\\n','\n')
133 133 return super(SeparateStr, self).validate(obj, value)
134 134
135 135 class MultipleInstanceError(Exception):
136 136 pass
137 137
138 138 class ReadlineNoRecord(object):
139 139 """Context manager to execute some code, then reload readline history
140 140 so that interactive input to the code doesn't appear when pressing up."""
141 141 def __init__(self, shell):
142 142 self.shell = shell
143 143 self._nested_level = 0
144 144
145 145 def __enter__(self):
146 146 if self._nested_level == 0:
147 147 self.orig_length = self.current_length()
148 148 self.readline_tail = self.get_readline_tail()
149 149 self._nested_level += 1
150 150
151 151 def __exit__(self, type, value, traceback):
152 152 self._nested_level -= 1
153 153 if self._nested_level == 0:
154 154 # Try clipping the end if it's got longer
155 155 e = self.current_length() - self.orig_length
156 156 if e > 0:
157 157 for _ in range(e):
158 158 self.shell.readline.remove_history_item(self.orig_length)
159 159
160 160 # If it still doesn't match, just reload readline history.
161 161 if self.current_length() != self.orig_length \
162 162 or self.get_readline_tail() != self.readline_tail:
163 163 self.shell.refill_readline_hist()
164 164 # Returning False will cause exceptions to propagate
165 165 return False
166 166
167 167 def current_length(self):
168 168 return self.shell.readline.get_current_history_length()
169 169
170 170 def get_readline_tail(self, n=10):
171 171 """Get the last n items in readline history."""
172 172 end = self.shell.readline.get_current_history_length() + 1
173 173 start = max(end-n, 1)
174 174 ghi = self.shell.readline.get_history_item
175 175 return [ghi(x) for x in range(start, end)]
176 176
177 177
178 178 #-----------------------------------------------------------------------------
179 179 # Main IPython class
180 180 #-----------------------------------------------------------------------------
181 181
182 182 class InteractiveShell(Configurable, Magic):
183 183 """An enhanced, interactive shell for Python."""
184 184
185 185 _instance = None
186 186 autocall = Enum((0,1,2), default_value=1, config=True)
187 187 # TODO: remove all autoindent logic and put into frontends.
188 188 # We can't do this yet because even runlines uses the autoindent.
189 189 autoindent = CBool(True, config=True)
190 190 automagic = CBool(True, config=True)
191 191 cache_size = Int(1000, config=True)
192 192 color_info = CBool(True, config=True)
193 193 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
194 194 default_value=get_default_colors(), config=True)
195 195 debug = CBool(False, config=True)
196 196 deep_reload = CBool(False, config=True)
197 197 display_formatter = Instance(DisplayFormatter)
198 198 displayhook_class = Type(DisplayHook)
199 199 display_pub_class = Type(DisplayPublisher)
200 200
201 201 exit_now = CBool(False)
202 202 exiter = Instance(ExitAutocall)
203 203 def _exiter_default(self):
204 204 return ExitAutocall(self)
205 205 # Monotonically increasing execution counter
206 206 execution_count = Int(1)
207 207 filename = Unicode("<ipython console>")
208 208 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
209 209
210 210 # Input splitter, to split entire cells of input into either individual
211 211 # interactive statements or whole blocks.
212 212 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
213 213 (), {})
214 214 logstart = CBool(False, config=True)
215 215 logfile = Unicode('', config=True)
216 216 logappend = Unicode('', config=True)
217 217 object_info_string_level = Enum((0,1,2), default_value=0,
218 218 config=True)
219 219 pdb = CBool(False, config=True)
220 220
221 221 profile = Unicode('', config=True)
222 222 prompt_in1 = Str('In [\\#]: ', config=True)
223 223 prompt_in2 = Str(' .\\D.: ', config=True)
224 224 prompt_out = Str('Out[\\#]: ', config=True)
225 225 prompts_pad_left = CBool(True, config=True)
226 226 quiet = CBool(False, config=True)
227 227
228 228 history_length = Int(10000, config=True)
229 229
230 230 # The readline stuff will eventually be moved to the terminal subclass
231 231 # but for now, we can't do that as readline is welded in everywhere.
232 232 readline_use = CBool(True, config=True)
233 233 readline_merge_completions = CBool(True, config=True)
234 234 readline_omit__names = Enum((0,1,2), default_value=2, config=True)
235 235 readline_remove_delims = Str('-/~', config=True)
236 236 readline_parse_and_bind = List([
237 237 'tab: complete',
238 238 '"\C-l": clear-screen',
239 239 'set show-all-if-ambiguous on',
240 240 '"\C-o": tab-insert',
241 241 # See bug gh-58 - with \M-i enabled, chars 0x9000-0x9fff
242 242 # crash IPython.
243 243 '"\M-o": "\d\d\d\d"',
244 244 '"\M-I": "\d\d\d\d"',
245 245 '"\C-r": reverse-search-history',
246 246 '"\C-s": forward-search-history',
247 247 '"\C-p": history-search-backward',
248 248 '"\C-n": history-search-forward',
249 249 '"\e[A": history-search-backward',
250 250 '"\e[B": history-search-forward',
251 251 '"\C-k": kill-line',
252 252 '"\C-u": unix-line-discard',
253 253 ], allow_none=False, config=True)
254 254
255 255 # TODO: this part of prompt management should be moved to the frontends.
256 256 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
257 257 separate_in = SeparateStr('\n', config=True)
258 258 separate_out = SeparateStr('', config=True)
259 259 separate_out2 = SeparateStr('', config=True)
260 260 wildcards_case_sensitive = CBool(True, config=True)
261 261 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
262 262 default_value='Context', config=True)
263 263
264 264 # Subcomponents of InteractiveShell
265 265 alias_manager = Instance('IPython.core.alias.AliasManager')
266 266 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
267 267 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
268 268 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
269 269 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
270 270 plugin_manager = Instance('IPython.core.plugin.PluginManager')
271 271 payload_manager = Instance('IPython.core.payload.PayloadManager')
272 272 history_manager = Instance('IPython.core.history.HistoryManager')
273 273
274 274 # Private interface
275 275 _post_execute = Instance(dict)
276 276
277 277 def __init__(self, config=None, ipython_dir=None,
278 278 user_ns=None, user_global_ns=None,
279 279 custom_exceptions=((), None)):
280 280
281 281 # This is where traits with a config_key argument are updated
282 282 # from the values on config.
283 283 super(InteractiveShell, self).__init__(config=config)
284 284
285 285 # These are relatively independent and stateless
286 286 self.init_ipython_dir(ipython_dir)
287 287 self.init_instance_attrs()
288 288 self.init_environment()
289 289
290 290 # Create namespaces (user_ns, user_global_ns, etc.)
291 291 self.init_create_namespaces(user_ns, user_global_ns)
292 292 # This has to be done after init_create_namespaces because it uses
293 293 # something in self.user_ns, but before init_sys_modules, which
294 294 # is the first thing to modify sys.
295 295 # TODO: When we override sys.stdout and sys.stderr before this class
296 296 # is created, we are saving the overridden ones here. Not sure if this
297 297 # is what we want to do.
298 298 self.save_sys_module_state()
299 299 self.init_sys_modules()
300 300
301 301 # While we're trying to have each part of the code directly access what
302 302 # it needs without keeping redundant references to objects, we have too
303 303 # much legacy code that expects ip.db to exist.
304 304 self.db = PickleShareDB(os.path.join(self.ipython_dir, 'db'))
305 305
306 306 self.init_history()
307 307 self.init_encoding()
308 308 self.init_prefilter()
309 309
310 310 Magic.__init__(self, self)
311 311
312 312 self.init_syntax_highlighting()
313 313 self.init_hooks()
314 314 self.init_pushd_popd_magic()
315 315 # self.init_traceback_handlers use to be here, but we moved it below
316 316 # because it and init_io have to come after init_readline.
317 317 self.init_user_ns()
318 318 self.init_logger()
319 319 self.init_alias()
320 320 self.init_builtins()
321 321
322 322 # pre_config_initialization
323 323
324 324 # The next section should contain everything that was in ipmaker.
325 325 self.init_logstart()
326 326
327 327 # The following was in post_config_initialization
328 328 self.init_inspector()
329 329 # init_readline() must come before init_io(), because init_io uses
330 330 # readline related things.
331 331 self.init_readline()
332 332 # init_completer must come after init_readline, because it needs to
333 333 # know whether readline is present or not system-wide to configure the
334 334 # completers, since the completion machinery can now operate
335 335 # independently of readline (e.g. over the network)
336 336 self.init_completer()
337 337 # TODO: init_io() needs to happen before init_traceback handlers
338 338 # because the traceback handlers hardcode the stdout/stderr streams.
339 339 # This logic in in debugger.Pdb and should eventually be changed.
340 340 self.init_io()
341 341 self.init_traceback_handlers(custom_exceptions)
342 342 self.init_prompts()
343 343 self.init_display_formatter()
344 344 self.init_display_pub()
345 345 self.init_displayhook()
346 346 self.init_reload_doctest()
347 347 self.init_magics()
348 348 self.init_pdb()
349 349 self.init_extension_manager()
350 350 self.init_plugin_manager()
351 351 self.init_payload()
352 352 self.hooks.late_startup_hook()
353 353 atexit.register(self.atexit_operations)
354 354
355 355 @classmethod
356 356 def instance(cls, *args, **kwargs):
357 357 """Returns a global InteractiveShell instance."""
358 358 if cls._instance is None:
359 359 inst = cls(*args, **kwargs)
360 360 # Now make sure that the instance will also be returned by
361 361 # the subclasses instance attribute.
362 362 for subclass in cls.mro():
363 363 if issubclass(cls, subclass) and \
364 364 issubclass(subclass, InteractiveShell):
365 365 subclass._instance = inst
366 366 else:
367 367 break
368 368 if isinstance(cls._instance, cls):
369 369 return cls._instance
370 370 else:
371 371 raise MultipleInstanceError(
372 372 'Multiple incompatible subclass instances of '
373 373 'InteractiveShell are being created.'
374 374 )
375 375
376 376 @classmethod
377 377 def initialized(cls):
378 378 return hasattr(cls, "_instance")
379 379
380 380 def get_ipython(self):
381 381 """Return the currently running IPython instance."""
382 382 return self
383 383
384 384 #-------------------------------------------------------------------------
385 385 # Trait changed handlers
386 386 #-------------------------------------------------------------------------
387 387
388 388 def _ipython_dir_changed(self, name, new):
389 389 if not os.path.isdir(new):
390 390 os.makedirs(new, mode = 0777)
391 391
392 392 def set_autoindent(self,value=None):
393 393 """Set the autoindent flag, checking for readline support.
394 394
395 395 If called with no arguments, it acts as a toggle."""
396 396
397 397 if not self.has_readline:
398 398 if os.name == 'posix':
399 399 warn("The auto-indent feature requires the readline library")
400 400 self.autoindent = 0
401 401 return
402 402 if value is None:
403 403 self.autoindent = not self.autoindent
404 404 else:
405 405 self.autoindent = value
406 406
407 407 #-------------------------------------------------------------------------
408 408 # init_* methods called by __init__
409 409 #-------------------------------------------------------------------------
410 410
411 411 def init_ipython_dir(self, ipython_dir):
412 412 if ipython_dir is not None:
413 413 self.ipython_dir = ipython_dir
414 414 self.config.Global.ipython_dir = self.ipython_dir
415 415 return
416 416
417 417 if hasattr(self.config.Global, 'ipython_dir'):
418 418 self.ipython_dir = self.config.Global.ipython_dir
419 419 else:
420 420 self.ipython_dir = get_ipython_dir()
421 421
422 422 # All children can just read this
423 423 self.config.Global.ipython_dir = self.ipython_dir
424 424
425 425 def init_instance_attrs(self):
426 426 self.more = False
427 427
428 428 # command compiler
429 429 self.compile = CachingCompiler()
430 430
431 431 # User input buffers
432 432 # NOTE: these variables are slated for full removal, once we are 100%
433 433 # sure that the new execution logic is solid. We will delte runlines,
434 434 # push_line and these buffers, as all input will be managed by the
435 435 # frontends via an inputsplitter instance.
436 436 self.buffer = []
437 437 self.buffer_raw = []
438 438
439 439 # Make an empty namespace, which extension writers can rely on both
440 440 # existing and NEVER being used by ipython itself. This gives them a
441 441 # convenient location for storing additional information and state
442 442 # their extensions may require, without fear of collisions with other
443 443 # ipython names that may develop later.
444 444 self.meta = Struct()
445 445
446 446 # Temporary files used for various purposes. Deleted at exit.
447 447 self.tempfiles = []
448 448
449 449 # Keep track of readline usage (later set by init_readline)
450 450 self.has_readline = False
451 451
452 452 # keep track of where we started running (mainly for crash post-mortem)
453 453 # This is not being used anywhere currently.
454 454 self.starting_dir = os.getcwd()
455 455
456 456 # Indentation management
457 457 self.indent_current_nsp = 0
458 458
459 459 # Dict to track post-execution functions that have been registered
460 460 self._post_execute = {}
461 461
462 462 def init_environment(self):
463 463 """Any changes we need to make to the user's environment."""
464 464 pass
465 465
466 466 def init_encoding(self):
467 467 # Get system encoding at startup time. Certain terminals (like Emacs
468 468 # under Win32 have it set to None, and we need to have a known valid
469 469 # encoding to use in the raw_input() method
470 470 try:
471 471 self.stdin_encoding = sys.stdin.encoding or 'ascii'
472 472 except AttributeError:
473 473 self.stdin_encoding = 'ascii'
474 474
475 475 def init_syntax_highlighting(self):
476 476 # Python source parser/formatter for syntax highlighting
477 477 pyformat = PyColorize.Parser().format
478 478 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
479 479
480 480 def init_pushd_popd_magic(self):
481 481 # for pushd/popd management
482 482 try:
483 483 self.home_dir = get_home_dir()
484 484 except HomeDirError, msg:
485 485 fatal(msg)
486 486
487 487 self.dir_stack = []
488 488
489 489 def init_logger(self):
490 490 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
491 491 logmode='rotate')
492 492
493 493 def init_logstart(self):
494 494 """Initialize logging in case it was requested at the command line.
495 495 """
496 496 if self.logappend:
497 497 self.magic_logstart(self.logappend + ' append')
498 498 elif self.logfile:
499 499 self.magic_logstart(self.logfile)
500 500 elif self.logstart:
501 501 self.magic_logstart()
502 502
503 503 def init_builtins(self):
504 504 self.builtin_trap = BuiltinTrap(shell=self)
505 505
506 506 def init_inspector(self):
507 507 # Object inspector
508 508 self.inspector = oinspect.Inspector(oinspect.InspectColors,
509 509 PyColorize.ANSICodeColors,
510 510 'NoColor',
511 511 self.object_info_string_level)
512 512
513 513 def init_io(self):
514 514 # This will just use sys.stdout and sys.stderr. If you want to
515 515 # override sys.stdout and sys.stderr themselves, you need to do that
516 516 # *before* instantiating this class, because Term holds onto
517 517 # references to the underlying streams.
518 518 if sys.platform == 'win32' and self.has_readline:
519 519 Term = io.IOTerm(cout=self.readline._outputfile,
520 520 cerr=self.readline._outputfile)
521 521 else:
522 522 Term = io.IOTerm()
523 523 io.Term = Term
524 524
525 525 def init_prompts(self):
526 526 # TODO: This is a pass for now because the prompts are managed inside
527 527 # the DisplayHook. Once there is a separate prompt manager, this
528 528 # will initialize that object and all prompt related information.
529 529 pass
530 530
531 531 def init_display_formatter(self):
532 532 self.display_formatter = DisplayFormatter(config=self.config)
533 533
534 534 def init_display_pub(self):
535 535 self.display_pub = self.display_pub_class(config=self.config)
536 536
537 537 def init_displayhook(self):
538 538 # Initialize displayhook, set in/out prompts and printing system
539 539 self.displayhook = self.displayhook_class(
540 540 config=self.config,
541 541 shell=self,
542 542 cache_size=self.cache_size,
543 543 input_sep = self.separate_in,
544 544 output_sep = self.separate_out,
545 545 output_sep2 = self.separate_out2,
546 546 ps1 = self.prompt_in1,
547 547 ps2 = self.prompt_in2,
548 548 ps_out = self.prompt_out,
549 549 pad_left = self.prompts_pad_left
550 550 )
551 551 # This is a context manager that installs/revmoes the displayhook at
552 552 # the appropriate time.
553 553 self.display_trap = DisplayTrap(hook=self.displayhook)
554 554
555 555 def init_reload_doctest(self):
556 556 # Do a proper resetting of doctest, including the necessary displayhook
557 557 # monkeypatching
558 558 try:
559 559 doctest_reload()
560 560 except ImportError:
561 561 warn("doctest module does not exist.")
562 562
563 563 #-------------------------------------------------------------------------
564 564 # Things related to injections into the sys module
565 565 #-------------------------------------------------------------------------
566 566
567 567 def save_sys_module_state(self):
568 568 """Save the state of hooks in the sys module.
569 569
570 570 This has to be called after self.user_ns is created.
571 571 """
572 572 self._orig_sys_module_state = {}
573 573 self._orig_sys_module_state['stdin'] = sys.stdin
574 574 self._orig_sys_module_state['stdout'] = sys.stdout
575 575 self._orig_sys_module_state['stderr'] = sys.stderr
576 576 self._orig_sys_module_state['excepthook'] = sys.excepthook
577 577 try:
578 578 self._orig_sys_modules_main_name = self.user_ns['__name__']
579 579 except KeyError:
580 580 pass
581 581
582 582 def restore_sys_module_state(self):
583 583 """Restore the state of the sys module."""
584 584 try:
585 585 for k, v in self._orig_sys_module_state.iteritems():
586 586 setattr(sys, k, v)
587 587 except AttributeError:
588 588 pass
589 589 # Reset what what done in self.init_sys_modules
590 590 try:
591 591 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
592 592 except (AttributeError, KeyError):
593 593 pass
594 594
595 595 #-------------------------------------------------------------------------
596 596 # Things related to hooks
597 597 #-------------------------------------------------------------------------
598 598
599 599 def init_hooks(self):
600 600 # hooks holds pointers used for user-side customizations
601 601 self.hooks = Struct()
602 602
603 603 self.strdispatchers = {}
604 604
605 605 # Set all default hooks, defined in the IPython.hooks module.
606 606 hooks = IPython.core.hooks
607 607 for hook_name in hooks.__all__:
608 608 # default hooks have priority 100, i.e. low; user hooks should have
609 609 # 0-100 priority
610 610 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
611 611
612 612 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
613 613 """set_hook(name,hook) -> sets an internal IPython hook.
614 614
615 615 IPython exposes some of its internal API as user-modifiable hooks. By
616 616 adding your function to one of these hooks, you can modify IPython's
617 617 behavior to call at runtime your own routines."""
618 618
619 619 # At some point in the future, this should validate the hook before it
620 620 # accepts it. Probably at least check that the hook takes the number
621 621 # of args it's supposed to.
622 622
623 623 f = types.MethodType(hook,self)
624 624
625 625 # check if the hook is for strdispatcher first
626 626 if str_key is not None:
627 627 sdp = self.strdispatchers.get(name, StrDispatch())
628 628 sdp.add_s(str_key, f, priority )
629 629 self.strdispatchers[name] = sdp
630 630 return
631 631 if re_key is not None:
632 632 sdp = self.strdispatchers.get(name, StrDispatch())
633 633 sdp.add_re(re.compile(re_key), f, priority )
634 634 self.strdispatchers[name] = sdp
635 635 return
636 636
637 637 dp = getattr(self.hooks, name, None)
638 638 if name not in IPython.core.hooks.__all__:
639 639 print "Warning! Hook '%s' is not one of %s" % \
640 640 (name, IPython.core.hooks.__all__ )
641 641 if not dp:
642 642 dp = IPython.core.hooks.CommandChainDispatcher()
643 643
644 644 try:
645 645 dp.add(f,priority)
646 646 except AttributeError:
647 647 # it was not commandchain, plain old func - replace
648 648 dp = f
649 649
650 650 setattr(self.hooks,name, dp)
651 651
652 652 def register_post_execute(self, func):
653 653 """Register a function for calling after code execution.
654 654 """
655 655 if not callable(func):
656 656 raise ValueError('argument %s must be callable' % func)
657 657 self._post_execute[func] = True
658 658
659 659 #-------------------------------------------------------------------------
660 660 # Things related to the "main" module
661 661 #-------------------------------------------------------------------------
662 662
663 663 def new_main_mod(self,ns=None):
664 664 """Return a new 'main' module object for user code execution.
665 665 """
666 666 main_mod = self._user_main_module
667 667 init_fakemod_dict(main_mod,ns)
668 668 return main_mod
669 669
670 670 def cache_main_mod(self,ns,fname):
671 671 """Cache a main module's namespace.
672 672
673 673 When scripts are executed via %run, we must keep a reference to the
674 674 namespace of their __main__ module (a FakeModule instance) around so
675 675 that Python doesn't clear it, rendering objects defined therein
676 676 useless.
677 677
678 678 This method keeps said reference in a private dict, keyed by the
679 679 absolute path of the module object (which corresponds to the script
680 680 path). This way, for multiple executions of the same script we only
681 681 keep one copy of the namespace (the last one), thus preventing memory
682 682 leaks from old references while allowing the objects from the last
683 683 execution to be accessible.
684 684
685 685 Note: we can not allow the actual FakeModule instances to be deleted,
686 686 because of how Python tears down modules (it hard-sets all their
687 687 references to None without regard for reference counts). This method
688 688 must therefore make a *copy* of the given namespace, to allow the
689 689 original module's __dict__ to be cleared and reused.
690 690
691 691
692 692 Parameters
693 693 ----------
694 694 ns : a namespace (a dict, typically)
695 695
696 696 fname : str
697 697 Filename associated with the namespace.
698 698
699 699 Examples
700 700 --------
701 701
702 702 In [10]: import IPython
703 703
704 704 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
705 705
706 706 In [12]: IPython.__file__ in _ip._main_ns_cache
707 707 Out[12]: True
708 708 """
709 709 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
710 710
711 711 def clear_main_mod_cache(self):
712 712 """Clear the cache of main modules.
713 713
714 714 Mainly for use by utilities like %reset.
715 715
716 716 Examples
717 717 --------
718 718
719 719 In [15]: import IPython
720 720
721 721 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
722 722
723 723 In [17]: len(_ip._main_ns_cache) > 0
724 724 Out[17]: True
725 725
726 726 In [18]: _ip.clear_main_mod_cache()
727 727
728 728 In [19]: len(_ip._main_ns_cache) == 0
729 729 Out[19]: True
730 730 """
731 731 self._main_ns_cache.clear()
732 732
733 733 #-------------------------------------------------------------------------
734 734 # Things related to debugging
735 735 #-------------------------------------------------------------------------
736 736
737 737 def init_pdb(self):
738 738 # Set calling of pdb on exceptions
739 739 # self.call_pdb is a property
740 740 self.call_pdb = self.pdb
741 741
742 742 def _get_call_pdb(self):
743 743 return self._call_pdb
744 744
745 745 def _set_call_pdb(self,val):
746 746
747 747 if val not in (0,1,False,True):
748 748 raise ValueError,'new call_pdb value must be boolean'
749 749
750 750 # store value in instance
751 751 self._call_pdb = val
752 752
753 753 # notify the actual exception handlers
754 754 self.InteractiveTB.call_pdb = val
755 755
756 756 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
757 757 'Control auto-activation of pdb at exceptions')
758 758
759 759 def debugger(self,force=False):
760 760 """Call the pydb/pdb debugger.
761 761
762 762 Keywords:
763 763
764 764 - force(False): by default, this routine checks the instance call_pdb
765 765 flag and does not actually invoke the debugger if the flag is false.
766 766 The 'force' option forces the debugger to activate even if the flag
767 767 is false.
768 768 """
769 769
770 770 if not (force or self.call_pdb):
771 771 return
772 772
773 773 if not hasattr(sys,'last_traceback'):
774 774 error('No traceback has been produced, nothing to debug.')
775 775 return
776 776
777 777 # use pydb if available
778 778 if debugger.has_pydb:
779 779 from pydb import pm
780 780 else:
781 781 # fallback to our internal debugger
782 782 pm = lambda : self.InteractiveTB.debugger(force=True)
783 783
784 784 with self.readline_no_record:
785 785 pm()
786 786
787 787 #-------------------------------------------------------------------------
788 788 # Things related to IPython's various namespaces
789 789 #-------------------------------------------------------------------------
790 790
791 791 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
792 792 # Create the namespace where the user will operate. user_ns is
793 793 # normally the only one used, and it is passed to the exec calls as
794 794 # the locals argument. But we do carry a user_global_ns namespace
795 795 # given as the exec 'globals' argument, This is useful in embedding
796 796 # situations where the ipython shell opens in a context where the
797 797 # distinction between locals and globals is meaningful. For
798 798 # non-embedded contexts, it is just the same object as the user_ns dict.
799 799
800 800 # FIXME. For some strange reason, __builtins__ is showing up at user
801 801 # level as a dict instead of a module. This is a manual fix, but I
802 802 # should really track down where the problem is coming from. Alex
803 803 # Schmolck reported this problem first.
804 804
805 805 # A useful post by Alex Martelli on this topic:
806 806 # Re: inconsistent value from __builtins__
807 807 # Von: Alex Martelli <aleaxit@yahoo.com>
808 808 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
809 809 # Gruppen: comp.lang.python
810 810
811 811 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
812 812 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
813 813 # > <type 'dict'>
814 814 # > >>> print type(__builtins__)
815 815 # > <type 'module'>
816 816 # > Is this difference in return value intentional?
817 817
818 818 # Well, it's documented that '__builtins__' can be either a dictionary
819 819 # or a module, and it's been that way for a long time. Whether it's
820 820 # intentional (or sensible), I don't know. In any case, the idea is
821 821 # that if you need to access the built-in namespace directly, you
822 822 # should start with "import __builtin__" (note, no 's') which will
823 823 # definitely give you a module. Yeah, it's somewhat confusing:-(.
824 824
825 825 # These routines return properly built dicts as needed by the rest of
826 826 # the code, and can also be used by extension writers to generate
827 827 # properly initialized namespaces.
828 828 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
829 829 user_global_ns)
830 830
831 831 # Assign namespaces
832 832 # This is the namespace where all normal user variables live
833 833 self.user_ns = user_ns
834 834 self.user_global_ns = user_global_ns
835 835
836 836 # An auxiliary namespace that checks what parts of the user_ns were
837 837 # loaded at startup, so we can list later only variables defined in
838 838 # actual interactive use. Since it is always a subset of user_ns, it
839 839 # doesn't need to be separately tracked in the ns_table.
840 840 self.user_ns_hidden = {}
841 841
842 842 # A namespace to keep track of internal data structures to prevent
843 843 # them from cluttering user-visible stuff. Will be updated later
844 844 self.internal_ns = {}
845 845
846 846 # Now that FakeModule produces a real module, we've run into a nasty
847 847 # problem: after script execution (via %run), the module where the user
848 848 # code ran is deleted. Now that this object is a true module (needed
849 849 # so docetst and other tools work correctly), the Python module
850 850 # teardown mechanism runs over it, and sets to None every variable
851 851 # present in that module. Top-level references to objects from the
852 852 # script survive, because the user_ns is updated with them. However,
853 853 # calling functions defined in the script that use other things from
854 854 # the script will fail, because the function's closure had references
855 855 # to the original objects, which are now all None. So we must protect
856 856 # these modules from deletion by keeping a cache.
857 857 #
858 858 # To avoid keeping stale modules around (we only need the one from the
859 859 # last run), we use a dict keyed with the full path to the script, so
860 860 # only the last version of the module is held in the cache. Note,
861 861 # however, that we must cache the module *namespace contents* (their
862 862 # __dict__). Because if we try to cache the actual modules, old ones
863 863 # (uncached) could be destroyed while still holding references (such as
864 864 # those held by GUI objects that tend to be long-lived)>
865 865 #
866 866 # The %reset command will flush this cache. See the cache_main_mod()
867 867 # and clear_main_mod_cache() methods for details on use.
868 868
869 869 # This is the cache used for 'main' namespaces
870 870 self._main_ns_cache = {}
871 871 # And this is the single instance of FakeModule whose __dict__ we keep
872 872 # copying and clearing for reuse on each %run
873 873 self._user_main_module = FakeModule()
874 874
875 875 # A table holding all the namespaces IPython deals with, so that
876 876 # introspection facilities can search easily.
877 877 self.ns_table = {'user':user_ns,
878 878 'user_global':user_global_ns,
879 879 'internal':self.internal_ns,
880 880 'builtin':__builtin__.__dict__
881 881 }
882 882
883 883 # Similarly, track all namespaces where references can be held and that
884 884 # we can safely clear (so it can NOT include builtin). This one can be
885 885 # a simple list. Note that the main execution namespaces, user_ns and
886 886 # user_global_ns, can NOT be listed here, as clearing them blindly
887 887 # causes errors in object __del__ methods. Instead, the reset() method
888 888 # clears them manually and carefully.
889 889 self.ns_refs_table = [ self.user_ns_hidden,
890 890 self.internal_ns, self._main_ns_cache ]
891 891
892 892 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
893 893 """Return a valid local and global user interactive namespaces.
894 894
895 895 This builds a dict with the minimal information needed to operate as a
896 896 valid IPython user namespace, which you can pass to the various
897 897 embedding classes in ipython. The default implementation returns the
898 898 same dict for both the locals and the globals to allow functions to
899 899 refer to variables in the namespace. Customized implementations can
900 900 return different dicts. The locals dictionary can actually be anything
901 901 following the basic mapping protocol of a dict, but the globals dict
902 902 must be a true dict, not even a subclass. It is recommended that any
903 903 custom object for the locals namespace synchronize with the globals
904 904 dict somehow.
905 905
906 906 Raises TypeError if the provided globals namespace is not a true dict.
907 907
908 908 Parameters
909 909 ----------
910 910 user_ns : dict-like, optional
911 911 The current user namespace. The items in this namespace should
912 912 be included in the output. If None, an appropriate blank
913 913 namespace should be created.
914 914 user_global_ns : dict, optional
915 915 The current user global namespace. The items in this namespace
916 916 should be included in the output. If None, an appropriate
917 917 blank namespace should be created.
918 918
919 919 Returns
920 920 -------
921 921 A pair of dictionary-like object to be used as the local namespace
922 922 of the interpreter and a dict to be used as the global namespace.
923 923 """
924 924
925 925
926 926 # We must ensure that __builtin__ (without the final 's') is always
927 927 # available and pointing to the __builtin__ *module*. For more details:
928 928 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
929 929
930 930 if user_ns is None:
931 931 # Set __name__ to __main__ to better match the behavior of the
932 932 # normal interpreter.
933 933 user_ns = {'__name__' :'__main__',
934 934 '__builtin__' : __builtin__,
935 935 '__builtins__' : __builtin__,
936 936 }
937 937 else:
938 938 user_ns.setdefault('__name__','__main__')
939 939 user_ns.setdefault('__builtin__',__builtin__)
940 940 user_ns.setdefault('__builtins__',__builtin__)
941 941
942 942 if user_global_ns is None:
943 943 user_global_ns = user_ns
944 944 if type(user_global_ns) is not dict:
945 945 raise TypeError("user_global_ns must be a true dict; got %r"
946 946 % type(user_global_ns))
947 947
948 948 return user_ns, user_global_ns
949 949
950 950 def init_sys_modules(self):
951 951 # We need to insert into sys.modules something that looks like a
952 952 # module but which accesses the IPython namespace, for shelve and
953 953 # pickle to work interactively. Normally they rely on getting
954 954 # everything out of __main__, but for embedding purposes each IPython
955 955 # instance has its own private namespace, so we can't go shoving
956 956 # everything into __main__.
957 957
958 958 # note, however, that we should only do this for non-embedded
959 959 # ipythons, which really mimic the __main__.__dict__ with their own
960 960 # namespace. Embedded instances, on the other hand, should not do
961 961 # this because they need to manage the user local/global namespaces
962 962 # only, but they live within a 'normal' __main__ (meaning, they
963 963 # shouldn't overtake the execution environment of the script they're
964 964 # embedded in).
965 965
966 966 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
967 967
968 968 try:
969 969 main_name = self.user_ns['__name__']
970 970 except KeyError:
971 971 raise KeyError('user_ns dictionary MUST have a "__name__" key')
972 972 else:
973 973 sys.modules[main_name] = FakeModule(self.user_ns)
974 974
975 975 def init_user_ns(self):
976 976 """Initialize all user-visible namespaces to their minimum defaults.
977 977
978 978 Certain history lists are also initialized here, as they effectively
979 979 act as user namespaces.
980 980
981 981 Notes
982 982 -----
983 983 All data structures here are only filled in, they are NOT reset by this
984 984 method. If they were not empty before, data will simply be added to
985 985 therm.
986 986 """
987 987 # This function works in two parts: first we put a few things in
988 988 # user_ns, and we sync that contents into user_ns_hidden so that these
989 989 # initial variables aren't shown by %who. After the sync, we add the
990 990 # rest of what we *do* want the user to see with %who even on a new
991 991 # session (probably nothing, so theye really only see their own stuff)
992 992
993 993 # The user dict must *always* have a __builtin__ reference to the
994 994 # Python standard __builtin__ namespace, which must be imported.
995 995 # This is so that certain operations in prompt evaluation can be
996 996 # reliably executed with builtins. Note that we can NOT use
997 997 # __builtins__ (note the 's'), because that can either be a dict or a
998 998 # module, and can even mutate at runtime, depending on the context
999 999 # (Python makes no guarantees on it). In contrast, __builtin__ is
1000 1000 # always a module object, though it must be explicitly imported.
1001 1001
1002 1002 # For more details:
1003 1003 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1004 1004 ns = dict(__builtin__ = __builtin__)
1005 1005
1006 1006 # Put 'help' in the user namespace
1007 1007 try:
1008 1008 from site import _Helper
1009 1009 ns['help'] = _Helper()
1010 1010 except ImportError:
1011 1011 warn('help() not available - check site.py')
1012 1012
1013 1013 # make global variables for user access to the histories
1014 1014 ns['_ih'] = self.history_manager.input_hist_parsed
1015 1015 ns['_oh'] = self.history_manager.output_hist
1016 1016 ns['_dh'] = self.history_manager.dir_hist
1017 1017
1018 1018 ns['_sh'] = shadowns
1019 1019
1020 1020 # user aliases to input and output histories. These shouldn't show up
1021 1021 # in %who, as they can have very large reprs.
1022 1022 ns['In'] = self.history_manager.input_hist_parsed
1023 1023 ns['Out'] = self.history_manager.output_hist
1024 1024
1025 1025 # Store myself as the public api!!!
1026 1026 ns['get_ipython'] = self.get_ipython
1027 1027
1028 1028 ns['exit'] = self.exiter
1029 1029 ns['quit'] = self.exiter
1030 1030
1031 1031 # Sync what we've added so far to user_ns_hidden so these aren't seen
1032 1032 # by %who
1033 1033 self.user_ns_hidden.update(ns)
1034 1034
1035 1035 # Anything put into ns now would show up in %who. Think twice before
1036 1036 # putting anything here, as we really want %who to show the user their
1037 1037 # stuff, not our variables.
1038 1038
1039 1039 # Finally, update the real user's namespace
1040 1040 self.user_ns.update(ns)
1041 1041
1042 1042 def reset(self, new_session=True):
1043 1043 """Clear all internal namespaces.
1044 1044
1045 1045 Note that this is much more aggressive than %reset, since it clears
1046 1046 fully all namespaces, as well as all input/output lists.
1047 1047
1048 1048 If new_session is True, a new history session will be opened.
1049 1049 """
1050 1050 # Clear histories
1051 1051 self.history_manager.reset(new_session)
1052 1052 # Reset counter used to index all histories
1053 1053 if new_session:
1054 1054 self.execution_count = 1
1055 1055
1056 1056 # Flush cached output items
1057 1057 self.displayhook.flush()
1058 1058
1059 1059 # Restore the user namespaces to minimal usability
1060 1060 for ns in self.ns_refs_table:
1061 1061 ns.clear()
1062 1062
1063 1063 # The main execution namespaces must be cleared very carefully,
1064 1064 # skipping the deletion of the builtin-related keys, because doing so
1065 1065 # would cause errors in many object's __del__ methods.
1066 1066 for ns in [self.user_ns, self.user_global_ns]:
1067 1067 drop_keys = set(ns.keys())
1068 1068 drop_keys.discard('__builtin__')
1069 1069 drop_keys.discard('__builtins__')
1070 1070 for k in drop_keys:
1071 1071 del ns[k]
1072 1072
1073 1073 # Restore the user namespaces to minimal usability
1074 1074 self.init_user_ns()
1075 1075
1076 1076 # Restore the default and user aliases
1077 1077 self.alias_manager.clear_aliases()
1078 1078 self.alias_manager.init_aliases()
1079 1079
1080 1080 # Flush the private list of module references kept for script
1081 1081 # execution protection
1082 1082 self.clear_main_mod_cache()
1083 1083
1084 1084 def reset_selective(self, regex=None):
1085 1085 """Clear selective variables from internal namespaces based on a
1086 1086 specified regular expression.
1087 1087
1088 1088 Parameters
1089 1089 ----------
1090 1090 regex : string or compiled pattern, optional
1091 1091 A regular expression pattern that will be used in searching
1092 1092 variable names in the users namespaces.
1093 1093 """
1094 1094 if regex is not None:
1095 1095 try:
1096 1096 m = re.compile(regex)
1097 1097 except TypeError:
1098 1098 raise TypeError('regex must be a string or compiled pattern')
1099 1099 # Search for keys in each namespace that match the given regex
1100 1100 # If a match is found, delete the key/value pair.
1101 1101 for ns in self.ns_refs_table:
1102 1102 for var in ns:
1103 1103 if m.search(var):
1104 1104 del ns[var]
1105 1105
1106 1106 def push(self, variables, interactive=True):
1107 1107 """Inject a group of variables into the IPython user namespace.
1108 1108
1109 1109 Parameters
1110 1110 ----------
1111 1111 variables : dict, str or list/tuple of str
1112 1112 The variables to inject into the user's namespace. If a dict, a
1113 1113 simple update is done. If a str, the string is assumed to have
1114 1114 variable names separated by spaces. A list/tuple of str can also
1115 1115 be used to give the variable names. If just the variable names are
1116 1116 give (list/tuple/str) then the variable values looked up in the
1117 1117 callers frame.
1118 1118 interactive : bool
1119 1119 If True (default), the variables will be listed with the ``who``
1120 1120 magic.
1121 1121 """
1122 1122 vdict = None
1123 1123
1124 1124 # We need a dict of name/value pairs to do namespace updates.
1125 1125 if isinstance(variables, dict):
1126 1126 vdict = variables
1127 1127 elif isinstance(variables, (basestring, list, tuple)):
1128 1128 if isinstance(variables, basestring):
1129 1129 vlist = variables.split()
1130 1130 else:
1131 1131 vlist = variables
1132 1132 vdict = {}
1133 1133 cf = sys._getframe(1)
1134 1134 for name in vlist:
1135 1135 try:
1136 1136 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1137 1137 except:
1138 1138 print ('Could not get variable %s from %s' %
1139 1139 (name,cf.f_code.co_name))
1140 1140 else:
1141 1141 raise ValueError('variables must be a dict/str/list/tuple')
1142 1142
1143 1143 # Propagate variables to user namespace
1144 1144 self.user_ns.update(vdict)
1145 1145
1146 1146 # And configure interactive visibility
1147 1147 config_ns = self.user_ns_hidden
1148 1148 if interactive:
1149 1149 for name, val in vdict.iteritems():
1150 1150 config_ns.pop(name, None)
1151 1151 else:
1152 1152 for name,val in vdict.iteritems():
1153 1153 config_ns[name] = val
1154 1154
1155 1155 #-------------------------------------------------------------------------
1156 1156 # Things related to object introspection
1157 1157 #-------------------------------------------------------------------------
1158 1158
1159 1159 def _ofind(self, oname, namespaces=None):
1160 1160 """Find an object in the available namespaces.
1161 1161
1162 1162 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1163 1163
1164 1164 Has special code to detect magic functions.
1165 1165 """
1166 1166 #oname = oname.strip()
1167 1167 #print '1- oname: <%r>' % oname # dbg
1168 1168 try:
1169 1169 oname = oname.strip().encode('ascii')
1170 1170 #print '2- oname: <%r>' % oname # dbg
1171 1171 except UnicodeEncodeError:
1172 1172 print 'Python identifiers can only contain ascii characters.'
1173 1173 return dict(found=False)
1174 1174
1175 1175 alias_ns = None
1176 1176 if namespaces is None:
1177 1177 # Namespaces to search in:
1178 1178 # Put them in a list. The order is important so that we
1179 1179 # find things in the same order that Python finds them.
1180 1180 namespaces = [ ('Interactive', self.user_ns),
1181 1181 ('IPython internal', self.internal_ns),
1182 1182 ('Python builtin', __builtin__.__dict__),
1183 1183 ('Alias', self.alias_manager.alias_table),
1184 1184 ]
1185 1185 alias_ns = self.alias_manager.alias_table
1186 1186
1187 1187 # initialize results to 'null'
1188 1188 found = False; obj = None; ospace = None; ds = None;
1189 1189 ismagic = False; isalias = False; parent = None
1190 1190
1191 1191 # We need to special-case 'print', which as of python2.6 registers as a
1192 1192 # function but should only be treated as one if print_function was
1193 1193 # loaded with a future import. In this case, just bail.
1194 1194 if (oname == 'print' and not (self.compile.compiler_flags &
1195 1195 __future__.CO_FUTURE_PRINT_FUNCTION)):
1196 1196 return {'found':found, 'obj':obj, 'namespace':ospace,
1197 1197 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1198 1198
1199 1199 # Look for the given name by splitting it in parts. If the head is
1200 1200 # found, then we look for all the remaining parts as members, and only
1201 1201 # declare success if we can find them all.
1202 1202 oname_parts = oname.split('.')
1203 1203 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1204 1204 for nsname,ns in namespaces:
1205 1205 try:
1206 1206 obj = ns[oname_head]
1207 1207 except KeyError:
1208 1208 continue
1209 1209 else:
1210 1210 #print 'oname_rest:', oname_rest # dbg
1211 1211 for part in oname_rest:
1212 1212 try:
1213 1213 parent = obj
1214 1214 obj = getattr(obj,part)
1215 1215 except:
1216 1216 # Blanket except b/c some badly implemented objects
1217 1217 # allow __getattr__ to raise exceptions other than
1218 1218 # AttributeError, which then crashes IPython.
1219 1219 break
1220 1220 else:
1221 1221 # If we finish the for loop (no break), we got all members
1222 1222 found = True
1223 1223 ospace = nsname
1224 1224 if ns == alias_ns:
1225 1225 isalias = True
1226 1226 break # namespace loop
1227 1227
1228 1228 # Try to see if it's magic
1229 1229 if not found:
1230 1230 if oname.startswith(ESC_MAGIC):
1231 1231 oname = oname[1:]
1232 1232 obj = getattr(self,'magic_'+oname,None)
1233 1233 if obj is not None:
1234 1234 found = True
1235 1235 ospace = 'IPython internal'
1236 1236 ismagic = True
1237 1237
1238 1238 # Last try: special-case some literals like '', [], {}, etc:
1239 1239 if not found and oname_head in ["''",'""','[]','{}','()']:
1240 1240 obj = eval(oname_head)
1241 1241 found = True
1242 1242 ospace = 'Interactive'
1243 1243
1244 1244 return {'found':found, 'obj':obj, 'namespace':ospace,
1245 1245 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1246 1246
1247 1247 def _ofind_property(self, oname, info):
1248 1248 """Second part of object finding, to look for property details."""
1249 1249 if info.found:
1250 1250 # Get the docstring of the class property if it exists.
1251 1251 path = oname.split('.')
1252 1252 root = '.'.join(path[:-1])
1253 1253 if info.parent is not None:
1254 1254 try:
1255 1255 target = getattr(info.parent, '__class__')
1256 1256 # The object belongs to a class instance.
1257 1257 try:
1258 1258 target = getattr(target, path[-1])
1259 1259 # The class defines the object.
1260 1260 if isinstance(target, property):
1261 1261 oname = root + '.__class__.' + path[-1]
1262 1262 info = Struct(self._ofind(oname))
1263 1263 except AttributeError: pass
1264 1264 except AttributeError: pass
1265 1265
1266 1266 # We return either the new info or the unmodified input if the object
1267 1267 # hadn't been found
1268 1268 return info
1269 1269
1270 1270 def _object_find(self, oname, namespaces=None):
1271 1271 """Find an object and return a struct with info about it."""
1272 1272 inf = Struct(self._ofind(oname, namespaces))
1273 1273 return Struct(self._ofind_property(oname, inf))
1274 1274
1275 1275 def _inspect(self, meth, oname, namespaces=None, **kw):
1276 1276 """Generic interface to the inspector system.
1277 1277
1278 1278 This function is meant to be called by pdef, pdoc & friends."""
1279 1279 info = self._object_find(oname)
1280 1280 if info.found:
1281 1281 pmethod = getattr(self.inspector, meth)
1282 1282 formatter = format_screen if info.ismagic else None
1283 1283 if meth == 'pdoc':
1284 1284 pmethod(info.obj, oname, formatter)
1285 1285 elif meth == 'pinfo':
1286 1286 pmethod(info.obj, oname, formatter, info, **kw)
1287 1287 else:
1288 1288 pmethod(info.obj, oname)
1289 1289 else:
1290 1290 print 'Object `%s` not found.' % oname
1291 1291 return 'not found' # so callers can take other action
1292 1292
1293 1293 def object_inspect(self, oname):
1294 1294 with self.builtin_trap:
1295 1295 info = self._object_find(oname)
1296 1296 if info.found:
1297 1297 return self.inspector.info(info.obj, oname, info=info)
1298 1298 else:
1299 1299 return oinspect.object_info(name=oname, found=False)
1300 1300
1301 1301 #-------------------------------------------------------------------------
1302 1302 # Things related to history management
1303 1303 #-------------------------------------------------------------------------
1304 1304
1305 1305 def init_history(self):
1306 1306 """Sets up the command history, and starts regular autosaves."""
1307 1307 self.history_manager = HistoryManager(shell=self, config=self.config)
1308 1308
1309 1309 #-------------------------------------------------------------------------
1310 1310 # Things related to exception handling and tracebacks (not debugging)
1311 1311 #-------------------------------------------------------------------------
1312 1312
1313 1313 def init_traceback_handlers(self, custom_exceptions):
1314 1314 # Syntax error handler.
1315 1315 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1316 1316
1317 1317 # The interactive one is initialized with an offset, meaning we always
1318 1318 # want to remove the topmost item in the traceback, which is our own
1319 1319 # internal code. Valid modes: ['Plain','Context','Verbose']
1320 1320 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1321 1321 color_scheme='NoColor',
1322 1322 tb_offset = 1,
1323 1323 check_cache=self.compile.check_cache)
1324 1324
1325 1325 # The instance will store a pointer to the system-wide exception hook,
1326 1326 # so that runtime code (such as magics) can access it. This is because
1327 1327 # during the read-eval loop, it may get temporarily overwritten.
1328 1328 self.sys_excepthook = sys.excepthook
1329 1329
1330 1330 # and add any custom exception handlers the user may have specified
1331 1331 self.set_custom_exc(*custom_exceptions)
1332 1332
1333 1333 # Set the exception mode
1334 1334 self.InteractiveTB.set_mode(mode=self.xmode)
1335 1335
1336 1336 def set_custom_exc(self, exc_tuple, handler):
1337 1337 """set_custom_exc(exc_tuple,handler)
1338 1338
1339 1339 Set a custom exception handler, which will be called if any of the
1340 1340 exceptions in exc_tuple occur in the mainloop (specifically, in the
1341 1341 run_code() method.
1342 1342
1343 1343 Inputs:
1344 1344
1345 1345 - exc_tuple: a *tuple* of valid exceptions to call the defined
1346 1346 handler for. It is very important that you use a tuple, and NOT A
1347 1347 LIST here, because of the way Python's except statement works. If
1348 1348 you only want to trap a single exception, use a singleton tuple:
1349 1349
1350 1350 exc_tuple == (MyCustomException,)
1351 1351
1352 1352 - handler: this must be defined as a function with the following
1353 1353 basic interface::
1354 1354
1355 1355 def my_handler(self, etype, value, tb, tb_offset=None)
1356 1356 ...
1357 1357 # The return value must be
1358 1358 return structured_traceback
1359 1359
1360 1360 This will be made into an instance method (via types.MethodType)
1361 1361 of IPython itself, and it will be called if any of the exceptions
1362 1362 listed in the exc_tuple are caught. If the handler is None, an
1363 1363 internal basic one is used, which just prints basic info.
1364 1364
1365 1365 WARNING: by putting in your own exception handler into IPython's main
1366 1366 execution loop, you run a very good chance of nasty crashes. This
1367 1367 facility should only be used if you really know what you are doing."""
1368 1368
1369 1369 assert type(exc_tuple)==type(()) , \
1370 1370 "The custom exceptions must be given AS A TUPLE."
1371 1371
1372 1372 def dummy_handler(self,etype,value,tb):
1373 1373 print '*** Simple custom exception handler ***'
1374 1374 print 'Exception type :',etype
1375 1375 print 'Exception value:',value
1376 1376 print 'Traceback :',tb
1377 1377 print 'Source code :','\n'.join(self.buffer)
1378 1378
1379 1379 if handler is None: handler = dummy_handler
1380 1380
1381 1381 self.CustomTB = types.MethodType(handler,self)
1382 1382 self.custom_exceptions = exc_tuple
1383 1383
1384 1384 def excepthook(self, etype, value, tb):
1385 1385 """One more defense for GUI apps that call sys.excepthook.
1386 1386
1387 1387 GUI frameworks like wxPython trap exceptions and call
1388 1388 sys.excepthook themselves. I guess this is a feature that
1389 1389 enables them to keep running after exceptions that would
1390 1390 otherwise kill their mainloop. This is a bother for IPython
1391 1391 which excepts to catch all of the program exceptions with a try:
1392 1392 except: statement.
1393 1393
1394 1394 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1395 1395 any app directly invokes sys.excepthook, it will look to the user like
1396 1396 IPython crashed. In order to work around this, we can disable the
1397 1397 CrashHandler and replace it with this excepthook instead, which prints a
1398 1398 regular traceback using our InteractiveTB. In this fashion, apps which
1399 1399 call sys.excepthook will generate a regular-looking exception from
1400 1400 IPython, and the CrashHandler will only be triggered by real IPython
1401 1401 crashes.
1402 1402
1403 1403 This hook should be used sparingly, only in places which are not likely
1404 1404 to be true IPython errors.
1405 1405 """
1406 1406 self.showtraceback((etype,value,tb),tb_offset=0)
1407 1407
1408 1408 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1409 1409 exception_only=False):
1410 1410 """Display the exception that just occurred.
1411 1411
1412 1412 If nothing is known about the exception, this is the method which
1413 1413 should be used throughout the code for presenting user tracebacks,
1414 1414 rather than directly invoking the InteractiveTB object.
1415 1415
1416 1416 A specific showsyntaxerror() also exists, but this method can take
1417 1417 care of calling it if needed, so unless you are explicitly catching a
1418 1418 SyntaxError exception, don't try to analyze the stack manually and
1419 1419 simply call this method."""
1420 1420
1421 1421 try:
1422 1422 if exc_tuple is None:
1423 1423 etype, value, tb = sys.exc_info()
1424 1424 else:
1425 1425 etype, value, tb = exc_tuple
1426 1426
1427 1427 if etype is None:
1428 1428 if hasattr(sys, 'last_type'):
1429 1429 etype, value, tb = sys.last_type, sys.last_value, \
1430 1430 sys.last_traceback
1431 1431 else:
1432 1432 self.write_err('No traceback available to show.\n')
1433 1433 return
1434 1434
1435 1435 if etype is SyntaxError:
1436 1436 # Though this won't be called by syntax errors in the input
1437 1437 # line, there may be SyntaxError cases whith imported code.
1438 1438 self.showsyntaxerror(filename)
1439 1439 elif etype is UsageError:
1440 1440 print "UsageError:", value
1441 1441 else:
1442 1442 # WARNING: these variables are somewhat deprecated and not
1443 1443 # necessarily safe to use in a threaded environment, but tools
1444 1444 # like pdb depend on their existence, so let's set them. If we
1445 1445 # find problems in the field, we'll need to revisit their use.
1446 1446 sys.last_type = etype
1447 1447 sys.last_value = value
1448 1448 sys.last_traceback = tb
1449 1449 if etype in self.custom_exceptions:
1450 1450 # FIXME: Old custom traceback objects may just return a
1451 1451 # string, in that case we just put it into a list
1452 1452 stb = self.CustomTB(etype, value, tb, tb_offset)
1453 1453 if isinstance(ctb, basestring):
1454 1454 stb = [stb]
1455 1455 else:
1456 1456 if exception_only:
1457 1457 stb = ['An exception has occurred, use %tb to see '
1458 1458 'the full traceback.\n']
1459 1459 stb.extend(self.InteractiveTB.get_exception_only(etype,
1460 1460 value))
1461 1461 else:
1462 1462 stb = self.InteractiveTB.structured_traceback(etype,
1463 1463 value, tb, tb_offset=tb_offset)
1464 1464
1465 1465 if self.call_pdb:
1466 1466 # drop into debugger
1467 1467 self.debugger(force=True)
1468 1468
1469 1469 # Actually show the traceback
1470 1470 self._showtraceback(etype, value, stb)
1471 1471
1472 1472 except KeyboardInterrupt:
1473 1473 self.write_err("\nKeyboardInterrupt\n")
1474 1474
1475 1475 def _showtraceback(self, etype, evalue, stb):
1476 1476 """Actually show a traceback.
1477 1477
1478 1478 Subclasses may override this method to put the traceback on a different
1479 1479 place, like a side channel.
1480 1480 """
1481 1481 print >> io.Term.cout, self.InteractiveTB.stb2text(stb)
1482 1482
1483 1483 def showsyntaxerror(self, filename=None):
1484 1484 """Display the syntax error that just occurred.
1485 1485
1486 1486 This doesn't display a stack trace because there isn't one.
1487 1487
1488 1488 If a filename is given, it is stuffed in the exception instead
1489 1489 of what was there before (because Python's parser always uses
1490 1490 "<string>" when reading from a string).
1491 1491 """
1492 1492 etype, value, last_traceback = sys.exc_info()
1493 1493
1494 1494 # See note about these variables in showtraceback() above
1495 1495 sys.last_type = etype
1496 1496 sys.last_value = value
1497 1497 sys.last_traceback = last_traceback
1498 1498
1499 1499 if filename and etype is SyntaxError:
1500 1500 # Work hard to stuff the correct filename in the exception
1501 1501 try:
1502 1502 msg, (dummy_filename, lineno, offset, line) = value
1503 1503 except:
1504 1504 # Not the format we expect; leave it alone
1505 1505 pass
1506 1506 else:
1507 1507 # Stuff in the right filename
1508 1508 try:
1509 1509 # Assume SyntaxError is a class exception
1510 1510 value = SyntaxError(msg, (filename, lineno, offset, line))
1511 1511 except:
1512 1512 # If that failed, assume SyntaxError is a string
1513 1513 value = msg, (filename, lineno, offset, line)
1514 1514 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1515 1515 self._showtraceback(etype, value, stb)
1516 1516
1517 1517 #-------------------------------------------------------------------------
1518 1518 # Things related to readline
1519 1519 #-------------------------------------------------------------------------
1520 1520
1521 1521 def init_readline(self):
1522 1522 """Command history completion/saving/reloading."""
1523 1523
1524 1524 if self.readline_use:
1525 1525 import IPython.utils.rlineimpl as readline
1526 1526
1527 1527 self.rl_next_input = None
1528 1528 self.rl_do_indent = False
1529 1529
1530 1530 if not self.readline_use or not readline.have_readline:
1531 1531 self.has_readline = False
1532 1532 self.readline = None
1533 1533 # Set a number of methods that depend on readline to be no-op
1534 1534 self.set_readline_completer = no_op
1535 1535 self.set_custom_completer = no_op
1536 1536 self.set_completer_frame = no_op
1537 1537 warn('Readline services not available or not loaded.')
1538 1538 else:
1539 1539 self.has_readline = True
1540 1540 self.readline = readline
1541 1541 sys.modules['readline'] = readline
1542 1542
1543 1543 # Platform-specific configuration
1544 1544 if os.name == 'nt':
1545 1545 # FIXME - check with Frederick to see if we can harmonize
1546 1546 # naming conventions with pyreadline to avoid this
1547 1547 # platform-dependent check
1548 1548 self.readline_startup_hook = readline.set_pre_input_hook
1549 1549 else:
1550 1550 self.readline_startup_hook = readline.set_startup_hook
1551 1551
1552 1552 # Load user's initrc file (readline config)
1553 1553 # Or if libedit is used, load editrc.
1554 1554 inputrc_name = os.environ.get('INPUTRC')
1555 1555 if inputrc_name is None:
1556 1556 home_dir = get_home_dir()
1557 1557 if home_dir is not None:
1558 1558 inputrc_name = '.inputrc'
1559 1559 if readline.uses_libedit:
1560 1560 inputrc_name = '.editrc'
1561 1561 inputrc_name = os.path.join(home_dir, inputrc_name)
1562 1562 if os.path.isfile(inputrc_name):
1563 1563 try:
1564 1564 readline.read_init_file(inputrc_name)
1565 1565 except:
1566 1566 warn('Problems reading readline initialization file <%s>'
1567 1567 % inputrc_name)
1568 1568
1569 1569 # Configure readline according to user's prefs
1570 1570 # This is only done if GNU readline is being used. If libedit
1571 1571 # is being used (as on Leopard) the readline config is
1572 1572 # not run as the syntax for libedit is different.
1573 1573 if not readline.uses_libedit:
1574 1574 for rlcommand in self.readline_parse_and_bind:
1575 1575 #print "loading rl:",rlcommand # dbg
1576 1576 readline.parse_and_bind(rlcommand)
1577 1577
1578 1578 # Remove some chars from the delimiters list. If we encounter
1579 1579 # unicode chars, discard them.
1580 1580 delims = readline.get_completer_delims().encode("ascii", "ignore")
1581 1581 delims = delims.translate(None, self.readline_remove_delims)
1582 1582 delims = delims.replace(ESC_MAGIC, '')
1583 1583 readline.set_completer_delims(delims)
1584 1584 # otherwise we end up with a monster history after a while:
1585 1585 readline.set_history_length(self.history_length)
1586 1586
1587 1587 self.refill_readline_hist()
1588 1588 self.readline_no_record = ReadlineNoRecord(self)
1589 1589
1590 1590 # Configure auto-indent for all platforms
1591 1591 self.set_autoindent(self.autoindent)
1592 1592
1593 1593 def refill_readline_hist(self):
1594 1594 # Load the last 1000 lines from history
1595 1595 self.readline.clear_history()
1596 1596 stdin_encoding = sys.stdin.encoding or "utf-8"
1597 1597 for _, _, cell in self.history_manager.get_tail(1000,
1598 1598 include_latest=True):
1599 1599 if cell.strip(): # Ignore blank lines
1600 1600 for line in cell.splitlines():
1601 1601 self.readline.add_history(line.encode(stdin_encoding))
1602 1602
1603 1603 def set_next_input(self, s):
1604 1604 """ Sets the 'default' input string for the next command line.
1605 1605
1606 1606 Requires readline.
1607 1607
1608 1608 Example:
1609 1609
1610 1610 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1611 1611 [D:\ipython]|2> Hello Word_ # cursor is here
1612 1612 """
1613 1613
1614 1614 self.rl_next_input = s
1615 1615
1616 1616 # Maybe move this to the terminal subclass?
1617 1617 def pre_readline(self):
1618 1618 """readline hook to be used at the start of each line.
1619 1619
1620 1620 Currently it handles auto-indent only."""
1621 1621
1622 1622 if self.rl_do_indent:
1623 1623 self.readline.insert_text(self._indent_current_str())
1624 1624 if self.rl_next_input is not None:
1625 1625 self.readline.insert_text(self.rl_next_input)
1626 1626 self.rl_next_input = None
1627 1627
1628 1628 def _indent_current_str(self):
1629 1629 """return the current level of indentation as a string"""
1630 1630 return self.input_splitter.indent_spaces * ' '
1631 1631
1632 1632 #-------------------------------------------------------------------------
1633 1633 # Things related to text completion
1634 1634 #-------------------------------------------------------------------------
1635 1635
1636 1636 def init_completer(self):
1637 1637 """Initialize the completion machinery.
1638 1638
1639 1639 This creates completion machinery that can be used by client code,
1640 1640 either interactively in-process (typically triggered by the readline
1641 1641 library), programatically (such as in test suites) or out-of-prcess
1642 1642 (typically over the network by remote frontends).
1643 1643 """
1644 1644 from IPython.core.completer import IPCompleter
1645 1645 from IPython.core.completerlib import (module_completer,
1646 1646 magic_run_completer, cd_completer)
1647 1647
1648 1648 self.Completer = IPCompleter(self,
1649 1649 self.user_ns,
1650 1650 self.user_global_ns,
1651 1651 self.readline_omit__names,
1652 1652 self.alias_manager.alias_table,
1653 1653 self.has_readline)
1654 1654
1655 1655 # Add custom completers to the basic ones built into IPCompleter
1656 1656 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1657 1657 self.strdispatchers['complete_command'] = sdisp
1658 1658 self.Completer.custom_completers = sdisp
1659 1659
1660 1660 self.set_hook('complete_command', module_completer, str_key = 'import')
1661 1661 self.set_hook('complete_command', module_completer, str_key = 'from')
1662 1662 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1663 1663 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1664 1664
1665 1665 # Only configure readline if we truly are using readline. IPython can
1666 1666 # do tab-completion over the network, in GUIs, etc, where readline
1667 1667 # itself may be absent
1668 1668 if self.has_readline:
1669 1669 self.set_readline_completer()
1670 1670
1671 1671 def complete(self, text, line=None, cursor_pos=None):
1672 1672 """Return the completed text and a list of completions.
1673 1673
1674 1674 Parameters
1675 1675 ----------
1676 1676
1677 1677 text : string
1678 1678 A string of text to be completed on. It can be given as empty and
1679 1679 instead a line/position pair are given. In this case, the
1680 1680 completer itself will split the line like readline does.
1681 1681
1682 1682 line : string, optional
1683 1683 The complete line that text is part of.
1684 1684
1685 1685 cursor_pos : int, optional
1686 1686 The position of the cursor on the input line.
1687 1687
1688 1688 Returns
1689 1689 -------
1690 1690 text : string
1691 1691 The actual text that was completed.
1692 1692
1693 1693 matches : list
1694 1694 A sorted list with all possible completions.
1695 1695
1696 1696 The optional arguments allow the completion to take more context into
1697 1697 account, and are part of the low-level completion API.
1698 1698
1699 1699 This is a wrapper around the completion mechanism, similar to what
1700 1700 readline does at the command line when the TAB key is hit. By
1701 1701 exposing it as a method, it can be used by other non-readline
1702 1702 environments (such as GUIs) for text completion.
1703 1703
1704 1704 Simple usage example:
1705 1705
1706 1706 In [1]: x = 'hello'
1707 1707
1708 1708 In [2]: _ip.complete('x.l')
1709 1709 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1710 1710 """
1711 1711
1712 1712 # Inject names into __builtin__ so we can complete on the added names.
1713 1713 with self.builtin_trap:
1714 1714 return self.Completer.complete(text, line, cursor_pos)
1715 1715
1716 1716 def set_custom_completer(self, completer, pos=0):
1717 1717 """Adds a new custom completer function.
1718 1718
1719 1719 The position argument (defaults to 0) is the index in the completers
1720 1720 list where you want the completer to be inserted."""
1721 1721
1722 1722 newcomp = types.MethodType(completer,self.Completer)
1723 1723 self.Completer.matchers.insert(pos,newcomp)
1724 1724
1725 1725 def set_readline_completer(self):
1726 1726 """Reset readline's completer to be our own."""
1727 1727 self.readline.set_completer(self.Completer.rlcomplete)
1728 1728
1729 1729 def set_completer_frame(self, frame=None):
1730 1730 """Set the frame of the completer."""
1731 1731 if frame:
1732 1732 self.Completer.namespace = frame.f_locals
1733 1733 self.Completer.global_namespace = frame.f_globals
1734 1734 else:
1735 1735 self.Completer.namespace = self.user_ns
1736 1736 self.Completer.global_namespace = self.user_global_ns
1737 1737
1738 1738 #-------------------------------------------------------------------------
1739 1739 # Things related to magics
1740 1740 #-------------------------------------------------------------------------
1741 1741
1742 1742 def init_magics(self):
1743 1743 # FIXME: Move the color initialization to the DisplayHook, which
1744 1744 # should be split into a prompt manager and displayhook. We probably
1745 1745 # even need a centralize colors management object.
1746 1746 self.magic_colors(self.colors)
1747 1747 # History was moved to a separate module
1748 1748 from . import history
1749 1749 history.init_ipython(self)
1750 1750
1751 1751 def magic(self,arg_s):
1752 1752 """Call a magic function by name.
1753 1753
1754 1754 Input: a string containing the name of the magic function to call and
1755 1755 any additional arguments to be passed to the magic.
1756 1756
1757 1757 magic('name -opt foo bar') is equivalent to typing at the ipython
1758 1758 prompt:
1759 1759
1760 1760 In[1]: %name -opt foo bar
1761 1761
1762 1762 To call a magic without arguments, simply use magic('name').
1763 1763
1764 1764 This provides a proper Python function to call IPython's magics in any
1765 1765 valid Python code you can type at the interpreter, including loops and
1766 1766 compound statements.
1767 1767 """
1768 1768 args = arg_s.split(' ',1)
1769 1769 magic_name = args[0]
1770 1770 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1771 1771
1772 1772 try:
1773 1773 magic_args = args[1]
1774 1774 except IndexError:
1775 1775 magic_args = ''
1776 1776 fn = getattr(self,'magic_'+magic_name,None)
1777 1777 if fn is None:
1778 1778 error("Magic function `%s` not found." % magic_name)
1779 1779 else:
1780 1780 magic_args = self.var_expand(magic_args,1)
1781 1781 # Grab local namespace if we need it:
1782 1782 if getattr(fn, "needs_local_scope", False):
1783 1783 self._magic_locals = sys._getframe(1).f_locals
1784 1784 with self.builtin_trap:
1785 1785 result = fn(magic_args)
1786 1786 # Ensure we're not keeping object references around:
1787 1787 self._magic_locals = {}
1788 1788 return result
1789 1789
1790 1790 def define_magic(self, magicname, func):
1791 1791 """Expose own function as magic function for ipython
1792 1792
1793 1793 def foo_impl(self,parameter_s=''):
1794 1794 'My very own magic!. (Use docstrings, IPython reads them).'
1795 1795 print 'Magic function. Passed parameter is between < >:'
1796 1796 print '<%s>' % parameter_s
1797 1797 print 'The self object is:',self
1798 1798
1799 1799 self.define_magic('foo',foo_impl)
1800 1800 """
1801 1801
1802 1802 import new
1803 1803 im = types.MethodType(func,self)
1804 1804 old = getattr(self, "magic_" + magicname, None)
1805 1805 setattr(self, "magic_" + magicname, im)
1806 1806 return old
1807 1807
1808 1808 #-------------------------------------------------------------------------
1809 1809 # Things related to macros
1810 1810 #-------------------------------------------------------------------------
1811 1811
1812 1812 def define_macro(self, name, themacro):
1813 1813 """Define a new macro
1814 1814
1815 1815 Parameters
1816 1816 ----------
1817 1817 name : str
1818 1818 The name of the macro.
1819 1819 themacro : str or Macro
1820 1820 The action to do upon invoking the macro. If a string, a new
1821 1821 Macro object is created by passing the string to it.
1822 1822 """
1823 1823
1824 1824 from IPython.core import macro
1825 1825
1826 1826 if isinstance(themacro, basestring):
1827 1827 themacro = macro.Macro(themacro)
1828 1828 if not isinstance(themacro, macro.Macro):
1829 1829 raise ValueError('A macro must be a string or a Macro instance.')
1830 1830 self.user_ns[name] = themacro
1831 1831
1832 1832 #-------------------------------------------------------------------------
1833 1833 # Things related to the running of system commands
1834 1834 #-------------------------------------------------------------------------
1835 1835
1836 1836 def system(self, cmd):
1837 1837 """Call the given cmd in a subprocess.
1838 1838
1839 1839 Parameters
1840 1840 ----------
1841 1841 cmd : str
1842 1842 Command to execute (can not end in '&', as bacground processes are
1843 1843 not supported.
1844 1844 """
1845 1845 # We do not support backgrounding processes because we either use
1846 1846 # pexpect or pipes to read from. Users can always just call
1847 1847 # os.system() if they really want a background process.
1848 1848 if cmd.endswith('&'):
1849 1849 raise OSError("Background processes not supported.")
1850 1850
1851 1851 return system(self.var_expand(cmd, depth=2))
1852 1852
1853 1853 def getoutput(self, cmd, split=True):
1854 1854 """Get output (possibly including stderr) from a subprocess.
1855 1855
1856 1856 Parameters
1857 1857 ----------
1858 1858 cmd : str
1859 1859 Command to execute (can not end in '&', as background processes are
1860 1860 not supported.
1861 1861 split : bool, optional
1862 1862
1863 1863 If True, split the output into an IPython SList. Otherwise, an
1864 1864 IPython LSString is returned. These are objects similar to normal
1865 1865 lists and strings, with a few convenience attributes for easier
1866 1866 manipulation of line-based output. You can use '?' on them for
1867 1867 details.
1868 1868 """
1869 1869 if cmd.endswith('&'):
1870 1870 raise OSError("Background processes not supported.")
1871 1871 out = getoutput(self.var_expand(cmd, depth=2))
1872 1872 if split:
1873 1873 out = SList(out.splitlines())
1874 1874 else:
1875 1875 out = LSString(out)
1876 1876 return out
1877 1877
1878 1878 #-------------------------------------------------------------------------
1879 1879 # Things related to aliases
1880 1880 #-------------------------------------------------------------------------
1881 1881
1882 1882 def init_alias(self):
1883 1883 self.alias_manager = AliasManager(shell=self, config=self.config)
1884 1884 self.ns_table['alias'] = self.alias_manager.alias_table,
1885 1885
1886 1886 #-------------------------------------------------------------------------
1887 1887 # Things related to extensions and plugins
1888 1888 #-------------------------------------------------------------------------
1889 1889
1890 1890 def init_extension_manager(self):
1891 1891 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1892 1892
1893 1893 def init_plugin_manager(self):
1894 1894 self.plugin_manager = PluginManager(config=self.config)
1895 1895
1896 1896 #-------------------------------------------------------------------------
1897 1897 # Things related to payloads
1898 1898 #-------------------------------------------------------------------------
1899 1899
1900 1900 def init_payload(self):
1901 1901 self.payload_manager = PayloadManager(config=self.config)
1902 1902
1903 1903 #-------------------------------------------------------------------------
1904 1904 # Things related to the prefilter
1905 1905 #-------------------------------------------------------------------------
1906 1906
1907 1907 def init_prefilter(self):
1908 1908 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1909 1909 # Ultimately this will be refactored in the new interpreter code, but
1910 1910 # for now, we should expose the main prefilter method (there's legacy
1911 1911 # code out there that may rely on this).
1912 1912 self.prefilter = self.prefilter_manager.prefilter_lines
1913 1913
1914 1914 def auto_rewrite_input(self, cmd):
1915 1915 """Print to the screen the rewritten form of the user's command.
1916 1916
1917 1917 This shows visual feedback by rewriting input lines that cause
1918 1918 automatic calling to kick in, like::
1919 1919
1920 1920 /f x
1921 1921
1922 1922 into::
1923 1923
1924 1924 ------> f(x)
1925 1925
1926 1926 after the user's input prompt. This helps the user understand that the
1927 1927 input line was transformed automatically by IPython.
1928 1928 """
1929 1929 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1930 1930
1931 1931 try:
1932 1932 # plain ascii works better w/ pyreadline, on some machines, so
1933 1933 # we use it and only print uncolored rewrite if we have unicode
1934 1934 rw = str(rw)
1935 1935 print >> IPython.utils.io.Term.cout, rw
1936 1936 except UnicodeEncodeError:
1937 1937 print "------> " + cmd
1938 1938
1939 1939 #-------------------------------------------------------------------------
1940 1940 # Things related to extracting values/expressions from kernel and user_ns
1941 1941 #-------------------------------------------------------------------------
1942 1942
1943 1943 def _simple_error(self):
1944 1944 etype, value = sys.exc_info()[:2]
1945 1945 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
1946 1946
1947 1947 def user_variables(self, names):
1948 1948 """Get a list of variable names from the user's namespace.
1949 1949
1950 1950 Parameters
1951 1951 ----------
1952 1952 names : list of strings
1953 1953 A list of names of variables to be read from the user namespace.
1954 1954
1955 1955 Returns
1956 1956 -------
1957 1957 A dict, keyed by the input names and with the repr() of each value.
1958 1958 """
1959 1959 out = {}
1960 1960 user_ns = self.user_ns
1961 1961 for varname in names:
1962 1962 try:
1963 1963 value = repr(user_ns[varname])
1964 1964 except:
1965 1965 value = self._simple_error()
1966 1966 out[varname] = value
1967 1967 return out
1968 1968
1969 1969 def user_expressions(self, expressions):
1970 1970 """Evaluate a dict of expressions in the user's namespace.
1971 1971
1972 1972 Parameters
1973 1973 ----------
1974 1974 expressions : dict
1975 1975 A dict with string keys and string values. The expression values
1976 1976 should be valid Python expressions, each of which will be evaluated
1977 1977 in the user namespace.
1978 1978
1979 1979 Returns
1980 1980 -------
1981 1981 A dict, keyed like the input expressions dict, with the repr() of each
1982 1982 value.
1983 1983 """
1984 1984 out = {}
1985 1985 user_ns = self.user_ns
1986 1986 global_ns = self.user_global_ns
1987 1987 for key, expr in expressions.iteritems():
1988 1988 try:
1989 1989 value = repr(eval(expr, global_ns, user_ns))
1990 1990 except:
1991 1991 value = self._simple_error()
1992 1992 out[key] = value
1993 1993 return out
1994 1994
1995 1995 #-------------------------------------------------------------------------
1996 1996 # Things related to the running of code
1997 1997 #-------------------------------------------------------------------------
1998 1998
1999 1999 def ex(self, cmd):
2000 2000 """Execute a normal python statement in user namespace."""
2001 2001 with self.builtin_trap:
2002 2002 exec cmd in self.user_global_ns, self.user_ns
2003 2003
2004 2004 def ev(self, expr):
2005 2005 """Evaluate python expression expr in user namespace.
2006 2006
2007 2007 Returns the result of evaluation
2008 2008 """
2009 2009 with self.builtin_trap:
2010 2010 return eval(expr, self.user_global_ns, self.user_ns)
2011 2011
2012 2012 def safe_execfile(self, fname, *where, **kw):
2013 2013 """A safe version of the builtin execfile().
2014 2014
2015 2015 This version will never throw an exception, but instead print
2016 2016 helpful error messages to the screen. This only works on pure
2017 2017 Python files with the .py extension.
2018 2018
2019 2019 Parameters
2020 2020 ----------
2021 2021 fname : string
2022 2022 The name of the file to be executed.
2023 2023 where : tuple
2024 2024 One or two namespaces, passed to execfile() as (globals,locals).
2025 2025 If only one is given, it is passed as both.
2026 2026 exit_ignore : bool (False)
2027 2027 If True, then silence SystemExit for non-zero status (it is always
2028 2028 silenced for zero status, as it is so common).
2029 2029 """
2030 2030 kw.setdefault('exit_ignore', False)
2031 2031
2032 2032 fname = os.path.abspath(os.path.expanduser(fname))
2033 2033 # Make sure we have a .py file
2034 2034 if not fname.endswith('.py'):
2035 2035 warn('File must end with .py to be run using execfile: <%s>' % fname)
2036 2036
2037 2037 # Make sure we can open the file
2038 2038 try:
2039 2039 with open(fname) as thefile:
2040 2040 pass
2041 2041 except:
2042 2042 warn('Could not open file <%s> for safe execution.' % fname)
2043 2043 return
2044 2044
2045 2045 # Find things also in current directory. This is needed to mimic the
2046 2046 # behavior of running a script from the system command line, where
2047 2047 # Python inserts the script's directory into sys.path
2048 2048 dname = os.path.dirname(fname)
2049 2049
2050 2050 if isinstance(fname, unicode):
2051 2051 # execfile uses default encoding instead of filesystem encoding
2052 2052 # so unicode filenames will fail
2053 2053 fname = fname.encode(sys.getfilesystemencoding() or sys.getdefaultencoding())
2054 2054
2055 2055 with prepended_to_syspath(dname):
2056 2056 try:
2057 2057 execfile(fname,*where)
2058 2058 except SystemExit, status:
2059 2059 # If the call was made with 0 or None exit status (sys.exit(0)
2060 2060 # or sys.exit() ), don't bother showing a traceback, as both of
2061 2061 # these are considered normal by the OS:
2062 2062 # > python -c'import sys;sys.exit(0)'; echo $?
2063 2063 # 0
2064 2064 # > python -c'import sys;sys.exit()'; echo $?
2065 2065 # 0
2066 2066 # For other exit status, we show the exception unless
2067 2067 # explicitly silenced, but only in short form.
2068 2068 if status.code not in (0, None) and not kw['exit_ignore']:
2069 2069 self.showtraceback(exception_only=True)
2070 2070 except:
2071 2071 self.showtraceback()
2072 2072
2073 2073 def safe_execfile_ipy(self, fname):
2074 2074 """Like safe_execfile, but for .ipy files with IPython syntax.
2075 2075
2076 2076 Parameters
2077 2077 ----------
2078 2078 fname : str
2079 2079 The name of the file to execute. The filename must have a
2080 2080 .ipy extension.
2081 2081 """
2082 2082 fname = os.path.abspath(os.path.expanduser(fname))
2083 2083
2084 2084 # Make sure we have a .py file
2085 2085 if not fname.endswith('.ipy'):
2086 2086 warn('File must end with .py to be run using execfile: <%s>' % fname)
2087 2087
2088 2088 # Make sure we can open the file
2089 2089 try:
2090 2090 with open(fname) as thefile:
2091 2091 pass
2092 2092 except:
2093 2093 warn('Could not open file <%s> for safe execution.' % fname)
2094 2094 return
2095 2095
2096 2096 # Find things also in current directory. This is needed to mimic the
2097 2097 # behavior of running a script from the system command line, where
2098 2098 # Python inserts the script's directory into sys.path
2099 2099 dname = os.path.dirname(fname)
2100 2100
2101 2101 with prepended_to_syspath(dname):
2102 2102 try:
2103 2103 with open(fname) as thefile:
2104 2104 # self.run_cell currently captures all exceptions
2105 2105 # raised in user code. It would be nice if there were
2106 2106 # versions of runlines, execfile that did raise, so
2107 2107 # we could catch the errors.
2108 2108 self.run_cell(thefile.read(), store_history=False)
2109 2109 except:
2110 2110 self.showtraceback()
2111 2111 warn('Unknown failure executing file: <%s>' % fname)
2112 2112
2113 2113 def run_cell(self, raw_cell, store_history=True):
2114 2114 """Run a complete IPython cell.
2115 2115
2116 2116 Parameters
2117 2117 ----------
2118 2118 raw_cell : str
2119 2119 The code (including IPython code such as %magic functions) to run.
2120 2120 store_history : bool
2121 2121 If True, the raw and translated cell will be stored in IPython's
2122 2122 history. For user code calling back into IPython's machinery, this
2123 2123 should be set to False.
2124 2124 """
2125 2125 if (not raw_cell) or raw_cell.isspace():
2126 2126 return
2127 2127
2128 2128 for line in raw_cell.splitlines():
2129 2129 self.input_splitter.push(line)
2130 2130 cell = self.input_splitter.source_reset()
2131 2131
2132 2132 with self.builtin_trap:
2133 2133 if len(cell.splitlines()) == 1:
2134 2134 cell = self.prefilter_manager.prefilter_lines(cell)
2135 2135
2136 2136 # Store raw and processed history
2137 2137 if store_history:
2138 2138 self.history_manager.store_inputs(self.execution_count,
2139 2139 cell, raw_cell)
2140 2140
2141 2141 self.logger.log(cell, raw_cell)
2142 2142
2143 2143 cell_name = self.compile.cache(cell, self.execution_count)
2144 2144
2145 2145 with self.display_trap:
2146 2146 try:
2147 2147 code_ast = ast.parse(cell, filename=cell_name)
2148 2148 except (OverflowError, SyntaxError, ValueError, TypeError,
2149 2149 MemoryError):
2150 2150 self.showsyntaxerror()
2151 2151 self.execution_count += 1
2152 2152 return None
2153
2154 interactivity = 'last' # Last node to be run interactive
2155 if len(cell.splitlines()) == 1:
2156 interactivity = 'all' # Single line; run fully interactive
2157 2153
2158 self.run_ast_nodes(code_ast.body, cell_name, interactivity)
2154 self.run_ast_nodes(code_ast.body, cell_name,
2155 interactivity="last_expr")
2159 2156
2160 2157 # Execute any registered post-execution functions.
2161 2158 for func, status in self._post_execute.iteritems():
2162 2159 if not status:
2163 2160 continue
2164 2161 try:
2165 2162 func()
2166 2163 except:
2167 2164 self.showtraceback()
2168 2165 # Deactivate failing function
2169 2166 self._post_execute[func] = False
2170 2167
2171 2168 if store_history:
2172 2169 # Write output to the database. Does nothing unless
2173 2170 # history output logging is enabled.
2174 2171 self.history_manager.store_output(self.execution_count)
2175 2172 # Each cell is a *single* input, regardless of how many lines it has
2176 2173 self.execution_count += 1
2177 2174
2178 def run_ast_nodes(self, nodelist, cell_name, interactivity='last'):
2175 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'):
2179 2176 """Run a sequence of AST nodes. The execution mode depends on the
2180 2177 interactivity parameter.
2181 2178
2182 2179 Parameters
2183 2180 ----------
2184 2181 nodelist : list
2185 2182 A sequence of AST nodes to run.
2186 2183 cell_name : str
2187 2184 Will be passed to the compiler as the filename of the cell. Typically
2188 2185 the value returned by ip.compile.cache(cell).
2189 2186 interactivity : str
2190 'all', 'last' or 'none', specifying which nodes should be run
2191 interactively (displaying output from expressions). Other values for
2192 this parameter will raise a ValueError.
2187 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2188 run interactively (displaying output from expressions). 'last_expr'
2189 will run the last node interactively only if it is an expression (i.e.
2190 expressions in loops or other blocks are not displayed. Other values
2191 for this parameter will raise a ValueError.
2193 2192 """
2194 2193 if not nodelist:
2195 2194 return
2196 2195
2196 if interactivity == 'last_expr':
2197 if isinstance(nodelist[-1], ast.Expr):
2198 interactivity = "last"
2199 else:
2200 interactivity = "none"
2201
2197 2202 if interactivity == 'none':
2198 2203 to_run_exec, to_run_interactive = nodelist, []
2199 2204 elif interactivity == 'last':
2200 2205 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2201 2206 elif interactivity == 'all':
2202 2207 to_run_exec, to_run_interactive = [], nodelist
2203 2208 else:
2204 2209 raise ValueError("Interactivity was %r" % interactivity)
2205 2210
2206 2211 exec_count = self.execution_count
2207 2212
2208 2213 for i, node in enumerate(to_run_exec):
2209 2214 mod = ast.Module([node])
2210 2215 code = self.compile(mod, cell_name, "exec")
2211 2216 if self.run_code(code):
2212 2217 return True
2213 2218
2214 2219 for i, node in enumerate(to_run_interactive):
2215 2220 mod = ast.Interactive([node])
2216 2221 code = self.compile(mod, cell_name, "single")
2217 2222 if self.run_code(code):
2218 2223 return True
2219 2224
2220 2225 return False
2221 2226
2222 2227
2223 2228 # PENDING REMOVAL: this method is slated for deletion, once our new
2224 2229 # input logic has been 100% moved to frontends and is stable.
2225 2230 def runlines(self, lines, clean=False):
2226 2231 """Run a string of one or more lines of source.
2227 2232
2228 2233 This method is capable of running a string containing multiple source
2229 2234 lines, as if they had been entered at the IPython prompt. Since it
2230 2235 exposes IPython's processing machinery, the given strings can contain
2231 2236 magic calls (%magic), special shell access (!cmd), etc.
2232 2237 """
2233 2238
2234 2239 if not isinstance(lines, (list, tuple)):
2235 2240 lines = lines.splitlines()
2236 2241
2237 2242 if clean:
2238 2243 lines = self._cleanup_ipy_script(lines)
2239 2244
2240 2245 # We must start with a clean buffer, in case this is run from an
2241 2246 # interactive IPython session (via a magic, for example).
2242 2247 self.reset_buffer()
2243 2248
2244 2249 # Since we will prefilter all lines, store the user's raw input too
2245 2250 # before we apply any transformations
2246 2251 self.buffer_raw[:] = [ l+'\n' for l in lines]
2247 2252
2248 2253 more = False
2249 2254 prefilter_lines = self.prefilter_manager.prefilter_lines
2250 2255 with nested(self.builtin_trap, self.display_trap):
2251 2256 for line in lines:
2252 2257 # skip blank lines so we don't mess up the prompt counter, but
2253 2258 # do NOT skip even a blank line if we are in a code block (more
2254 2259 # is true)
2255 2260
2256 2261 if line or more:
2257 2262 more = self.push_line(prefilter_lines(line, more))
2258 2263 # IPython's run_source returns None if there was an error
2259 2264 # compiling the code. This allows us to stop processing
2260 2265 # right away, so the user gets the error message at the
2261 2266 # right place.
2262 2267 if more is None:
2263 2268 break
2264 2269 # final newline in case the input didn't have it, so that the code
2265 2270 # actually does get executed
2266 2271 if more:
2267 2272 self.push_line('\n')
2268 2273
2269 2274 def run_source(self, source, filename=None, symbol='single'):
2270 2275 """Compile and run some source in the interpreter.
2271 2276
2272 2277 Arguments are as for compile_command().
2273 2278
2274 2279 One several things can happen:
2275 2280
2276 2281 1) The input is incorrect; compile_command() raised an
2277 2282 exception (SyntaxError or OverflowError). A syntax traceback
2278 2283 will be printed by calling the showsyntaxerror() method.
2279 2284
2280 2285 2) The input is incomplete, and more input is required;
2281 2286 compile_command() returned None. Nothing happens.
2282 2287
2283 2288 3) The input is complete; compile_command() returned a code
2284 2289 object. The code is executed by calling self.run_code() (which
2285 2290 also handles run-time exceptions, except for SystemExit).
2286 2291
2287 2292 The return value is:
2288 2293
2289 2294 - True in case 2
2290 2295
2291 2296 - False in the other cases, unless an exception is raised, where
2292 2297 None is returned instead. This can be used by external callers to
2293 2298 know whether to continue feeding input or not.
2294 2299
2295 2300 The return value can be used to decide whether to use sys.ps1 or
2296 2301 sys.ps2 to prompt the next line."""
2297 2302
2298 2303 # We need to ensure that the source is unicode from here on.
2299 2304 if type(source)==str:
2300 2305 usource = source.decode(self.stdin_encoding)
2301 2306 else:
2302 2307 usource = source
2303 2308
2304 2309 try:
2305 2310 code_name = self.compile.cache(usource, self.execution_count)
2306 2311 code = self.compile(usource, code_name, symbol)
2307 2312 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2308 2313 # Case 1
2309 2314 self.showsyntaxerror(filename)
2310 2315 return None
2311 2316
2312 2317 if code is None:
2313 2318 # Case 2
2314 2319 return True
2315 2320
2316 2321 # Case 3
2317 2322 # now actually execute the code object
2318 2323 if not self.run_code(code):
2319 2324 return False
2320 2325 else:
2321 2326 return None
2322 2327
2323 2328 # For backwards compatibility
2324 2329 runsource = run_source
2325 2330
2326 2331 def run_code(self, code_obj):
2327 2332 """Execute a code object.
2328 2333
2329 2334 When an exception occurs, self.showtraceback() is called to display a
2330 2335 traceback.
2331 2336
2332 2337 Parameters
2333 2338 ----------
2334 2339 code_obj : code object
2335 2340 A compiled code object, to be executed
2336 2341 post_execute : bool [default: True]
2337 2342 whether to call post_execute hooks after this particular execution.
2338 2343
2339 2344 Returns
2340 2345 -------
2341 2346 False : successful execution.
2342 2347 True : an error occurred.
2343 2348 """
2344 2349
2345 2350 # Set our own excepthook in case the user code tries to call it
2346 2351 # directly, so that the IPython crash handler doesn't get triggered
2347 2352 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2348 2353
2349 2354 # we save the original sys.excepthook in the instance, in case config
2350 2355 # code (such as magics) needs access to it.
2351 2356 self.sys_excepthook = old_excepthook
2352 2357 outflag = 1 # happens in more places, so it's easier as default
2353 2358 try:
2354 2359 try:
2355 2360 self.hooks.pre_run_code_hook()
2356 2361 #rprint('Running code', repr(code_obj)) # dbg
2357 2362 exec code_obj in self.user_global_ns, self.user_ns
2358 2363 finally:
2359 2364 # Reset our crash handler in place
2360 2365 sys.excepthook = old_excepthook
2361 2366 except SystemExit:
2362 2367 self.reset_buffer()
2363 2368 self.showtraceback(exception_only=True)
2364 2369 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2365 2370 except self.custom_exceptions:
2366 2371 etype,value,tb = sys.exc_info()
2367 2372 self.CustomTB(etype,value,tb)
2368 2373 except:
2369 2374 self.showtraceback()
2370 2375 else:
2371 2376 outflag = 0
2372 2377 if softspace(sys.stdout, 0):
2373 2378 print
2374 2379
2375 2380 return outflag
2376 2381
2377 2382 # For backwards compatibility
2378 2383 runcode = run_code
2379 2384
2380 2385 # PENDING REMOVAL: this method is slated for deletion, once our new
2381 2386 # input logic has been 100% moved to frontends and is stable.
2382 2387 def push_line(self, line):
2383 2388 """Push a line to the interpreter.
2384 2389
2385 2390 The line should not have a trailing newline; it may have
2386 2391 internal newlines. The line is appended to a buffer and the
2387 2392 interpreter's run_source() method is called with the
2388 2393 concatenated contents of the buffer as source. If this
2389 2394 indicates that the command was executed or invalid, the buffer
2390 2395 is reset; otherwise, the command is incomplete, and the buffer
2391 2396 is left as it was after the line was appended. The return
2392 2397 value is 1 if more input is required, 0 if the line was dealt
2393 2398 with in some way (this is the same as run_source()).
2394 2399 """
2395 2400
2396 2401 # autoindent management should be done here, and not in the
2397 2402 # interactive loop, since that one is only seen by keyboard input. We
2398 2403 # need this done correctly even for code run via runlines (which uses
2399 2404 # push).
2400 2405
2401 2406 #print 'push line: <%s>' % line # dbg
2402 2407 self.buffer.append(line)
2403 2408 full_source = '\n'.join(self.buffer)
2404 2409 more = self.run_source(full_source, self.filename)
2405 2410 if not more:
2406 2411 self.history_manager.store_inputs(self.execution_count,
2407 2412 '\n'.join(self.buffer_raw), full_source)
2408 2413 self.reset_buffer()
2409 2414 self.execution_count += 1
2410 2415 return more
2411 2416
2412 2417 def reset_buffer(self):
2413 2418 """Reset the input buffer."""
2414 2419 self.buffer[:] = []
2415 2420 self.buffer_raw[:] = []
2416 2421 self.input_splitter.reset()
2417 2422
2418 2423 # For backwards compatibility
2419 2424 resetbuffer = reset_buffer
2420 2425
2421 2426 def _is_secondary_block_start(self, s):
2422 2427 if not s.endswith(':'):
2423 2428 return False
2424 2429 if (s.startswith('elif') or
2425 2430 s.startswith('else') or
2426 2431 s.startswith('except') or
2427 2432 s.startswith('finally')):
2428 2433 return True
2429 2434
2430 2435 def _cleanup_ipy_script(self, script):
2431 2436 """Make a script safe for self.runlines()
2432 2437
2433 2438 Currently, IPython is lines based, with blocks being detected by
2434 2439 empty lines. This is a problem for block based scripts that may
2435 2440 not have empty lines after blocks. This script adds those empty
2436 2441 lines to make scripts safe for running in the current line based
2437 2442 IPython.
2438 2443 """
2439 2444 res = []
2440 2445 lines = script.splitlines()
2441 2446 level = 0
2442 2447
2443 2448 for l in lines:
2444 2449 lstripped = l.lstrip()
2445 2450 stripped = l.strip()
2446 2451 if not stripped:
2447 2452 continue
2448 2453 newlevel = len(l) - len(lstripped)
2449 2454 if level > 0 and newlevel == 0 and \
2450 2455 not self._is_secondary_block_start(stripped):
2451 2456 # add empty line
2452 2457 res.append('')
2453 2458 res.append(l)
2454 2459 level = newlevel
2455 2460
2456 2461 return '\n'.join(res) + '\n'
2457 2462
2458 2463 #-------------------------------------------------------------------------
2459 2464 # Things related to GUI support and pylab
2460 2465 #-------------------------------------------------------------------------
2461 2466
2462 2467 def enable_pylab(self, gui=None):
2463 2468 raise NotImplementedError('Implement enable_pylab in a subclass')
2464 2469
2465 2470 #-------------------------------------------------------------------------
2466 2471 # Utilities
2467 2472 #-------------------------------------------------------------------------
2468 2473
2469 2474 def var_expand(self,cmd,depth=0):
2470 2475 """Expand python variables in a string.
2471 2476
2472 2477 The depth argument indicates how many frames above the caller should
2473 2478 be walked to look for the local namespace where to expand variables.
2474 2479
2475 2480 The global namespace for expansion is always the user's interactive
2476 2481 namespace.
2477 2482 """
2478 2483 res = ItplNS(cmd, self.user_ns, # globals
2479 2484 # Skip our own frame in searching for locals:
2480 2485 sys._getframe(depth+1).f_locals # locals
2481 2486 )
2482 2487 return str(res).decode(res.codec)
2483 2488
2484 2489 def mktempfile(self, data=None, prefix='ipython_edit_'):
2485 2490 """Make a new tempfile and return its filename.
2486 2491
2487 2492 This makes a call to tempfile.mktemp, but it registers the created
2488 2493 filename internally so ipython cleans it up at exit time.
2489 2494
2490 2495 Optional inputs:
2491 2496
2492 2497 - data(None): if data is given, it gets written out to the temp file
2493 2498 immediately, and the file is closed again."""
2494 2499
2495 2500 filename = tempfile.mktemp('.py', prefix)
2496 2501 self.tempfiles.append(filename)
2497 2502
2498 2503 if data:
2499 2504 tmp_file = open(filename,'w')
2500 2505 tmp_file.write(data)
2501 2506 tmp_file.close()
2502 2507 return filename
2503 2508
2504 2509 # TODO: This should be removed when Term is refactored.
2505 2510 def write(self,data):
2506 2511 """Write a string to the default output"""
2507 2512 io.Term.cout.write(data)
2508 2513
2509 2514 # TODO: This should be removed when Term is refactored.
2510 2515 def write_err(self,data):
2511 2516 """Write a string to the default error output"""
2512 2517 io.Term.cerr.write(data)
2513 2518
2514 2519 def ask_yes_no(self,prompt,default=True):
2515 2520 if self.quiet:
2516 2521 return True
2517 2522 return ask_yes_no(prompt,default)
2518 2523
2519 2524 def show_usage(self):
2520 2525 """Show a usage message"""
2521 2526 page.page(IPython.core.usage.interactive_usage)
2522 2527
2523 2528 def find_user_code(self, target, raw=True):
2524 2529 """Get a code string from history, file, or a string or macro.
2525 2530
2526 2531 This is mainly used by magic functions.
2527 2532
2528 2533 Parameters
2529 2534 ----------
2530 2535 target : str
2531 2536 A string specifying code to retrieve. This will be tried respectively
2532 2537 as: ranges of input history (see %history for syntax), a filename, or
2533 2538 an expression evaluating to a string or Macro in the user namespace.
2534 2539 raw : bool
2535 2540 If true (default), retrieve raw history. Has no effect on the other
2536 2541 retrieval mechanisms.
2537 2542
2538 2543 Returns
2539 2544 -------
2540 2545 A string of code.
2541 2546
2542 2547 ValueError is raised if nothing is found, and TypeError if it evaluates
2543 2548 to an object of another type. In each case, .args[0] is a printable
2544 2549 message.
2545 2550 """
2546 2551 code = self.extract_input_lines(target, raw=raw) # Grab history
2547 2552 if code:
2548 2553 return code
2549 2554 if os.path.isfile(target): # Read file
2550 2555 return open(target, "r").read()
2551 2556
2552 2557 try: # User namespace
2553 2558 codeobj = eval(target, self.user_ns)
2554 2559 except Exception:
2555 2560 raise ValueError(("'%s' was not found in history, as a file, nor in"
2556 2561 " the user namespace.") % target)
2557 2562 if isinstance(codeobj, basestring):
2558 2563 return codeobj
2559 2564 elif isinstance(codeobj, Macro):
2560 2565 return codeobj.value
2561 2566
2562 2567 raise TypeError("%s is neither a string nor a macro." % target,
2563 2568 codeobj)
2564 2569
2565 2570 #-------------------------------------------------------------------------
2566 2571 # Things related to IPython exiting
2567 2572 #-------------------------------------------------------------------------
2568 2573 def atexit_operations(self):
2569 2574 """This will be executed at the time of exit.
2570 2575
2571 2576 Cleanup operations and saving of persistent data that is done
2572 2577 unconditionally by IPython should be performed here.
2573 2578
2574 2579 For things that may depend on startup flags or platform specifics (such
2575 2580 as having readline or not), register a separate atexit function in the
2576 2581 code that has the appropriate information, rather than trying to
2577 2582 clutter
2578 2583 """
2579 2584 # Cleanup all tempfiles left around
2580 2585 for tfile in self.tempfiles:
2581 2586 try:
2582 2587 os.unlink(tfile)
2583 2588 except OSError:
2584 2589 pass
2585 2590
2586 2591 # Close the history session (this stores the end time and line count)
2587 2592 self.history_manager.end_session()
2588 2593
2589 2594 # Clear all user namespaces to release all references cleanly.
2590 2595 self.reset(new_session=False)
2591 2596
2592 2597 # Run user hooks
2593 2598 self.hooks.shutdown_hook()
2594 2599
2595 2600 def cleanup(self):
2596 2601 self.restore_sys_module_state()
2597 2602
2598 2603
2599 2604 class InteractiveShellABC(object):
2600 2605 """An abstract base class for InteractiveShell."""
2601 2606 __metaclass__ = abc.ABCMeta
2602 2607
2603 2608 InteractiveShellABC.register(InteractiveShell)
@@ -1,109 +1,109 b''
1 1 # coding: utf-8
2 2 """Tests for the IPython tab-completion machinery.
3 3 """
4 4 #-----------------------------------------------------------------------------
5 5 # Module imports
6 6 #-----------------------------------------------------------------------------
7 7
8 8 # stdlib
9 9 import os
10 10 import sys
11 11 import unittest
12 12
13 13 # third party
14 14 import nose.tools as nt
15 15
16 16 # our own packages
17 17 from IPython.utils.tempdir import TemporaryDirectory
18 18 from IPython.core.history import HistoryManager, extract_hist_ranges
19 19
20 20 def setUp():
21 21 nt.assert_equal(sys.getdefaultencoding(), "ascii")
22 22
23 23 def test_history():
24 24 ip = get_ipython()
25 25 with TemporaryDirectory() as tmpdir:
26 26 hist_manager_ori = ip.history_manager
27 27 hist_file = os.path.join(tmpdir, 'history.sqlite')
28 28 try:
29 29 ip.history_manager = HistoryManager(shell=ip, hist_file=hist_file)
30 30 hist = ['a=1', 'def f():\n test = 1\n return test', u"b='β‚¬Γ†ΒΎΓ·ΓŸ'"]
31 31 for i, h in enumerate(hist, start=1):
32 32 ip.history_manager.store_inputs(i, h)
33 33
34 34 ip.history_manager.db_log_output = True
35 35 # Doesn't match the input, but we'll just check it's stored.
36 ip.history_manager.output_hist_reprs[3].append("spam")
36 ip.history_manager.output_hist_reprs[3] = "spam"
37 37 ip.history_manager.store_output(3)
38 38
39 39 nt.assert_equal(ip.history_manager.input_hist_raw, [''] + hist)
40 40
41 41
42 42 # New session
43 43 ip.history_manager.reset()
44 44 newcmds = ["z=5","class X(object):\n pass", "k='p'"]
45 45 for i, cmd in enumerate(newcmds, start=1):
46 46 ip.history_manager.store_inputs(i, cmd)
47 47 gothist = ip.history_manager.get_range(start=1, stop=4)
48 48 nt.assert_equal(list(gothist), zip([0,0,0],[1,2,3], newcmds))
49 49 # Previous session:
50 50 gothist = ip.history_manager.get_range(-1, 1, 4)
51 51 nt.assert_equal(list(gothist), zip([1,1,1],[1,2,3], hist))
52 52
53 53 # Check get_hist_tail
54 54 gothist = ip.history_manager.get_tail(4, output=True,
55 55 include_latest=True)
56 expected = [(1, 3, (hist[-1], ["spam"])),
56 expected = [(1, 3, (hist[-1], "spam")),
57 57 (2, 1, (newcmds[0], None)),
58 58 (2, 2, (newcmds[1], None)),
59 59 (2, 3, (newcmds[2], None)),]
60 60 nt.assert_equal(list(gothist), expected)
61 61
62 62 gothist = ip.history_manager.get_tail(2)
63 63 expected = [(2, 1, newcmds[0]),
64 64 (2, 2, newcmds[1])]
65 65 nt.assert_equal(list(gothist), expected)
66 66
67 67 # Check get_hist_search
68 68 gothist = ip.history_manager.search("*test*")
69 69 nt.assert_equal(list(gothist), [(1,2,hist[1])] )
70 70 gothist = ip.history_manager.search("b*", output=True)
71 nt.assert_equal(list(gothist), [(1,3,(hist[2],["spam"]))] )
71 nt.assert_equal(list(gothist), [(1,3,(hist[2],"spam"))] )
72 72
73 73 # Cross testing: check that magic %save can get previous session.
74 74 testfilename = os.path.realpath(os.path.join(tmpdir, "test.py"))
75 75 ip.magic_save(testfilename + " ~1/1-3")
76 76 testfile = open(testfilename, "r")
77 77 nt.assert_equal(testfile.read().decode("utf-8"),
78 78 "# coding: utf-8\n" + "\n".join(hist))
79 79
80 80 # Duplicate line numbers - check that it doesn't crash, and
81 81 # gets a new session
82 82 ip.history_manager.store_inputs(1, "rogue")
83 83 ip.history_manager.writeout_cache()
84 84 nt.assert_equal(ip.history_manager.session_number, 3)
85 85 finally:
86 86 # Restore history manager
87 87 ip.history_manager = hist_manager_ori
88 88
89 89
90 90 def test_extract_hist_ranges():
91 91 instr = "1 2/3 ~4/5-6 ~4/7-~4/9 ~9/2-~7/5"
92 92 expected = [(0, 1, 2), # 0 == current session
93 93 (2, 3, 4),
94 94 (-4, 5, 7),
95 95 (-4, 7, 10),
96 96 (-9, 2, None), # None == to end
97 97 (-8, 1, None),
98 98 (-7, 1, 6)]
99 99 actual = list(extract_hist_ranges(instr))
100 100 nt.assert_equal(actual, expected)
101 101
102 102 def test_magic_rerun():
103 103 """Simple test for %rerun (no args -> rerun last line)"""
104 104 ip = get_ipython()
105 105 ip.run_cell("a = 10")
106 106 ip.run_cell("a += 1")
107 107 nt.assert_equal(ip.user_ns["a"], 11)
108 108 ip.run_cell("%rerun")
109 109 nt.assert_equal(ip.user_ns["a"], 12)
General Comments 0
You need to be logged in to leave comments. Login now