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