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